feat(redshift): support S3 COPY JSON and manifest, and DynamoDB zero-ETL backfill (#3889)

* feat(redshift): support S3 COPY FORMAT AS JSON 'auto' and MANIFEST

* fix(redshift): resolve column discovery via pg_catalog and guard against empty columns

* feat(redshift): track zero-ETL backfill progress and syncing status

* feat(redshift): backfill existing DynamoDB items into zero-ETL landing table

* test(redshift): prove zero-ETL backfill and syncing-to-active status

* fix(redshift): reject JSON 'auto' COPY without columns over Extended Query clearly

Catalog-based column discovery only runs over the Simple Query protocol, so
a column-less COPY ... FORMAT AS JSON 'auto' sent over Extended Query failed
with an obscure error. Name the cause and remedy in the error, document the
limitation, and run the discovery tests over Simple Query.

* docs(redshift): document zero-ETL DynamoDB backfill and syncing status

* fix(redshift): address review feedback on COPY JSON, manifest and zero-ETL backfill

* fix(redshift): pass user column list as written and clarify syncing status in docs

* fix(redshift): wrap long condition in identifier unquoting

* fix(redshift): keep user columns as written in runCopyFrom and verify backfill account scope

* test(redshift): use assertNotNull for last evaluated key assertion
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-20 00:23:54 -04:00
1 parent 1088187cb3
commit 9379fa1179
16 files changed
+1605 -55

No files matched your search

@@ -1,25 +1,51 @@
package io.github.hectorvent.floci.services.redshift;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@QuarkusTest
class RedshiftDynamoDbZeroEtlConsumerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Inject
DynamoDbService dynamoDbService;
@Test
void writesRecordsAndAdvancesCheckpointOnlyAfterSuccessfulBatch() {
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
Integration integration = integration();
Integration integration = integration("orders");
integration.setBackfillCompleted(true);
DynamoDbStreamRecord record = new DynamoDbStreamRecord();
record.setEventId("event-1");
record.setSequenceNumber("000000000000000000001");
@@ -32,7 +58,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
.thenReturn(record.getSequenceNumber());
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streamService, redshiftService, writer);
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer);
consumer.pollOnce(integration);
verify(writer).createLandingTable(integration.getAccountId(), "warehouse", "floci_zetl_orders");
@@ -41,11 +67,120 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
record.getSequenceNumber(), true, null);
}
private static Integration integration() {
@Test
void backfillsOnePageAtATimeBeforeSwitchingToStreamPolling() {
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-page-" + System.nanoTime();
Integration integration = integration(tableName);
assertFalse(integration.isBackfillCompleted());
// Create table and items in the integration's account scope (111111111111).
// Populate > BATCH_SIZE (100) items so the scan produces a LastEvaluatedKey.
RequestScopes.runAs(integration.getAccountId(), () -> {
dynamoDbService.createTable(tableName,
List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")),
5L, 5L, "us-east-1");
for (int i = 1; i <= 101; i++) {
dynamoDbService.putItem(tableName, itemWithId(String.valueOf(i)), "us-east-1");
}
});
// The table must NOT exist in the default account: this proves the account scope is applied.
assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1"));
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer);
consumer.pollOnce(integration);
assertFalse(integration.isBackfillCompleted());
assertNotNull(integration.getBackfillLastEvaluatedKey());
verify(redshiftService).updateIntegrationBackfillProgress(eq(integration.getAccountId()),
eq(integration.getIntegrationArn()), eq(integration.getBackfillLastEvaluatedKey()), eq(false));
verify(streamService, never()).getShardIterator(any(), any(), any(), any());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<DynamoDbStreamRecord>> captor = ArgumentCaptor.forClass(List.class);
verify(writer).writeBatch(eq(integration.getAccountId()), eq("warehouse"), eq("floci_zetl_orders"),
captor.capture());
assertEquals(100, captor.getValue().size());
DynamoDbStreamRecord written = captor.getValue().get(0);
assertEquals("INSERT", written.getEventName());
assertTrue(written.getEventId().startsWith("backfill#" + integration.getIntegrationArn() + "#"));
}
@Test
void backfillCompletesWhenScanReturnsNoLastEvaluatedKey() {
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-empty-" + System.nanoTime();
Integration integration = integration(tableName);
RequestScopes.runAs(integration.getAccountId(), () -> {
dynamoDbService.createTable(tableName,
List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")),
5L, 5L, "us-east-1");
});
assertThrows(AwsException.class, () -> dynamoDbService.describeTable(tableName, "us-east-1"));
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer);
consumer.pollOnce(integration);
assertTrue(integration.isBackfillCompleted());
verify(redshiftService).updateIntegrationBackfillProgress(integration.getAccountId(),
integration.getIntegrationArn(), null, true);
verify(writer, never()).writeBatch(any(), any(), any(), any());
}
@Test
void sameItemProducesTheSameEventIdAcrossScans() {
DynamoDbStreamService streamService = mock(DynamoDbStreamService.class);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-same-" + System.nanoTime();
Integration integration = integration(tableName);
ObjectNode item = itemWithId("1");
RequestScopes.runAs(integration.getAccountId(), () -> {
dynamoDbService.createTable(tableName,
List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")),
5L, 5L, "us-east-1");
dynamoDbService.putItem(tableName, item, "us-east-1");
});
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streamService, dynamoDbService, redshiftService, writer);
consumer.pollOnce(integration);
integration.setBackfillCompleted(false);
consumer.pollOnce(integration);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<DynamoDbStreamRecord>> captor = ArgumentCaptor.forClass(List.class);
verify(writer, times(2)).writeBatch(any(), any(), any(), captor.capture());
assertEquals(captor.getAllValues().get(0).get(0).getEventId(),
captor.getAllValues().get(1).get(0).getEventId());
}
private static ObjectNode itemWithId(String id) {
ObjectNode item = MAPPER.createObjectNode();
ObjectNode idAttr = MAPPER.createObjectNode();
idAttr.put("S", id);
item.set("id", idAttr);
return item;
}
private static Integration integration(String tableName) {
Integration integration = new Integration();
integration.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:one");
integration.setAccountId("111111111111");
integration.setSourceStreamArn("arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/one");
integration.setSourceStreamArn("arn:aws:dynamodb:us-east-1:111111111111:table/" + tableName + "/stream/one");
integration.setTargetClusterIdentifier("warehouse");
integration.setLandingTableName("floci_zetl_orders");
integration.setPollingEnabled(true);
@@ -1,7 +1,16 @@
package io.github.hectorvent.floci.services.redshift;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.awaitility.Awaitility;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.quarkus.test.junit.QuarkusTest;
@@ -115,11 +124,81 @@ class RedshiftIntegrationsIntegrationTest {
.body(containsString("zetl-described"))
.body(containsString(source))
.body(containsString(TARGET))
// Lower case on real Redshift, not ACTIVE.
.body(containsString("<Status>active</Status>"))
// Lower case on real Redshift, not ACTIVE. `syncing` right after creation: the
// zero-ETL consumer has not yet confirmed the backfill scan of the source table.
.body(containsString("<Status>syncing</Status>"))
.body(containsString("<Errors></Errors>"));
}
@Test
void anEmptySourceTableEventuallyReachesActiveStatus() {
String arn = arnOf(createIntegration("zetl-eventually-active"));
Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.untilAsserted(() -> query("Action", "DescribeIntegrations", "IntegrationArn", arn)
.then().statusCode(200)
.body(containsString("<Status>active</Status>")));
}
@Test
void preExistingDynamoDbItemsAreBackfilledIntoTheLandingTable() {
RestAssuredJsonUtils.configureAwsContentTypes();
String tableName = "keystone-backfill-" + System.nanoTime();
String streamArn = createDynamoTable(tableName);
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType("application/x-amz-json-1.0")
.body("""
{
"TableName": "%s",
"Item": {"id": {"S": "pre-existing-1"}, "note": {"S": "seeded before integration"}}
}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200);
String createResponse = query("Action", "CreateIntegration", "IntegrationName", "zetl-backfill-proof",
"SourceArn", streamArn, "TargetArn", TARGET)
.then().statusCode(200)
.extract().body().asString();
String arn = arnOf(createResponse);
String landingTable = "floci_zetl_" + arn.substring(arn.lastIndexOf(':') + 1).replace('-', '_');
int port = clusterPort("zero-etl-cluster");
Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.untilAsserted(() -> assertTrue(
landingTableHasBackfilledRow(port, landingTable, "pre-existing-1")));
}
private static int clusterPort(String clusterIdentifier) {
String xml = query("Action", "DescribeClusters", "ClusterIdentifier", clusterIdentifier)
.then().statusCode(200).extract().body().asString();
Matcher matcher = Pattern.compile("<Endpoint>.*?<Port>(\\d+)</Port>", Pattern.DOTALL).matcher(xml);
assertTrue(matcher.find(), "DescribeClusters returned no endpoint port: " + xml);
return Integer.parseInt(matcher.group(1));
}
private static boolean landingTableHasBackfilledRow(int port, String landingTable, String itemId)
throws SQLException {
String url = "jdbc:postgresql://127.0.0.1:" + port + "/dev";
try (Connection connection = DriverManager.getConnection(url, "admin", "password123");
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT new_image_json FROM " + landingTable
+ " WHERE event_id LIKE 'backfill#%'")) {
while (rows.next()) {
if (rows.getString(1).contains(itemId)) {
return true;
}
}
return false;
}
}
@Test
void describingByArnReturnsOnlyThatIntegration() {
String arn = arnOf(createIntegration("zetl-byarn"));
@@ -90,6 +90,16 @@ class RedshiftInterceptorIntegrationTest {
return jdbcUrl(cluster) + "?prepareThreshold=1";
}
/**
* Catalog-based column discovery for {@code FORMAT AS JSON 'auto'} without an explicit column
* list only runs over the Simple Query protocol (see {@code docs/services/redshift.md}), so
* tests exercising that discovery must force it explicitly: pgjdbc's default query mode is
* Extended even for a plain {@link java.sql.Statement}.
*/
private static String simpleQueryJdbcUrl(Cluster cluster) {
return jdbcUrl(cluster) + "?preferQueryMode=simple";
}
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
return waitForConnection(jdbcUrl(cluster), username, password);
}
@@ -443,4 +453,144 @@ class RedshiftInterceptorIntegrationTest {
"UNLOAD ('select id from o_src') TO 's3://redshift-unload-it-ow/o/' ALLOWOVERWRITE");
}
}
@Test
void copyFromS3JsonAutoExplicitColumnsLoadsRows() throws Exception {
clusterId = "it-copy-json-explicit";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-copy-json-explicit";
s3.createBucket(bucket, "us-east-1");
String ndjson = "{\"id\": 1, \"name\": \"Alice\", \"score\": 95.5}\n"
+ "{\"id\": 2, \"name\": \"Bob\", \"score\": 82.0}\n";
s3.putObject(bucket, "data/users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE users (id int, name text, score numeric)");
c.createStatement().execute("COPY users (id, name, score) FROM 's3://" + bucket + "/data/users.json' FORMAT AS JSON 'auto'");
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*), sum(score) FROM users")) {
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
assertEquals(177.5, rs.getDouble(2), 0.001);
}
}
}
@Test
void copyFromS3JsonAutoWithoutColumnsDiscoversSchema() throws Exception {
clusterId = "it-copy-json-auto-schema";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-copy-json-auto-schema";
s3.createBucket(bucket, "us-east-1");
String ndjson = "{\"id\": 10, \"name\": \"Charlie\", \"note\": \"hello\"}\n"
+ "{\"id\": 20, \"name\": \"David\", \"note\": \"world\"}\n";
s3.putObject(bucket, "data/items.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
// Column discovery only runs over Simple Query; force it explicitly since pgjdbc's
// default query mode is Extended even for a plain Statement.
try (Connection c = waitForConnection(simpleQueryJdbcUrl(cluster), "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE items (id int, name text, note text)");
c.createStatement().execute("COPY items FROM 's3://" + bucket + "/data/items.json' FORMAT AS JSON 'auto'");
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*), max(id) FROM items")) {
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
assertEquals(20, rs.getInt(2));
}
}
}
@Test
void copyFromS3JsonAutoWithoutColumnsOverExtendedQueryFailsClearly() throws Exception {
clusterId = "it-copy-json-auto-extended-rejects";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-copy-json-auto-extended";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "data/items.json",
"{\"id\": 1}\n".getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
// Default connection: pgjdbc's default query mode is Extended even for a plain Statement,
// where the column list is fixed at Parse time and catalog discovery cannot run.
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE ext_items (id int)");
SQLException ex = assertThrows(SQLException.class, () -> c.createStatement().execute(
"COPY ext_items FROM 's3://" + bucket + "/data/items.json' FORMAT AS JSON 'auto'"));
assertTrue(ex.getMessage().contains("explicit column list"));
}
}
@Test
void copyFromS3JsonAutoGzipLoadsRows() throws Exception {
clusterId = "it-copy-json-gzip";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-copy-json-gzip";
s3.createBucket(bucket, "us-east-1");
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (GZIPOutputStream gz = new GZIPOutputStream(raw)) {
gz.write("{\"id\": 100, \"val\": \"zipped\"}\n".getBytes(StandardCharsets.UTF_8));
}
s3.putObject(bucket, "data/compressed.json.gz", raw.toByteArray(), "application/gzip", Map.of());
// Column discovery only runs over Simple Query; force it explicitly since pgjdbc's
// default query mode is Extended even for a plain Statement.
try (Connection c = waitForConnection(simpleQueryJdbcUrl(cluster), "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE gz_items (id int, val text)");
c.createStatement().execute("COPY gz_items FROM 's3://" + bucket + "/data/compressed.json.gz' GZIP FORMAT AS JSON 'auto'");
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*), max(val) FROM gz_items")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals("zipped", rs.getString(2));
}
}
}
@Test
void copyFromS3ManifestRoundtrip() throws Exception {
clusterId = "it-manifest-roundtrip";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-manifest-roundtrip";
s3.createBucket(bucket, "us-east-1");
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE src (id int, name text)");
c.createStatement().execute("INSERT INTO src VALUES (1, 'alpha'), (2, 'beta')");
// UNLOAD with MANIFEST
c.createStatement().execute("UNLOAD ('select id, name from src order by id') "
+ "TO 's3://" + bucket + "/export/' MANIFEST ALLOWOVERWRITE");
// Target table
c.createStatement().execute("CREATE TABLE dst (id int, name text)");
// COPY using the generated manifest
c.createStatement().execute("COPY dst (id, name) FROM 's3://" + bucket + "/export/manifest' MANIFEST");
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM dst")) {
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
}
}
}
@Test
void copyFromS3ManifestMissingMandatoryFails() throws Exception {
clusterId = "it-manifest-missing";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-manifest-missing";
s3.createBucket(bucket, "us-east-1");
String manifestJson = "{\"entries\": [{\"url\": \"s3://" + bucket + "/missing.csv\", \"mandatory\": true}]}";
s3.putObject(bucket, "manifest", manifestJson.getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE t_mand (id int)");
SQLException ex = assertThrows(SQLException.class,
() -> c.createStatement().execute("COPY t_mand FROM 's3://" + bucket + "/manifest' MANIFEST"));
assertTrue(ex.getMessage().toLowerCase().contains("does not exist") || ex.getMessage().toLowerCase().contains("missing.csv"), ex.getMessage());
}
}
}
@@ -35,7 +35,9 @@ import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
@@ -126,6 +128,51 @@ class RedshiftServiceTest {
assertEquals(streamArn, integration.getSourceStreamArn());
assertEquals("warehouse", integration.getTargetClusterIdentifier());
assertNotNull(integration.getLandingTableName());
assertEquals("syncing", integration.getStatus());
assertFalse(integration.isBackfillCompleted());
}
@Test
void updateIntegrationBackfillProgressPersistsCheckpointAndFlipsStatusOnCompletion() {
String streamArn = "arn:aws:dynamodb:us-east-1:111111111111:table/orders/stream/2026-09-18T00:00:00.000";
String targetArn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
StreamDescription stream = new StreamDescription();
stream.setStreamArn(streamArn);
stream.setTableName("orders");
stream.setStreamStatus("ENABLED");
when(streamService.describeStream(streamArn)).thenReturn(stream);
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");
when(clusterBackend.get("warehouse")).thenReturn(Optional.of(cluster));
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = service.createIntegration("orders-to-warehouse", streamArn, targetArn,
null, null, Map.of(), Map.of(), "us-east-1");
ArgumentCaptor<String> keyCaptor = ArgumentCaptor.forClass(String.class);
verify(integrationBackend).put(keyCaptor.capture(), eq(integration));
String storageKey = keyCaptor.getValue();
when(integrationBackend.keysForAccount("111111111111")).thenReturn(java.util.Set.of(storageKey));
when(integrationBackend.getForAccount("111111111111", storageKey)).thenReturn(Optional.of(integration));
service.updateIntegrationBackfillProgress("111111111111", integration.getIntegrationArn(),
"{\"id\":{\"S\":\"1\"}}", false);
assertEquals("syncing", integration.getStatus());
assertEquals("{\"id\":{\"S\":\"1\"}}", integration.getBackfillLastEvaluatedKey());
assertFalse(integration.isBackfillCompleted());
service.updateIntegrationBackfillProgress("111111111111", integration.getIntegrationArn(), null, true);
assertEquals("active", integration.getStatus());
assertNull(integration.getBackfillLastEvaluatedKey());
assertTrue(integration.isBackfillCompleted());
}
@Test
void updateIntegrationBackfillProgressOnUnknownIntegrationThrows() {
when(integrationBackend.keysForAccount("111111111111")).thenReturn(java.util.Set.of());
assertThrows(AwsException.class, () -> service.updateIntegrationBackfillProgress(
"111111111111", "arn:aws:redshift:us-east-1:111111111111:integration:missing", null, true));
}
@Test
@@ -163,12 +163,13 @@ class CopyStatementParserTest {
@Test
void returnsNullForUnsupportedClauses() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS PARQUET"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 'auto'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 's3://mybucket/jsonpaths.json'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FIXEDWIDTH 'a:1,b:2'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP MAXERROR 10"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'YYYY-MM-DD'"));
}
@Test
void returnsNullWhenAStatementFollowsTheCopy() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k'; DROP TABLE staging"));
@@ -325,4 +326,67 @@ class CopyStatementParserTest {
assertFalse(u.csv());
assertEquals("csv", u.nullAs());
}
@Test
void parseCopy_jsonAuto_explicitColumns() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY users (id, name) FROM 's3://mybucket/users.json' "
+ "IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftRole' "
+ "FORMAT AS JSON 'auto'");
assertEquals("users", c.targetTable());
assertEquals(List.of("id", "name"), c.columns());
assertEquals("mybucket", c.bucket());
assertEquals("users.json", c.keyOrPrefix());
assertTrue(c.jsonAuto());
assertFalse(c.manifest());
}
@Test
void parseCopy_jsonAuto_variations() {
CopyStatementParser.S3CopyFrom c1 = copyFrom("COPY tbl FROM 's3://b/data.json' JSON 'auto'");
assertTrue(c1.jsonAuto());
assertFalse(c1.jsonAutoIgnoreCase());
CopyStatementParser.S3CopyFrom c2 = copyFrom("COPY tbl FROM 's3://b/data.json' JSON AS 'auto'");
assertTrue(c2.jsonAuto());
assertFalse(c2.jsonAutoIgnoreCase());
CopyStatementParser.S3CopyFrom c3 = copyFrom("COPY tbl FROM 's3://b/data.json' FORMAT JSON 'auto'");
assertTrue(c3.jsonAuto());
assertFalse(c3.jsonAutoIgnoreCase());
CopyStatementParser.S3CopyFrom c4 = copyFrom("COPY tbl FROM 's3://b/data.json' JSON 'auto ignorecase'");
assertTrue(c4.jsonAuto());
assertTrue(c4.jsonAutoIgnoreCase());
CopyStatementParser.S3CopyFrom c5 = copyFrom("COPY tbl FROM 's3://b/data.json' FORMAT AS JSON 'auto ignorecase'");
assertTrue(c5.jsonAuto());
assertTrue(c5.jsonAutoIgnoreCase());
}
@Test
void parseCopy_manifest_gzip() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY sales FROM 's3://mybucket/manifest.json' "
+ "IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftRole' "
+ "MANIFEST GZIP CSV");
assertTrue(c.manifest());
assertTrue(c.gzip());
assertTrue(c.csv());
assertFalse(c.jsonAuto());
}
@Test
void parseCopy_jsonAutoAndManifest() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY tbl FROM 's3://b/manifest' "
+ "MANIFEST FORMAT AS JSON 'auto'");
assertTrue(c.manifest());
assertTrue(c.jsonAuto());
}
@Test
void parseCopy_rejectsUnsupportedJsonPathsAndParquet() {
// Only JSON 'auto' is supported; jsonpaths or bare JSON must be rejected
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' JSON 's3://b/paths.json'"));
assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' PARQUET"));
}
}
@@ -0,0 +1,139 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JsonLinesToCsvConverterTest {
@Test
void convert_caseInsensitiveMappingAndEscaping() throws IOException {
String ndjson = "{\"Id\": 1, \"Name\": \"Alice\", \"note\": \"hello, world\"}\n"
+ "{\"id\": 2, \"NAME\": \"Bob, \\\"The Builder\\\"\", \"note\": \"multi\\nline\"}\n"
+ "{\"ID\": 3, \"name\": null}\n";
ByteArrayInputStream in = new ByteArrayInputStream(ndjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "name", "note");
JsonLinesToCsvConverter.convert(in, columns, out, true);
String result = out.toString(StandardCharsets.UTF_8);
String[] lines = result.split("\n");
assertEquals("1,Alice,\"hello, world\"", lines[0].trim());
assertEquals("2,\"Bob, \"\"The Builder\"\"\",\"multi\nline\"", lines[1].trim() + "\n" + lines[2].trim());
assertEquals("3,,", lines[3].trim());
}
@Test
void convert_caseSensitiveDefault_matchesExactCase() throws IOException {
String ndjson = "{\"Id\": 1, \"id\": 10, \"NAME\": \"Alice\", \"name\": \"Bob\"}\n"
+ "{\"Id\": 2, \"name\": \"Charlie\"}\n";
ByteArrayInputStream in = new ByteArrayInputStream(ndjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "name");
// default ignoreCase = false
JsonLinesToCsvConverter.convert(in, columns, out);
String result = out.toString(StandardCharsets.UTF_8);
String[] lines = result.split("\n");
assertEquals("10,Bob", lines[0].trim());
// Second line has "Id" but not "id", so "id" column is null (empty)
assertEquals(",Charlie", lines[1].trim());
}
@Test
void convert_prettyPrintedMultilineJson() throws IOException {
String prettyJson = "{\n \"id\": 1,\n \"name\": \"Alice\"\n}\n"
+ "{\n \"id\": 2,\n \"name\": \"Bob\"\n}\n";
ByteArrayInputStream in = new ByteArrayInputStream(prettyJson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "name");
JsonLinesToCsvConverter.convert(in, columns, out);
String result = out.toString(StandardCharsets.UTF_8);
String[] lines = result.split("\n");
assertEquals("1,Alice", lines[0].trim());
assertEquals("2,Bob", lines[1].trim());
}
@Test
void convert_nonObjectRoot_throwsException() {
String jsonArray = "[{\"id\": 1, \"name\": \"Alice\"}]\n";
ByteArrayInputStream in = new ByteArrayInputStream(jsonArray.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "name");
S3CopySimulator.S3TransferException ex = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> JsonLinesToCsvConverter.convert(in, columns, out));
assertTrue(ex.getMessage().contains("JSON value is not an object"));
}
@Test
void convert_nestedJsonSerializedToString() throws IOException {
String ndjson = "{\"id\": 10, \"payload\": {\"subKey\": \"val\", \"count\": 5}}\n";
ByteArrayInputStream in = new ByteArrayInputStream(ndjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "payload");
JsonLinesToCsvConverter.convert(in, columns, out);
String result = out.toString(StandardCharsets.UTF_8);
assertEquals("10,\"{\"\"subKey\"\":\"\"val\"\",\"\"count\"\":5}\"", result.trim());
}
@Test
void convert_booleanAndNumericFormats() throws IOException {
String ndjson = "{\"flag\": true, \"val\": 12.345, \"zero\": 0}\n";
ByteArrayInputStream in = new ByteArrayInputStream(ndjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("flag", "val", "zero");
JsonLinesToCsvConverter.convert(in, columns, out);
String result = out.toString(StandardCharsets.UTF_8);
assertEquals("true,12.345,0", result.trim());
}
@Test
void convert_malformedJson_includesLinePreviewInException() {
String badNdjson = "{\"id\": 1, \"name\": invalid_json}\n";
ByteArrayInputStream in = new ByteArrayInputStream(badNdjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> columns = List.of("id", "name");
S3CopySimulator.S3TransferException ex = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> JsonLinesToCsvConverter.convert(in, columns, out));
assertTrue(ex.getMessage().contains("invalid_json"));
}
@Test
void convert_emptyOrNullColumns_throwsException() {
String ndjson = "{\"id\": 1}\n";
ByteArrayInputStream in = new ByteArrayInputStream(ndjson.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out = new ByteArrayOutputStream();
assertThrows(
S3CopySimulator.S3TransferException.class,
() -> JsonLinesToCsvConverter.convert(in, List.of(), out));
assertThrows(
S3CopySimulator.S3TransferException.class,
() -> JsonLinesToCsvConverter.convert(in, null, out));
}
}
@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
class ManifestReaderTest {
@Test
void parseManifest_validEntries() {
S3Service s3 = Mockito.mock(S3Service.class);
String manifestJson = "{\"entries\": ["
+ "{\"url\": \"s3://mybucket/data/file1.csv\", \"mandatory\": true},"
+ "{\"url\": \"s3://mybucket/data/file2.csv\", \"mandatory\": false}"
+ "]}";
S3Object obj = new S3Object();
obj.setData(manifestJson.getBytes(StandardCharsets.UTF_8));
when(s3.getObject("mybucket", "manifest.json")).thenReturn(obj);
when(s3.objectExists("mybucket", "data/file1.csv")).thenReturn(true);
when(s3.objectExists("mybucket", "data/file2.csv")).thenReturn(false);
List<String> keys = ManifestReader.resolveManifestKeys("mybucket", "manifest.json", s3);
assertEquals(List.of("data/file1.csv"), keys);
}
@Test
void parseManifest_missingMandatory_throwsException() {
S3Service s3 = Mockito.mock(S3Service.class);
String manifestJson = "{\"entries\": ["
+ "{\"url\": \"s3://mybucket/data/missing.csv\", \"mandatory\": true}"
+ "]}";
S3Object obj = new S3Object();
obj.setData(manifestJson.getBytes(StandardCharsets.UTF_8));
when(s3.getObject("mybucket", "manifest.json")).thenReturn(obj);
when(s3.objectExists("mybucket", "data/missing.csv")).thenReturn(false);
S3CopySimulator.S3TransferException ex = assertThrows(S3CopySimulator.S3TransferException.class, () ->
ManifestReader.resolveManifestKeys("mybucket", "manifest.json", s3));
assertTrue(ex.getMessage().contains("missing.csv"));
}
@Test
void parseManifest_malformedJson_throwsException() {
S3Service s3 = Mockito.mock(S3Service.class);
S3Object obj = new S3Object();
obj.setData("not valid json".getBytes(StandardCharsets.UTF_8));
when(s3.getObject("mybucket", "manifest.json")).thenReturn(obj);
assertThrows(S3CopySimulator.S3TransferException.class, () ->
ManifestReader.resolveManifestKeys("mybucket", "manifest.json", s3));
}
@Test
void parseManifest_missingMandatoryFlagDefaultsToFalse_skipsMissingFile() {
S3Service s3 = Mockito.mock(S3Service.class);
String manifestJson = "{\"entries\": ["
+ "{\"url\": \"s3://mybucket/data/file1.csv\"},"
+ "{\"url\": \"s3://mybucket/data/missing.csv\"}"
+ "]}";
S3Object obj = new S3Object();
obj.setData(manifestJson.getBytes(StandardCharsets.UTF_8));
when(s3.getObject("mybucket", "manifest.json")).thenReturn(obj);
when(s3.objectExists("mybucket", "data/file1.csv")).thenReturn(true);
when(s3.objectExists("mybucket", "data/missing.csv")).thenReturn(false);
List<String> keys = ManifestReader.resolveManifestKeys("mybucket", "manifest.json", s3);
assertEquals(List.of("data/file1.csv"), keys);
}
}
@@ -1327,4 +1327,292 @@ class S3CopySimulatorTest {
assertNull(in.nextMessage(), "Client must not receive an unconfirmed ReadyForQuery");
}
@Test
void prepareCopy_withManifest_resolvesManifestKeys() {
String manifestJson = "{\"entries\": [{\"url\": \"s3://wh/data1.csv\", \"mandatory\": true}]}";
S3Object manifestObj = new S3Object("wh", "manifest.json", manifestJson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "manifest.json")).thenReturn(manifestObj);
when(s3.objectExists("wh", "data1.csv")).thenReturn(true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "manifest.json", ",", 0, false, true, null, null, false, true);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, null);
assertEquals(List.of("data1.csv"), input.keys());
}
@Test
void copyBackendSql_and_stream_withJsonAuto() throws Exception {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"users", List.of("id", "name"), "wh", "users.json", null, 0, false, false, null, null, true, false);
assertEquals("COPY users (id, name) FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
S3CopySimulator.copyBackendSql(spec));
String ndjson = "{\"id\": 1, \"name\": \"Alice\"}\n{\"id\": 2, \"name\": \"Bob\"}\n";
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
byte[] rawBytes = out.toByteArray();
// The output is framed as Postgres 'd' CopyData messages
assertTrue(rawBytes.length > 0);
assertEquals('d', rawBytes[0]);
}
@Test
void copyBackendSql_quotesDiscoveredColumnIdentifiers() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"orders", List.of(), "wh", "orders.csv", ",", 0, false, true, null, null);
assertEquals("COPY orders (\"order\", \"user\", \"col\"\"name\") FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
S3CopySimulator.copyBackendSql(spec, List.of("order", "user", "col\"name")));
}
@Test
void copyBackendSql_passesUserSuppliedColumnListThroughAsWritten() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"orders", List.of("\"col one\"", "MixedCase", "\"User\""), "wh", "orders.csv", ",", 0, false, true, null, null);
assertEquals("COPY orders (\"col one\", MixedCase, \"User\") FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
S3CopySimulator.copyBackendSql(spec));
}
@Test
void copyBackendSql_withJsonAuto_forcesCommaDelimiter() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"users", List.of("id"), "wh", "users.json", "\t", 0, false, false, null, null, true, false);
assertEquals("COPY users (id) FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
S3CopySimulator.copyBackendSql(spec));
}
@Test
void streamCopyInput_withJsonAuto_unquotesQuotedColumnIdentifiers() throws Exception {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"users", List.of("\"col one\"", "Id"), "wh", "users.json", null, 0, false, false, null, null, true, false);
String ndjson = "{\"col one\": \"Alice\", \"Id\": 10}\n";
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
byte[] rawBytes = out.toByteArray();
assertTrue(rawBytes.length > 5);
assertEquals('d', rawBytes[0]);
String payload = new String(rawBytes, 5, rawBytes.length - 5, StandardCharsets.UTF_8);
assertEquals("Alice,10\n", payload);
}
@Test
void streamCopyInput_withJsonAutoAndGzip() throws Exception {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"users", List.of("id", "name"), "wh", "users.json.gz", null, 0, true, false, null, null, true, false);
String ndjson = "{\"id\": 1, \"name\": \"Alice\"}\n";
ByteArrayOutputStream gzippedOut = new ByteArrayOutputStream();
try (java.util.zip.GZIPOutputStream gzip = new java.util.zip.GZIPOutputStream(gzippedOut)) {
gzip.write(ndjson.getBytes(StandardCharsets.UTF_8));
}
S3Object dataObj = new S3Object("wh", "users.json.gz", gzippedOut.toByteArray(), "application/gzip");
when(s3.getObject("wh", "users.json.gz")).thenReturn(dataObj);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("users.json.gz"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, out);
byte[] rawBytes = out.toByteArray();
assertTrue(rawBytes.length > 0);
assertEquals('d', rawBytes[0]);
}
@Test
void runCopyFrom_withJsonAutoWithoutColumns_discoversSchemaAndCopies() throws Exception {
String ndjson = "{\"id\": 10, \"name\": \"Alice\"}\n";
S3Object dataObj = new S3Object("wh", "data.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.objectExists("wh", "data.json")).thenReturn(true);
when(s3.getObject("wh", "data.json")).thenReturn(dataObj);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"public.items", List.of(), "wh", "data.json", null, 0, false, false, null, null, true, false);
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder.FrontendMessage q1 = in.nextMessage();
assertEquals('Q', q1.type());
assertTrue(q1.getSql().contains("pg_catalog.pg_attribute"));
assertTrue(q1.getSql().contains("items"));
writeSingleColumnDataRow(out, "id");
writeSingleColumnDataRow(out, "name");
writeCommandComplete(out, "SELECT 2");
writeReadyForQuery(out, 'I');
PostgresWireDecoder.FrontendMessage q2 = in.nextMessage();
assertEquals('Q', q2.type());
assertEquals("COPY public.items (\"id\", \"name\") FROM STDIN WITH (FORMAT csv, DELIMITER ',')", q2.getSql());
out.write(new byte[]{'G', 0, 0, 0, 4});
out.flush();
PostgresWireDecoder.FrontendMessage d = in.nextMessage();
assertEquals('d', d.type());
PostgresWireDecoder.FrontendMessage c = in.nextMessage();
assertEquals('c', c.type());
writeCommandComplete(out, "COPY 1");
writeReadyForQuery(out, 'I');
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
PostgresWireDecoder clientIn = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage msg1 = clientIn.nextMessage();
assertEquals('C', msg1.type());
PostgresWireDecoder.FrontendMessage msg2 = clientIn.nextMessage();
assertEquals('Z', msg2.type());
}
@Test
void runCopyFrom_withQuotedAndMixedCaseColumns_passesThroughToBackendAndMatchesJsonKeys() throws Exception {
String ndjson = "{\"col one\": \"Alice\", \"MixedCase\": 10}\n";
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.objectExists("wh", "users.json")).thenReturn(true);
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"public.users", List.of("\"col one\"", "MixedCase"), "wh", "users.json", null, 0, false, false, null, null, true, false);
ByteArrayOutputStream streamedData = new ByteArrayOutputStream();
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
assertEquals('Q', q.type());
assertEquals("COPY public.users (\"col one\", MixedCase) FROM STDIN WITH (FORMAT csv, DELIMITER ',')", q.getSql());
out.write(new byte[]{'G', 0, 0, 0, 4});
out.flush();
while (true) {
PostgresWireDecoder.FrontendMessage m = in.nextMessage();
if (m == null || m.type() == 'c') {
break;
}
if (m.type() == 'd') {
streamedData.write(m.body());
}
}
writeCommandComplete(out, "COPY 1");
writeReadyForQuery(out, 'I');
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
assertEquals("Alice,10\n", streamedData.toString(StandardCharsets.UTF_8));
PostgresWireDecoder clientIn = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('C', clientIn.nextMessage().type());
assertEquals('Z', clientIn.nextMessage().type());
}
@Test
void runCopyFrom_withJsonAuto_releasesIamSessionEvenWhenCatalogDiscoveryFails() throws Exception {
when(s3.objectExists("wh", "data.json")).thenReturn(true);
IamService iamService = mock(IamService.class);
IamRole role = mock(IamRole.class);
when(role.getAssumeRolePolicyDocument()).thenReturn(
"{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"redshift.amazonaws.com\"}}]}");
when(iamService.findRole("000000000000", "Role")).thenReturn(java.util.Optional.of(role));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"missing_table", List.of(), "wh", "data.json", null, 0, false, false, null,
"arn:aws:iam::000000000000:role/Role", true, false);
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder.FrontendMessage q1 = in.nextMessage();
assertEquals('Q', q1.type());
writeCommandComplete(out, "SELECT 0");
writeReadyForQuery(out, 'I');
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, iamService, 'I');
joinBackend(backend);
assertTrue(handled);
verify(iamService, times(1)).registerSessionForAccount(eq("000000000000"), any(), any(), any(), any(), any(), any());
verify(iamService, times(1)).unregisterSession(eq("000000000000"), any());
}
@Test
void runCopyFrom_withJsonAutoWithoutColumns_whenTableNotFound_sendsError() throws Exception {
when(s3.objectExists("wh", "data.json")).thenReturn(true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"missing_table", List.of(), "wh", "data.json", null, 0, false, false, null, null, true, false);
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder.FrontendMessage q1 = in.nextMessage();
assertEquals('Q', q1.type());
assertTrue(q1.getSql().contains("missing_table"));
writeCommandComplete(out, "SELECT 0");
writeReadyForQuery(out, 'I');
});
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, null, 'I');
joinBackend(backend);
assertTrue(handled);
PostgresWireDecoder clientIn = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = clientIn.nextMessage();
assertEquals('E', err.type());
PostgresWireDecoder.FrontendMessage ready = clientIn.nextMessage();
assertEquals('Z', ready.type());
}
private static void writeSingleColumnDataRow(OutputStream out, String val) throws IOException {
byte[] b = val.getBytes(StandardCharsets.UTF_8);
int len = 4 + 2 + 4 + b.length;
out.write('D');
out.write(intBytes(len));
out.write(new byte[]{0, 1});
out.write(intBytes(b.length));
out.write(b);
out.flush();
}
private static void writeCommandComplete(OutputStream out, String tag) throws IOException {
byte[] b = (tag + "\0").getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(intBytes(4 + b.length));
out.write(b);
out.flush();
}
private static void writeReadyForQuery(OutputStream out, char status) throws IOException {
out.write(new byte[]{'Z', 0, 0, 0, 5, (byte) status});
out.flush();
}
}