mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): add relational queries for Redshift Spectrum (#5095)
* feat: add relational queries for Redshift Spectrum * fix(redshift): harden Spectrum relational query preparation Catch RuntimeException during preparation so the client gets an ErrorResponse instead of a dropped connection, skip preparation while the backend discards until Sync, defer schema binding until the transaction commits, make the catalog functions SECURITY DEFINER, and track COMMIT and ROLLBACK from the command tag. * fix(redshift): address review findings on transaction handling in Spectrum relational queries - Undo Glue tables created inside a rolled back transaction (Data API batch and wire proxy) - Keep bindings and Glue tables on ROLLBACK TO SAVEPOINT; only a closed transaction discards them - Report the real transaction status for locally handled simple queries instead of idle - Use a switch expression in BackendResponseCoordinator - Map host.docker.internal into the floci-duck container on Linux * fix(redshift): undo Glue tables across sessions and on rollback to savepoint - Scope staged Glue tables by the backend socket so the proxy rollback finds tables created by another session - Track SAVEPOINT, ROLLBACK TO and RELEASE so a Data API batch undoes only the tables created after the savepoint * fix(redshift): defer Glue undo on rollback to savepoint until the backend confirms and bundle bootstrap catalog in native image * fix(redshift): reject CREATE EXTERNAL TABLE inside a transaction like AWS AWS does not allow CREATE EXTERNAL TABLE inside a transaction block, and a Data API batch runs as one transaction. Return SQLSTATE 25001 instead of staging Glue tables and undoing them on rollback, which removes the savepoint tracking and cross-session undo code. Reuse ExternalTableMaterializer.quote. * fix(redshift): reject CREATE EXTERNAL TABLE in a transaction for legacy schemas too
This commit is contained in:
1 parent
a7e2447a34
commit
950b6fe774
30 files changed
+1773
-68
No files matched your search
+241
@@ -1,9 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.services.glue.model.Database;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatement;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatementParser;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.GlueTableBuilder;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.ExternalCatalogRegistry;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -18,18 +28,36 @@ import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Savepoint;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Map;
|
||||
import org.postgresql.PGStatement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RedshiftSpectrumIntegrationTest.SpectrumProfile.class)
|
||||
class RedshiftSpectrumIntegrationTest {
|
||||
|
||||
public static class SpectrumProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("quarkus.http.test-port", "17866", "floci.base-url", "http://localhost:17866",
|
||||
"floci.docker.resource-namespace", "spectrum-relational-tests");
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
RedshiftService redshiftService;
|
||||
|
||||
@@ -39,6 +67,12 @@ class RedshiftSpectrumIntegrationTest {
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@Inject
|
||||
GlueService glueService;
|
||||
|
||||
@Inject
|
||||
ExternalCatalogRegistry externalRegistry;
|
||||
|
||||
private static final String ROLE_NAME = "SpectrumItRole";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME;
|
||||
private static final String TRUST_POLICY = """
|
||||
@@ -47,6 +81,7 @@ class RedshiftSpectrumIntegrationTest {
|
||||
|
||||
private String clusterId;
|
||||
private String bucket;
|
||||
private String glueDatabase;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
@@ -86,6 +121,200 @@ class RedshiftSpectrumIntegrationTest {
|
||||
s3Service.deleteObject(bucket, "invalid/part-1.csv");
|
||||
s3Service.deleteBucket(bucket);
|
||||
}
|
||||
if (glueDatabase != null) {
|
||||
glueService.deleteDatabase(glueDatabase);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(120)
|
||||
void joinsExternalAndInternalTablesWithAggregation() throws Exception {
|
||||
bucket = "spectrum-relational-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,10\n1,5\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
glueDatabase = "spectrum_relational_" + System.nanoTime();
|
||||
Database database = new Database();
|
||||
database.setName(glueDatabase);
|
||||
glueService.createDatabase(database);
|
||||
clusterId = "it-relational-" + System.nanoTime();
|
||||
Cluster cluster = createClusterWithRole(clusterId);
|
||||
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE '" + glueDatabase
|
||||
+ "' IAM_ROLE '" + ROLE_ARN + "'");
|
||||
String externalDdl = "CREATE EXTERNAL TABLE lake.events (id INTEGER, amount INTEGER) "
|
||||
+ "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE LOCATION 's3://"
|
||||
+ bucket + "/events/'";
|
||||
ExternalStatement.CreateTable external = (ExternalStatement.CreateTable)
|
||||
new ExternalStatementParser().parse(externalDdl).orElseThrow();
|
||||
glueService.createTable(glueDatabase, GlueTableBuilder.toGlueTable(external));
|
||||
statement.execute("CREATE TABLE customers (id INTEGER, country VARCHAR(2))");
|
||||
statement.execute("INSERT INTO customers VALUES (1, 'VN'), (2, 'US')");
|
||||
try (PreparedStatement ddl = connection.prepareStatement("CREATE EXTERNAL SCHEMA rolledback_lake "
|
||||
+ "FROM DATA CATALOG DATABASE '" + glueDatabase + "' IAM_ROLE '" + ROLE_ARN + "'")) {
|
||||
ddl.unwrap(PGStatement.class).setPrepareThreshold(1);
|
||||
assertEquals(0, ddl.getParameterMetaData().getParameterCount());
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
SQLException rejected = assertThrows(SQLException.class, ddl::execute);
|
||||
assertEquals("0A000", rejected.getSQLState());
|
||||
} finally {
|
||||
connection.rollback();
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
assertTrue(externalRegistry.find("000000000000", "000000000000:" + clusterId,
|
||||
"dev", "rolledback_lake").isEmpty());
|
||||
}
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
SQLException rejected = assertThrows(SQLException.class, () -> statement.execute(
|
||||
externalDdl.replace("lake.events", "lake.in_transaction")));
|
||||
assertEquals("25001", rejected.getSQLState());
|
||||
assertTrue(rejected.getMessage().contains("cannot run inside a transaction block"));
|
||||
} finally {
|
||||
connection.rollback();
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
assertThrows(AwsException.class, () -> glueService.getTable(glueDatabase, "in_transaction"));
|
||||
try (PreparedStatement query = connection.prepareStatement("SELECT c.country, SUM(e.amount) AS total "
|
||||
+ "FROM lake.events e JOIN customers c ON c.id=e.id WHERE e.amount > ? "
|
||||
+ "GROUP BY c.country ORDER BY total DESC")) {
|
||||
query.setInt(1, 0);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("VN", rows.getString(1));
|
||||
assertEquals(15L, rows.getLong(2));
|
||||
assertTrue(rows.next());
|
||||
assertEquals("US", rows.getString(1));
|
||||
assertEquals(7L, rows.getLong(2));
|
||||
assertTrue(!rows.next());
|
||||
}
|
||||
query.unwrap(PGStatement.class).setPrepareThreshold(1);
|
||||
statement.execute("CREATE VIEW event_amounts AS SELECT amount FROM lake.events");
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,20\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(20L, rows.getLong(2));
|
||||
}
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,30\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(30L, rows.getLong(2));
|
||||
}
|
||||
}
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(a.amount) FROM lake.events a "
|
||||
+ "JOIN lake.events b ON a.id=b.id HAVING SUM(a.amount)>10 ORDER BY 1 LIMIT 1")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(37L, rows.getLong(1));
|
||||
}
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM event_amounts")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(37L, rows.getLong(1));
|
||||
}
|
||||
connection.setAutoCommit(false);
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,35\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
try (PreparedStatement cursor = connection.prepareStatement("SELECT id, amount FROM lake.events ORDER BY id")) {
|
||||
cursor.setFetchSize(1);
|
||||
try (ResultSet rows = cursor.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(1, rows.getInt(1));
|
||||
try (PreparedStatement another = connection.prepareStatement("SELECT SUM(amount) FROM lake.events");
|
||||
ResultSet sum = another.executeQuery()) {
|
||||
assertTrue(sum.next());
|
||||
assertEquals(42L, sum.getLong(1));
|
||||
}
|
||||
assertTrue(rows.next());
|
||||
assertEquals(2, rows.getInt(1));
|
||||
assertTrue(!rows.next());
|
||||
}
|
||||
}
|
||||
Savepoint beforeReload = connection.setSavepoint();
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,40\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(47L, rows.getLong(1));
|
||||
}
|
||||
connection.rollback(beforeReload);
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(47L, rows.getLong(1));
|
||||
}
|
||||
connection.rollback();
|
||||
connection.setAutoCommit(true);
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(47L, rows.getLong(1));
|
||||
}
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,30\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
String queryId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"ClusterIdentifier":"%s","DbUser":"admin","Database":"dev",
|
||||
"Sql":"SELECT SUM(amount) AS total FROM lake.events"}
|
||||
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
|
||||
assertEquals("FINISHED", RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Status"));
|
||||
Number total = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
|
||||
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue");
|
||||
assertEquals(37L, total.longValue());
|
||||
iamService.updateAssumeRolePolicy(ROLE_NAME, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");
|
||||
try {
|
||||
SQLException denied = assertThrows(SQLException.class,
|
||||
() -> statement.executeQuery("SELECT SUM(amount) FROM lake.events"));
|
||||
assertEquals("42501", denied.getSQLState());
|
||||
} finally {
|
||||
iamService.updateAssumeRolePolicy(ROLE_NAME, TRUST_POLICY);
|
||||
}
|
||||
statement.execute("CREATE USER spectrum_reader PASSWORD 'Password123'");
|
||||
statement.execute("GRANT USAGE ON SCHEMA lake TO spectrum_reader");
|
||||
statement.execute("GRANT SELECT ON lake.events TO spectrum_reader");
|
||||
try (Connection reader = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:"
|
||||
+ cluster.getEndpoint().getPort() + "/dev?socketTimeout=20", "spectrum_reader", "Password123");
|
||||
Statement readerQuery = reader.createStatement();
|
||||
ResultSet rows = readerQuery.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(37L, rows.getLong(1));
|
||||
}
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,40\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
CountDownLatch ready = new CountDownLatch(2);
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
try (ExecutorService queries = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
Future<Long> first = queries.submit(() -> concurrentTotal(cluster, ready, start));
|
||||
Future<Long> second = queries.submit(() -> concurrentTotal(cluster, ready, start));
|
||||
assertTrue(ready.await(20, TimeUnit.SECONDS));
|
||||
start.countDown();
|
||||
assertEquals(47L, first.get(30, TimeUnit.SECONDS));
|
||||
assertEquals(47L, second.get(30, TimeUnit.SECONDS));
|
||||
}
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "bad,40\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT SUM(amount) FROM lake.events"));
|
||||
s3Service.putObject(bucket, "events/part-1.csv", "1,40\n2,7\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(47L, rows.getLong(1));
|
||||
}
|
||||
glueService.deleteTable(glueDatabase, "events");
|
||||
SQLException missing = assertThrows(SQLException.class,
|
||||
() -> statement.executeQuery("SELECT * FROM lake.events"));
|
||||
assertEquals("42P01", missing.getSQLState());
|
||||
try (ResultSet rows = statement.executeQuery("SELECT 1")) {
|
||||
assertTrue(rows.next());
|
||||
}
|
||||
}
|
||||
String deleted = clusterId;
|
||||
redshiftService.deleteCluster(deleted);
|
||||
clusterId = null;
|
||||
assertTrue(externalRegistry.list("000000000000", "000000000000:" + deleted, "dev").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -214,4 +443,16 @@ class RedshiftSpectrumIntegrationTest {
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(url, username, password), Objects::nonNull);
|
||||
}
|
||||
|
||||
private static long concurrentTotal(Cluster cluster, CountDownLatch ready, CountDownLatch start) throws Exception {
|
||||
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
|
||||
PreparedStatement query = connection.prepareStatement("SELECT SUM(amount) FROM lake.events")) {
|
||||
ready.countDown();
|
||||
assertTrue(start.await(20, TimeUnit.SECONDS));
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
return rows.getLong(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -14,6 +14,28 @@ class BackendResponseCoordinatorTest {
|
||||
|
||||
private static final byte[] EMPTY_BODY = new byte[0];
|
||||
|
||||
@Test
|
||||
void beginUpdatesTransactionStateBeforeSync() {
|
||||
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
|
||||
coordinator.register(BackendResponseCoordinator.Operation.EXECUTE, null);
|
||||
coordinator.onBackendFrame('C', new byte[]{'B', 'E', 'G', 'I', 'N', 0});
|
||||
assertEquals('T', coordinator.lastReadyStatus());
|
||||
coordinator.onBackendFrame('C', new byte[]{'R', 'O', 'L', 'L', 'B', 'A', 'C', 'K', 0});
|
||||
assertEquals('T', coordinator.lastReadyStatus());
|
||||
coordinator.onBackendFrame('Z', new byte[]{'I'});
|
||||
assertEquals('I', coordinator.lastReadyStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void commitLeavesTransactionBeforeSync() {
|
||||
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
|
||||
coordinator.register(BackendResponseCoordinator.Operation.EXECUTE, null);
|
||||
coordinator.onBackendFrame('C', new byte[]{'B', 'E', 'G', 'I', 'N', 0});
|
||||
coordinator.register(BackendResponseCoordinator.Operation.EXECUTE, null);
|
||||
coordinator.onBackendFrame('C', new byte[]{'C', 'O', 'M', 'M', 'I', 'T', 0});
|
||||
assertEquals('I', coordinator.lastReadyStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseBindAndDescribeCompleteBeforeExecuteBecomesReady() throws InterruptedException {
|
||||
ExtendedQuerySession session = new ExtendedQuerySession();
|
||||
|
||||
+54
-1
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -11,9 +12,11 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
@@ -26,6 +29,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RedshiftInterceptingBridgeTest {
|
||||
|
||||
@Test
|
||||
void tracksBeginCommandAcrossFragmentedBackendFrames() {
|
||||
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
|
||||
RedshiftInterceptingBridge.WireFrameTracker tracker =
|
||||
new RedshiftInterceptingBridge.WireFrameTracker(coordinator::onBackendFrame);
|
||||
byte[] begin = new byte[]{'C', 0, 0, 0, 10, 'B', 'E', 'G', 'I', 'N', 0};
|
||||
tracker.consume(begin, 0, 7);
|
||||
assertEquals('I', coordinator.lastReadyStatus());
|
||||
tracker.consume(begin, 7, 4);
|
||||
assertEquals('T', coordinator.lastReadyStatus());
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftInterceptingBridgeTest.class);
|
||||
|
||||
private ServerSocket clientListener;
|
||||
@@ -39,6 +54,10 @@ class RedshiftInterceptingBridgeTest {
|
||||
private S3Service s3Stub;
|
||||
|
||||
private void startBridge() throws IOException {
|
||||
startBridge(null);
|
||||
}
|
||||
|
||||
private void startBridge(SpectrumInterceptor spectrumInterceptor) throws IOException {
|
||||
clientListener = new ServerSocket(0);
|
||||
testClientEnd = new Socket("localhost", clientListener.getLocalPort());
|
||||
bridgeClientEnd = clientListener.accept();
|
||||
@@ -49,7 +68,8 @@ class RedshiftInterceptingBridgeTest {
|
||||
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class));
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
|
||||
spectrumInterceptor, "000000000000:c", "dev");
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
@@ -306,6 +326,39 @@ class RedshiftInterceptingBridgeTest {
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(20)
|
||||
void locallyHandledQueryInsideTransactionKeepsTheTransactionStatus() throws Exception {
|
||||
SpectrumInterceptor interceptor = Mockito.mock(SpectrumInterceptor.class);
|
||||
Mockito.when(interceptor.intercept(Mockito.anyString(), Mockito.any(), Mockito.any(Socket.class)))
|
||||
.thenReturn(new SpectrumInterceptor.Decision.Forward(), new SpectrumInterceptor.Decision.Handled());
|
||||
startBridge(interceptor);
|
||||
InputStream fromBridge = testClientEnd.getInputStream();
|
||||
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("BEGIN"));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
assertEquals('Q', nextForwarded().type());
|
||||
writeBackendFrame('C', cString("BEGIN"));
|
||||
writeBackendFrame('Z', new byte[]{'T'});
|
||||
assertEquals('C', fromBridge.read());
|
||||
skipFrameBody(fromBridge);
|
||||
assertEquals('Z', fromBridge.read());
|
||||
skipFrameBody(fromBridge);
|
||||
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("CREATE EXTERNAL TABLE lake.t (id INT)"));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
assertEquals('C', fromBridge.read());
|
||||
skipFrameBody(fromBridge);
|
||||
assertEquals('Z', fromBridge.read());
|
||||
fromBridge.readNBytes(4);
|
||||
assertEquals('T', fromBridge.read());
|
||||
}
|
||||
|
||||
private static void skipFrameBody(InputStream in) throws IOException {
|
||||
int length = ByteBuffer.wrap(in.readNBytes(4)).getInt();
|
||||
in.readNBytes(length - 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pumpsBackendBytesToTheClientUnchanged() throws IOException {
|
||||
startBridge();
|
||||
|
||||
+38
@@ -39,6 +39,7 @@ import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -69,6 +70,12 @@ class ExternalTableMaterializerTest {
|
||||
|
||||
private static final class RecordingBackend implements BackendSql {
|
||||
private final List<String> statements = new ArrayList<>();
|
||||
private boolean publicationAllowed = true;
|
||||
|
||||
@Override
|
||||
public boolean permitsCachePublication() {
|
||||
return publicationAllowed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
@@ -115,6 +122,37 @@ class ExternalTableMaterializerTest {
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void confirmedExtendedCommitPublishesDefinitionsAndFingerprint() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
backend.publicationAllowed = false;
|
||||
materializer.ensureCurrent(backend, session(false), BINDING, "events");
|
||||
materializer.finishCycle(backend, true);
|
||||
RecordingBackend other = new RecordingBackend();
|
||||
assertEquals(ExternalTableMaterializer.Outcome.CURRENT,
|
||||
materializer.ensureCurrent(other, session(false), BINDING, "events"));
|
||||
forceReload();
|
||||
materializer.ensureCurrent(other, session(false), BINDING, "events");
|
||||
assertThat(other.statements.getLast(), containsString("CREATE TABLE IF NOT EXISTS"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendedLoadsAreReusableOnlyWithinTheirOwnCycle() {
|
||||
when(glue.getTable("lake", "events")).thenReturn(csvTable());
|
||||
backend.publicationAllowed = false;
|
||||
assertEquals(ExternalTableMaterializer.Outcome.LOADED,
|
||||
materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
assertEquals(ExternalTableMaterializer.Outcome.CURRENT,
|
||||
materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
RecordingBackend other = new RecordingBackend();
|
||||
other.publicationAllowed = false;
|
||||
assertEquals(ExternalTableMaterializer.Outcome.LOADED,
|
||||
materializer.ensureCurrent(other, session(false), BINDING, "events"));
|
||||
materializer.finishCycle(backend);
|
||||
assertEquals(ExternalTableMaterializer.Outcome.LOADED,
|
||||
materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsThroughAStagingTableAndCachesUnchangedData() {
|
||||
Table table = csvTable();
|
||||
|
||||
+81
@@ -19,6 +19,78 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class PostgresBackendSessionTest {
|
||||
|
||||
@Test
|
||||
void extendedFailureDoesNotWaitForIgnoredCleanupBeforeClientSync() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<String> names = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
String first = "";
|
||||
Frame frame;
|
||||
do {
|
||||
frame = readFrame(socket.getInputStream());
|
||||
if (frame.type() == 'P') {
|
||||
first = new String(frame.body(), StandardCharsets.UTF_8).split("\0", 2)[0];
|
||||
}
|
||||
} while (frame.type() != 'H');
|
||||
send(socket.getOutputStream(), 'E', new byte[]{'C', '4', '2', 'P', '0', '1', 0,
|
||||
'M', 'm', 'i', 's', 's', 'i', 'n', 'g', 0, 0});
|
||||
String second = "";
|
||||
do {
|
||||
frame = readFrame(socket.getInputStream());
|
||||
if (frame.type() == 'P') {
|
||||
second = new String(frame.body(), StandardCharsets.UTF_8).split("\0", 2)[0];
|
||||
}
|
||||
} while (frame.type() != 'H');
|
||||
send(socket.getOutputStream(), 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
return first.equals(second) ? "reused" : "distinct";
|
||||
}
|
||||
});
|
||||
PostgresExtendedBackendSession sql = new PostgresExtendedBackendSession(backend);
|
||||
assertThrows(SpectrumReadException.class, () -> sql.execute("SELECT missing"));
|
||||
SpectrumReadException cleanup = assertThrows(SpectrumReadException.class,
|
||||
() -> sql.execute("DROP TABLE t"));
|
||||
assertEquals("25P02", cleanup.sqlState());
|
||||
sql.onSync();
|
||||
sql.execute("SELECT 1");
|
||||
assertEquals("distinct", names.get());
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendedPreparationClosesOnlyItsNamedObjectsWithoutSyncOrSimpleQuery() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<String> messages = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
StringBuilder types = new StringBuilder();
|
||||
Frame frame;
|
||||
do {
|
||||
frame = readFrame(socket.getInputStream());
|
||||
types.append(frame.type());
|
||||
if (frame.type() == 'P') {
|
||||
assertEquals('f', (char) frame.body()[0]);
|
||||
}
|
||||
} while (frame.type() != 'H');
|
||||
send(socket.getOutputStream(), '1', new byte[0]);
|
||||
send(socket.getOutputStream(), '2', new byte[0]);
|
||||
send(socket.getOutputStream(), 'C', "DO\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
return types.toString();
|
||||
}
|
||||
});
|
||||
new PostgresExtendedBackendSession(backend).execute("CREATE TABLE t(id integer); INSERT INTO t VALUES (1)");
|
||||
assertEquals("PBECCH", messages.get());
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyReadFailureDrainsCopyFailResponseWithoutReplacingOriginalCause() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
@@ -188,4 +260,13 @@ class PostgresBackendSessionTest {
|
||||
|
||||
private record Frame(char type, byte[] body) {
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationFailsFastAfterTheClientsOwnBackendError() {
|
||||
PostgresExtendedBackendSession session = new PostgresExtendedBackendSession(null);
|
||||
session.onBackendError();
|
||||
SpectrumReadException error = assertThrows(SpectrumReadException.class, () -> session.execute("CREATE TABLE t(id INT)"));
|
||||
assertEquals("25P02", error.sqlState());
|
||||
session.onSync();
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class SpectrumQueryPreparationTest {
|
||||
private static final SpectrumSession SESSION = new SpectrumSession("000000000000", "000000000000:c",
|
||||
"dev", List.of(), false);
|
||||
private static final ExternalSchemaBinding BINDING = new ExternalSchemaBinding(SESSION.accountId(),
|
||||
SESSION.clusterKey(), "dev", "lake", "analytics", "arn:aws:iam::000000000000:role/R");
|
||||
private ExternalCatalogRegistry registry;
|
||||
private ExternalTableMaterializer materializer;
|
||||
private BackendSql backend;
|
||||
private SpectrumQueryPreparation preparation;
|
||||
private GlueService glue;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
registry = mock(ExternalCatalogRegistry.class);
|
||||
materializer = mock(ExternalTableMaterializer.class);
|
||||
backend = mock(BackendSql.class);
|
||||
when(registry.list(SESSION.accountId(), SESSION.clusterKey(), "dev")).thenReturn(List.of(BINDING));
|
||||
when(materializer.ensureCurrent(any(), any(), any(), anyString()))
|
||||
.thenReturn(ExternalTableMaterializer.Outcome.CURRENT);
|
||||
glue = mock(GlueService.class);
|
||||
preparation = new SpectrumQueryPreparation(registry, materializer, new ExternalStatementParser(),
|
||||
glue, mock(ExternalMetadataWriter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void glueDdlFailureUsesSqlErrorInsteadOfEscapingTheWireHandler() {
|
||||
doThrow(new AwsException("AlreadyExistsException", "table already exists", 400))
|
||||
.when(glue).createTable(anyString(), any());
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
|
||||
"CREATE EXTERNAL TABLE lake.sales (id INTEGER) STORED AS TEXTFILE LOCATION 's3://bucket/'",
|
||||
SESSION, backend));
|
||||
assertEquals("42P07", error.sqlState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionalSchemaCreateFailsBeforeChangingEitherStore() {
|
||||
SpectrumSession transaction = new SpectrumSession(SESSION.accountId(), SESSION.clusterKey(),
|
||||
SESSION.databaseName(), List.of(), true);
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
|
||||
"CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE 'analytics' IAM_ROLE '"
|
||||
+ BINDING.iamRoleArn() + "'", transaction, backend));
|
||||
assertEquals("0A000", error.sqlState());
|
||||
verifyNoInteractions(glue, backend);
|
||||
verify(registry, never()).bind(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparesDistinctExternalReferences() {
|
||||
assertFalse(preparation.prepare("SELECT a.id, SUM(b.amount) FROM lake.sales a JOIN lake.sales b "
|
||||
+ "ON a.id=b.id JOIN public.customers c ON c.id=a.id GROUP BY a.id ORDER BY a.id", SESSION, backend));
|
||||
verify(materializer).ensureCurrent(backend, SESSION, BINDING, "sales");
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesInternalSqlUntouched() {
|
||||
assertFalse(preparation.prepare("SELECT 'lake.sales' FROM public.customers lake", SESSION, backend));
|
||||
verifyNoInteractions(materializer, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsExternalMutationInCte() {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare(
|
||||
"WITH changed AS (DELETE FROM lake.sales RETURNING *) SELECT * FROM changed", SESSION, backend));
|
||||
assertEquals("0A000", error.sqlState());
|
||||
verifyNoInteractions(materializer, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingGlueTableDoesNotUseCachedRelation() {
|
||||
when(materializer.ensureCurrent(backend, SESSION, BINDING, "sales"))
|
||||
.thenReturn(ExternalTableMaterializer.Outcome.NOT_EXTERNAL);
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () ->
|
||||
preparation.prepare("SELECT * FROM lake.sales", SESSION, backend));
|
||||
assertEquals("42P01", error.sqlState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedSchemaCreateDoesNotPublishBinding() {
|
||||
when(registry.find(anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
doThrow(new SpectrumReadException("58030", "backend unavailable")).when(backend).execute(anyString());
|
||||
assertThrows(SpectrumReadException.class, () -> preparation.prepare(
|
||||
"CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE 'analytics' IAM_ROLE '"
|
||||
+ BINDING.iamRoleArn() + "'", SESSION, backend));
|
||||
verify(registry, never()).bind(any());
|
||||
}
|
||||
|
||||
private static final String CREATE_LAKE = "CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE 'analytics' IAM_ROLE '"
|
||||
+ BINDING.iamRoleArn() + "'";
|
||||
|
||||
@Test
|
||||
void schemaCreatedInClientTransactionIsBoundOnlyWhenItCommits() {
|
||||
when(registry.find(anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(backend.permitsCachePublication()).thenReturn(false);
|
||||
assertTrue(preparation.prepare(CREATE_LAKE, SESSION, backend));
|
||||
verify(registry, never()).bind(any());
|
||||
preparation.finishCycle(backend, true);
|
||||
verify(registry).bind(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void schemaCreatedInRolledBackTransactionIsNeverBound() {
|
||||
when(registry.find(anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(backend.permitsCachePublication()).thenReturn(false);
|
||||
assertTrue(preparation.prepare(CREATE_LAKE, SESSION, backend));
|
||||
preparation.finishCycle(backend);
|
||||
preparation.finishCycle(backend, true);
|
||||
verify(registry, never()).bind(any());
|
||||
}
|
||||
|
||||
private static final SpectrumSession TRANSACTION = new SpectrumSession(SESSION.accountId(), SESSION.clusterKey(),
|
||||
"dev", List.of(), true);
|
||||
private static final String CREATE_SALES =
|
||||
"CREATE EXTERNAL TABLE lake.sales (id INTEGER) STORED AS TEXTFILE LOCATION 's3://bucket/'";
|
||||
|
||||
@Test
|
||||
void transactionalTableCreateIsRejectedBeforeChangingEitherStore() {
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare(CREATE_SALES, TRANSACTION, backend));
|
||||
assertEquals("25001", error.sqlState());
|
||||
assertEquals("CREATE EXTERNAL TABLE cannot run inside a transaction block", error.getMessage());
|
||||
verifyNoInteractions(glue, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionalTableCreateInUnboundSchemaIsRejectedAndRoutedToPreparation() {
|
||||
String legacy = "CREATE EXTERNAL TABLE legacy.sales (id INTEGER) STORED AS TEXTFILE LOCATION 's3://bucket/'";
|
||||
assertTrue(preparation.handlesDdl(legacy, TRANSACTION));
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare(legacy, TRANSACTION, backend));
|
||||
assertEquals("25001", error.sqlState());
|
||||
verifyNoInteractions(glue, backend);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableCreatedOutsideTransactionIsStoredInGlue() {
|
||||
assertTrue(preparation.prepare(CREATE_SALES, SESSION, backend));
|
||||
verify(glue).createTable(eq("analytics"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardingLoadsOnlyDropsPendingLoads() {
|
||||
preparation.discardPendingLoads(backend);
|
||||
verify(materializer).finishCycle(backend);
|
||||
verifyNoInteractions(glue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void schemaCreatedOnAutocommitBackendIsBoundImmediately() {
|
||||
when(registry.find(anyString(), anyString(), anyString(), anyString())).thenReturn(Optional.empty());
|
||||
when(backend.permitsCachePublication()).thenReturn(true);
|
||||
assertTrue(preparation.prepare(CREATE_LAKE, SESSION, backend));
|
||||
verify(registry).bind(any());
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.postgresql.PGConnection;
|
||||
import org.postgresql.copy.CopyManager;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataBackendSqlTest {
|
||||
@Test
|
||||
void usesCallerConnectionWithoutCommittingOrClosingIt() throws Exception {
|
||||
Connection connection = mock(Connection.class);
|
||||
Statement statement = mock(Statement.class);
|
||||
PGConnection pg = mock(PGConnection.class);
|
||||
CopyManager copy = mock(CopyManager.class);
|
||||
when(connection.createStatement()).thenReturn(statement);
|
||||
when(connection.unwrap(PGConnection.class)).thenReturn(pg);
|
||||
when(pg.getCopyAPI()).thenReturn(copy);
|
||||
InputStream data = new ByteArrayInputStream(new byte[]{1});
|
||||
when(copy.copyIn("COPY t FROM STDIN", data)).thenReturn(2L);
|
||||
RedshiftDataBackendSql backend = new RedshiftDataBackendSql(connection);
|
||||
backend.execute("CREATE TABLE t(id INTEGER)");
|
||||
assertEquals(2L, backend.copyIn("COPY t FROM STDIN", data));
|
||||
verify(statement).execute("CREATE TABLE t(id INTEGER)");
|
||||
verify(statement).close();
|
||||
verify(connection, never()).commit();
|
||||
verify(connection, never()).rollback();
|
||||
verify(connection, never()).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesSqlStateOnFailure() throws Exception {
|
||||
Connection connection = mock(Connection.class);
|
||||
when(connection.createStatement()).thenThrow(new SQLException("denied", "42501"));
|
||||
SpectrumReadException error = assertThrows(SpectrumReadException.class,
|
||||
() -> new RedshiftDataBackendSql(connection).execute("SELECT 1"));
|
||||
assertEquals("42501", error.sqlState());
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -69,7 +69,8 @@ class RedshiftDataResourceResolverTest {
|
||||
private static RedshiftServerlessService.WorkgroupTarget workgroupTarget() {
|
||||
return new RedshiftServerlessService.WorkgroupTarget(
|
||||
"arn:aws:redshift-serverless:us-east-1:" + ACCOUNT + ":workgroup/wg-id", "wg-1",
|
||||
"127.0.0.1", 55433, "analytics", "root", "Secret123", "root");
|
||||
"127.0.0.1", 55433, "analytics", "root", "Secret123", "root",
|
||||
List.of("arn:aws:iam::" + ACCOUNT + ":role/Spectrum"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -88,6 +89,10 @@ class RedshiftDataResourceResolverTest {
|
||||
assertEquals("analytics", target.database());
|
||||
assertEquals("root", target.user());
|
||||
assertEquals("Secret123", target.password());
|
||||
assertEquals(ACCOUNT, target.spectrum().accountId());
|
||||
assertEquals(ACCOUNT + ":serverless_us-east-1_wg-1", target.spectrum().clusterKey());
|
||||
assertEquals("analytics", target.spectrum().databaseName());
|
||||
assertEquals(List.of("arn:aws:iam::" + ACCOUNT + ":role/Spectrum"), target.spectrum().iamRoleArns());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+31
-2
@@ -5,6 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
|
||||
import org.h2.Driver;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -14,6 +17,7 @@ import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -22,6 +26,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
|
||||
class RedshiftDataServiceTest {
|
||||
|
||||
@@ -34,6 +42,7 @@ class RedshiftDataServiceTest {
|
||||
private final ObjectMapper om = new ObjectMapper();
|
||||
private String jdbcUrl;
|
||||
private RedshiftDataService service;
|
||||
private SpectrumQueryPreparation preparation;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
@@ -41,13 +50,15 @@ class RedshiftDataServiceTest {
|
||||
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "127.0.0.1", 5439, "dev", "admin", "x"));
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "127.0.0.1", 5439, "dev", "admin", "x",
|
||||
new SpectrumSession("000000000000", "000000000000:wh", "dev", List.of(), false)));
|
||||
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenAnswer(inv -> DriverManager.getConnection(jdbcUrl, "sa", ""));
|
||||
|
||||
preparation = mock(SpectrumQueryPreparation.class);
|
||||
service = new RedshiftDataService(resolver, factory,
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), om);
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), om, preparation);
|
||||
}
|
||||
|
||||
private ObjectNode req(String sql) {
|
||||
@@ -63,6 +74,24 @@ class RedshiftDataServiceTest {
|
||||
return om.createObjectNode().put("Id", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationFailureIsStoredAsFailedStatement() {
|
||||
doThrow(new SpectrumReadException("42501", "S3 access denied")).when(preparation)
|
||||
.prepare(eq("SELECT * FROM lake.events"), any(), any());
|
||||
ObjectNode executed = service.executeStatement(req("SELECT * FROM lake.events"), REGION);
|
||||
ObjectNode described = service.describeStatement(idOf(executed.path("Id").asText()));
|
||||
assertEquals("FAILED", described.path("Status").asText());
|
||||
assertEquals("S3 access denied", described.path("Error").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchPreparationUsesTransactionContext() {
|
||||
ObjectNode request = req("unused");
|
||||
request.putArray("Sqls").add("SELECT 1");
|
||||
service.batchExecuteStatement(request, REGION);
|
||||
verify(preparation).prepare(eq("SELECT 1"), argThat(SpectrumSession::inTransaction), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWorkgroupStatementNamesItsWorkgroupAndOmitsTheClusterIdentifier() {
|
||||
ObjectNode request = om.createObjectNode();
|
||||
|
||||
Reference in new issue
Block a user