mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): project DynamoDB zero-ETL changes into a current-state table (#8180)
This commit is contained in:
1 parent
5c08fff5d7
commit
eea61cd42a
12 files changed
+1469
-4
No files matched your search
@@ -46,6 +46,7 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
|
||||
table.setTableName(TABLE_NAME);
|
||||
table.setTableArn(TABLE_ARN);
|
||||
table.setKeySchema(List.of(new KeySchemaElement("id", "HASH")));
|
||||
table.setAttributeDefinitions(List.of(new AttributeDefinition("id", "S")));
|
||||
return table;
|
||||
}
|
||||
|
||||
|
||||
+292
@@ -19,6 +19,8 @@ import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshift.model.Integration;
|
||||
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState;
|
||||
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState.Change;
|
||||
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -27,6 +29,7 @@ import io.vertx.core.Vertx;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
@@ -50,7 +53,9 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -605,6 +610,13 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
assertEquals("backfill", written.path("dynamodb").path("SequenceNumber").asText());
|
||||
assertEquals(written.path("dynamodb").path("Keys").path("id"),
|
||||
written.path("dynamodb").path("NewImage").path("id"));
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
// Only the first page empties the current-state table; the second continues the same backfill.
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
verify(writer, times(1)).resetCurrentStateTable(any(), any(), any());
|
||||
verify(writer, times(2)).applyChanges(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -815,6 +827,286 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
|
||||
List.of(first.awsRecord()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void projectsStreamRecordsIntoTheCurrentStateTableAfterTheyLand() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-projected-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
// Key 1 is in the source and key 2 was deleted from it; each is named by an insert and a remove.
|
||||
ObjectNode held = itemWithId("1");
|
||||
held.putObject("note").put("S", "held");
|
||||
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, held, "us-east-1"));
|
||||
DynamoDbStreamReader.Record inserted = imageRecord("s1", "INSERT", "1", "first");
|
||||
DynamoDbStreamReader.Record removed = keysOnlyRecord("s2", "REMOVE", "2");
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(inserted, removed));
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
|
||||
|
||||
ArgumentCaptor<RedshiftZeroEtlCurrentState> state = ArgumentCaptor.forClass(RedshiftZeroEtlCurrentState.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
|
||||
InOrder inOrder = inOrder(writer);
|
||||
inOrder.verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
|
||||
List.of(inserted.awsRecord(), removed.awsRecord()));
|
||||
inOrder.verify(writer).createCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), state.capture(),
|
||||
eq("one"));
|
||||
inOrder.verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq(state.getValue()),
|
||||
changes.capture());
|
||||
assertEquals(tableName, state.getValue().tableName());
|
||||
assertEquals(List.of(new Change(inserted.awsRecord().path("dynamodb").path("Keys"), held),
|
||||
new Change(removed.awsRecord().path("dynamodb").path("Keys"), null)), changes.getValue());
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
}
|
||||
|
||||
/**
|
||||
* The scan read version three of an item while the stream still holds the MODIFY records that led to it. They
|
||||
* are replayed after the scan, carrying older images, and must not put those over the newer row.
|
||||
*/
|
||||
@Test
|
||||
void replayedRecordsOfAnItemTheScanReadNewerNeverRegressItsRow() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-replayed-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
ObjectNode versionThree = itemWithId("1");
|
||||
versionThree.putObject("note").put("S", "version three");
|
||||
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, versionThree, "us-east-1"));
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
DynamoDbStreamReader.Record versionTwo = imageRecord("s1", "MODIFY", "1", "version two");
|
||||
DynamoDbStreamReader.Record versionThreeRecord = imageRecord("s2", "MODIFY", "1", "version three");
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(versionTwo));
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer = new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb,
|
||||
mock(RedshiftService.class), writer);
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).add(versionThreeRecord);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer, times(2)).applyChanges(any(), any(), any(), changes.capture());
|
||||
// Across polls, the older record's poll and the newer one's both leave version three in the row.
|
||||
for (List<Change> applied : changes.getAllValues()) {
|
||||
assertEquals(1, applied.size());
|
||||
assertEquals(versionThree, applied.get(0).item());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void manyRecordsOfOneKeyProjectItOnce() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-chatty-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(
|
||||
imageRecord("s1", "INSERT", "1", "a"), imageRecord("s2", "MODIFY", "1", "b"),
|
||||
keysOnlyRecord("s3", "REMOVE", "1")));
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
|
||||
.pollOnce(integration);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer).applyChanges(any(), any(), any(), changes.capture());
|
||||
assertEquals(1, changes.getValue().size());
|
||||
assertTrue(changes.getValue().get(0).isDelete());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecordWithoutANewImageIsProjectedFromTheSourceItem() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-keys-only-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
ObjectNode item = itemWithId("1");
|
||||
item.putObject("note").put("S", "as it is now");
|
||||
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, item, "us-east-1"));
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(
|
||||
keysOnlyRecord("s1", "MODIFY", "1"), keysOnlyRecord("s2", "MODIFY", "gone")));
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
|
||||
.pollOnce(integration);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
|
||||
verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(), changes.capture());
|
||||
assertEquals(item, changes.getValue().get(0).item());
|
||||
assertTrue(changes.getValue().get(1).isDelete());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedProjectionDoesNotHoldBackTheLandingLogAndTheTableIsRebuiltOnceItCanBeWritten() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
doThrow(new AwsException("InternalFailure", "Could not apply Redshift zero-ETL changes to orders.", 500))
|
||||
.when(writer).applyChanges(any(), any(), any(), any());
|
||||
String tableName = "orders-retried-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
integration.setCurrentStateProjected(true);
|
||||
DynamoDbStreamReader.Record first = imageRecord("s1", "INSERT", "1", "first");
|
||||
DynamoDbStreamReader.Record second = imageRecord("s2", "INSERT", "2", "second");
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).add(first);
|
||||
RedshiftDynamoDbZeroEtlConsumer consumer =
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
|
||||
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
// The record landed and its checkpoint advanced; only the projection stalled.
|
||||
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
|
||||
List.of(first.awsRecord()));
|
||||
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
|
||||
assertFalse(integration.isCurrentStateProjected());
|
||||
verify(redshiftService).updateIntegrationCurrentState(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), false);
|
||||
|
||||
// While the table cannot be written, later batches still land and none is projected.
|
||||
doThrow(new AwsException("InvalidParameterValue", "Table public.\"x\" is not ours.", 400))
|
||||
.when(writer).createCurrentStateTable(any(), any(), any(), any());
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).add(second);
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
|
||||
List.of(second.awsRecord()));
|
||||
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
|
||||
verify(writer, times(1)).applyChanges(any(), any(), any(), any());
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
|
||||
// Once the table can be made, the backfill starts over to fill it, and a scan that completes marks it so.
|
||||
doReturn(true).when(writer).createCurrentStateTable(any(), any(), any(), any());
|
||||
consumer.pollOnce(integration);
|
||||
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
assertTrue(integration.isCurrentStateProjected());
|
||||
verify(redshiftService, times(1)).updateIntegrationBackfillProgress(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), null, false);
|
||||
verify(redshiftService).updateIntegrationCurrentState(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), true);
|
||||
verify(writer, times(1)).resetCurrentStateTable(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTableTheIntegrationCannotMakeStallsTheProjectionAloneWhileTheScanLands() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
doThrow(new AwsException("InvalidParameterValue", "Table public.\"x\" is not ours.", 400))
|
||||
.when(writer).createCurrentStateTable(any(), any(), any(), any());
|
||||
String tableName = "orders-refused-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, false);
|
||||
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, itemWithId("1"), "us-east-1"));
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
|
||||
|
||||
verify(writer).writeBatch(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq("floci_zetl_orders"), any());
|
||||
verify(writer, never()).applyChanges(any(), any(), any(), any());
|
||||
verify(writer, never()).resetCurrentStateTable(any(), any(), any());
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
assertFalse(integration.isCurrentStateProjected());
|
||||
verify(redshiftService).updateIntegrationBackfillProgress(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), null, true);
|
||||
verify(redshiftService, never()).updateIntegrationCurrentState(any(), any(), eq(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTableMadeAfreshOverARunningIntegrationIsFilledByAnotherScan() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
doReturn(true).when(writer).createCurrentStateTable(any(), any(), any(), any());
|
||||
String tableName = "orders-dropped-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, true);
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
integration.setBackfillCompleted(true);
|
||||
integration.setCurrentStateProjected(true);
|
||||
streams.shard(table.getStreamArn(), SHARD_ID, null).add(imageRecord("s1", "INSERT", "1", "first"));
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
|
||||
|
||||
// The user dropped the table: it is made again and holds nothing but this batch, so the scan refills it.
|
||||
assertFalse(integration.isBackfillCompleted());
|
||||
assertFalse(integration.isCurrentStateProjected());
|
||||
verify(redshiftService).updateIntegrationBackfillProgress(integration.getAccountId(),
|
||||
integration.getIntegrationArn(), null, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPersistedIntegrationWithoutACurrentStateScansItsSourceAgainAtStartup() {
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setBackfillLastEvaluatedKey(null);
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
assertFalse(integration.isCurrentStateProjected());
|
||||
|
||||
startPersisted(CheckpointLifetime.STREAM, integration);
|
||||
|
||||
assertFalse(integration.isBackfillCompleted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPersistedIntegrationWhoseCurrentStateIsFilledKeepsItsBackfill() {
|
||||
Integration integration = streamingIntegration();
|
||||
integration.setCurrentStateProjected(true);
|
||||
|
||||
startPersisted(CheckpointLifetime.STREAM, integration);
|
||||
|
||||
assertTrue(integration.isBackfillCompleted());
|
||||
}
|
||||
|
||||
@Test
|
||||
void backfilledItemsAreProjectedAsUpserts() {
|
||||
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
|
||||
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
|
||||
String tableName = "orders-backfill-state-" + System.nanoTime();
|
||||
TableDefinition table = createTableAs("111111111111", tableName, false);
|
||||
ObjectNode item = itemWithId("1");
|
||||
RequestScopes.runAs("111111111111", () -> dynamoDbService.putItem(tableName, item, "us-east-1"));
|
||||
Integration integration = tableSourceIntegration(table);
|
||||
|
||||
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, mock(RedshiftService.class), writer)
|
||||
.pollOnce(integration);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<Change>> changes = ArgumentCaptor.forClass(List.class);
|
||||
InOrder inOrder = inOrder(writer);
|
||||
inOrder.verify(writer).createCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(),
|
||||
eq("one"));
|
||||
// A table left behind by an earlier integration of the source is emptied before the first page lands.
|
||||
inOrder.verify(writer).resetCurrentStateTable(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any());
|
||||
inOrder.verify(writer).writeBatch(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq("floci_zetl_orders"), any());
|
||||
inOrder.verify(writer).applyChanges(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), any(), changes.capture());
|
||||
assertEquals(List.of(new Change(item, item)), changes.getValue());
|
||||
}
|
||||
|
||||
private static DynamoDbStreamReader.Record imageRecord(String sequenceNumber, String eventName, String id,
|
||||
String note) {
|
||||
DynamoDbStreamReader.Record record = keysOnlyRecord(sequenceNumber, eventName, id);
|
||||
ObjectNode image = ((ObjectNode) record.awsRecord().path("dynamodb")).putObject("NewImage");
|
||||
image.putObject("id").put("S", id);
|
||||
image.putObject("note").put("S", note);
|
||||
return record;
|
||||
}
|
||||
|
||||
private static DynamoDbStreamReader.Record keysOnlyRecord(String sequenceNumber, String eventName, String id) {
|
||||
ObjectNode awsRecord = MAPPER.createObjectNode()
|
||||
.put("eventID", "event-" + sequenceNumber)
|
||||
.put("eventName", eventName);
|
||||
ObjectNode dynamodb = awsRecord.putObject("dynamodb").put("SequenceNumber", sequenceNumber);
|
||||
dynamodb.putObject("Keys").putObject("id").put("S", id);
|
||||
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
|
||||
}
|
||||
|
||||
private TableDefinition createTableAs(String accountId, String tableName, boolean streamed) {
|
||||
return RequestScopes.callAs(accountId, () -> {
|
||||
dynamoDbService.createTable(tableName, List.of(new KeySchemaElement("id", "HASH")),
|
||||
|
||||
@@ -16,6 +16,7 @@ import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
@@ -191,6 +192,66 @@ class RedshiftIntegrationsIntegrationTest {
|
||||
landingTableHasBackfilledRow(port, landingTable, "pre-existing-1")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The current-state table is named after the DynamoDB table in {@code public}, holds the item under its key
|
||||
* columns in a {@code value} column of DynamoDB JSON, and follows the source: a backfilled item is there, a
|
||||
* put replaces it, and a delete removes it.
|
||||
*/
|
||||
@Test
|
||||
void theSourceTablesCurrentStateIsProjectedUnderItsOwnName() throws SQLException {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
String tableName = "keystone-state-" + System.nanoTime();
|
||||
String streamArn = createDynamoTable(tableName);
|
||||
putItem(tableName, "order-1", "seeded");
|
||||
query("Action", "CreateIntegration", "IntegrationName", "zetl-current-state",
|
||||
"SourceArn", streamArn, "TargetArn", TARGET)
|
||||
.then().statusCode(200);
|
||||
int port = clusterPort("zero-etl-cluster");
|
||||
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.untilAsserted(() -> assertEquals("seeded", currentNote(port, tableName, "order-1")));
|
||||
|
||||
putItem(tableName, "order-1", "replaced");
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.untilAsserted(() -> assertEquals("replaced", currentNote(port, tableName, "order-1")));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("{\"TableName\":\"%s\",\"Key\":{\"id\":{\"S\":\"order-1\"}}}".formatted(tableName))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.untilAsserted(() -> assertEquals(null, currentNote(port, tableName, "order-1")));
|
||||
}
|
||||
|
||||
private static void putItem(String tableName, String id, String note) {
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"Item": {"id": {"S": "%s"}, "note": {"S": "%s"}}
|
||||
}
|
||||
""".formatted(tableName, id, note))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/** The item's {@code note} read the way a SUPER path is read on Redshift, or null when the row is gone. */
|
||||
private static String currentNote(int port, String tableName, String id) throws SQLException {
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + port + "/dev";
|
||||
try (Connection connection = DriverManager.getConnection(url, "admin", "password123");
|
||||
PreparedStatement statement = connection.prepareStatement(
|
||||
"SELECT value->'note'->>'S' FROM public.\"" + tableName + "\" WHERE id = ?")) {
|
||||
statement.setString(1, id);
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
return rows.next() ? rows.getString(1) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int clusterPort(String clusterIdentifier) {
|
||||
String xml = query("Action", "DescribeClusters", "ClusterIdentifier", clusterIdentifier)
|
||||
.then().statusCode(200).extract().body().asString();
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package io.floci.aws.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import io.floci.aws.services.redshiftdata.RedshiftZeroEtlCurrentState.Change;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
|
||||
class RedshiftZeroEtlCurrentStateTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void shapesTheTableAsAwsDoesWithKeyColumnsBeforeTheItemValue() {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
|
||||
List.of(new KeySchemaElement("sk", "RANGE"), new KeySchemaElement("pk", "HASH")),
|
||||
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "N"))));
|
||||
|
||||
assertEquals("orders", state.tableName());
|
||||
assertEquals(List.of("pk", "sk"), state.keyColumnNames());
|
||||
assertEquals("CREATE TABLE IF NOT EXISTS public.\"orders\" (\"pk\" TEXT NOT NULL, "
|
||||
+ "\"sk\" NUMERIC NOT NULL, \"value\" JSONB NOT NULL, PRIMARY KEY (\"pk\", \"sk\"))", state.ddl());
|
||||
assertEquals("TRUNCATE TABLE public.\"orders\"", state.resetSql());
|
||||
assertEquals(Map.of("pk", "text", "sk", "numeric", "value", "jsonb"), state.expectedColumnTypes());
|
||||
assertEquals("INSERT INTO public.\"orders\" (\"pk\", \"sk\", \"value\") VALUES (?, ?, ?::jsonb) "
|
||||
+ "ON CONFLICT (\"pk\", \"sk\") DO UPDATE SET \"value\" = EXCLUDED.\"value\"", state.upsertSql());
|
||||
assertEquals("DELETE FROM public.\"orders\" WHERE \"pk\" = ? AND \"sk\" = ?", state.deleteSql());
|
||||
assertEquals(3, state.valueParameterIndex());
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotesIdentifiersSoDynamoDbNamesSurviveCaseAndPunctuation() {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("Orders-v2.prod",
|
||||
List.of(new KeySchemaElement("Order Id", "HASH")), List.of(new AttributeDefinition("Order Id", "B"))));
|
||||
|
||||
assertEquals("CREATE TABLE IF NOT EXISTS public.\"Orders-v2.prod\" (\"Order Id\" BYTEA NOT NULL, "
|
||||
+ "\"value\" JSONB NOT NULL, PRIMARY KEY (\"Order Id\"))", state.ddl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesNamesPostgresWouldTruncate() {
|
||||
// 63 bytes is kept whole; 64 would be cut, and two names cut to the same prefix would share a table.
|
||||
assertEquals("x".repeat(63), RedshiftZeroEtlCurrentState.of(table("x".repeat(63),
|
||||
List.of(new KeySchemaElement("id", "HASH")), List.of(new AttributeDefinition("id", "S")))).tableName());
|
||||
AwsException longName = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
|
||||
table("x".repeat(64), List.of(new KeySchemaElement("id", "HASH")),
|
||||
List.of(new AttributeDefinition("id", "S")))));
|
||||
assertEquals("InvalidParameterValue", longName.getErrorCode());
|
||||
assertTrue(longName.getMessage().contains("63 bytes"));
|
||||
// Bytes, not characters: a multibyte name is cut sooner.
|
||||
AwsException multibyte = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
|
||||
table("é".repeat(32), List.of(new KeySchemaElement("id", "HASH")),
|
||||
List.of(new AttributeDefinition("id", "S")))));
|
||||
assertEquals("InvalidParameterValue", multibyte.getErrorCode());
|
||||
|
||||
AwsException longKey = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
|
||||
table("orders", List.of(new KeySchemaElement("k".repeat(64), "HASH")),
|
||||
List.of(new AttributeDefinition("k".repeat(64), "S")))));
|
||||
assertEquals("InvalidParameterValue", longKey.getErrorCode());
|
||||
|
||||
AwsException valueKey = assertThrows(AwsException.class, () -> RedshiftZeroEtlCurrentState.of(
|
||||
table("orders", List.of(new KeySchemaElement("value", "HASH")),
|
||||
List.of(new AttributeDefinition("value", "S")))));
|
||||
assertTrue(valueKey.getMessage().contains("value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsKeysByTheirDynamoDbType() throws Exception {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
|
||||
List.of(new KeySchemaElement("pk", "HASH"), new KeySchemaElement("sk", "RANGE")),
|
||||
List.of(new AttributeDefinition("pk", "S"), new AttributeDefinition("sk", "N"))));
|
||||
ObjectNode keys = MAPPER.createObjectNode();
|
||||
keys.putObject("pk").put("S", "customer#1");
|
||||
keys.putObject("sk").put("N", "42.5");
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
|
||||
state.bindKeys(statement, keys);
|
||||
|
||||
verify(statement).setString(1, "customer#1");
|
||||
verify(statement).setBigDecimal(2, new BigDecimal("42.5"));
|
||||
verifyNoMoreInteractions(statement);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsNumericKeysExactlyHoweverLargeOrFine() throws Exception {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("metrics",
|
||||
List.of(new KeySchemaElement("n", "HASH")), List.of(new AttributeDefinition("n", "N"))));
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
// 38 significant digits with 30 before the point, and a difference past the 18th decimal: both exact.
|
||||
for (String number : List.of("123456789012345678901234567890.12345678", "0.1234567890123456789",
|
||||
"0.1234567890123456788", "-1e125")) {
|
||||
ObjectNode keys = MAPPER.createObjectNode();
|
||||
keys.putObject("n").put("N", number);
|
||||
state.bindKeys(statement, keys);
|
||||
verify(statement).setBigDecimal(1, new BigDecimal(number));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsBinaryKeysFromBase64() throws Exception {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("blobs",
|
||||
List.of(new KeySchemaElement("id", "HASH")), List.of(new AttributeDefinition("id", "B"))));
|
||||
ObjectNode keys = MAPPER.createObjectNode();
|
||||
keys.putObject("id").put("B", "AQID");
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
|
||||
state.bindKeys(statement, keys);
|
||||
|
||||
verify(statement).setBytes(1, new byte[] {1, 2, 3});
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfAnotherTypeThanTheSchemaIsAnInternalFailure() {
|
||||
RedshiftZeroEtlCurrentState state = RedshiftZeroEtlCurrentState.of(table("orders",
|
||||
List.of(new KeySchemaElement("pk", "HASH")), List.of(new AttributeDefinition("pk", "S"))));
|
||||
ObjectNode keys = MAPPER.createObjectNode();
|
||||
keys.putObject("pk").put("N", "1");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, () -> state.bindKeys(mock(PreparedStatement.class), keys));
|
||||
assertEquals("InternalFailure", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecordIsProjectedFromTheItemAsTheSourceHoldsItNowNotFromItsOwnImage() {
|
||||
// A replayed MODIFY carries version two, but the source holds version three: the newer one is projected.
|
||||
ObjectNode replayed = record("MODIFY", true);
|
||||
ObjectNode current = MAPPER.createObjectNode();
|
||||
current.putObject("id").put("S", "1");
|
||||
current.putObject("note").put("S", "version three");
|
||||
|
||||
Change change = RedshiftZeroEtlCurrentState.changeOf(replayed, keys -> current);
|
||||
|
||||
assertEquals(replayed.path("dynamodb").path("Keys"), change.keys());
|
||||
assertEquals(current, change.item());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyKindOfRecordProjectsTheSameStateOfItsKey() {
|
||||
ObjectNode current = MAPPER.createObjectNode();
|
||||
current.putObject("id").put("S", "1");
|
||||
|
||||
for (String eventName : List.of("INSERT", "MODIFY", "REMOVE")) {
|
||||
assertEquals(current, RedshiftZeroEtlCurrentState.changeOf(record(eventName, true), keys -> current).item(),
|
||||
eventName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyTheSourceNoLongerHoldsIsDeleted() {
|
||||
// Even an INSERT record, replayed after its item was deleted, deletes: the source is the truth.
|
||||
Change delete = RedshiftZeroEtlCurrentState.changeOf(record("INSERT", true), keys -> null);
|
||||
|
||||
assertTrue(delete.isDelete());
|
||||
assertEquals(record("INSERT", true).path("dynamodb").path("Keys"), delete.keys());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecordWithoutKeysProjectsNothing() {
|
||||
ObjectNode record = MAPPER.createObjectNode().put("eventName", "MODIFY");
|
||||
record.putObject("dynamodb").put("SequenceNumber", "1");
|
||||
|
||||
assertNull(RedshiftZeroEtlCurrentState.changeOf(record, keys -> null));
|
||||
}
|
||||
|
||||
private static ObjectNode record(String eventName, boolean withNewImage) {
|
||||
ObjectNode record = MAPPER.createObjectNode().put("eventID", "e").put("eventName", eventName);
|
||||
ObjectNode dynamodb = record.putObject("dynamodb").put("SequenceNumber", "1");
|
||||
dynamodb.putObject("Keys").putObject("id").put("S", "1");
|
||||
if (withNewImage) {
|
||||
ObjectNode image = dynamodb.putObject("NewImage");
|
||||
image.putObject("id").put("S", "1");
|
||||
image.putObject("note").put("S", "hello");
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
private static TableDefinition table(String name, List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributes) {
|
||||
TableDefinition table = new TableDefinition();
|
||||
table.setTableName(name);
|
||||
table.setKeySchema(keySchema);
|
||||
table.setAttributeDefinitions(attributes);
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,34 @@ package io.floci.aws.services.redshiftdata;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import io.floci.aws.services.dynamodb.model.TableDefinition;
|
||||
import io.floci.aws.services.redshift.RedshiftService;
|
||||
import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints;
|
||||
import io.floci.aws.services.redshift.model.Cluster;
|
||||
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.time.Instant;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Arrays;
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -83,6 +94,252 @@ class RedshiftZeroEtlWriterTest {
|
||||
verify(connection).close();
|
||||
}
|
||||
|
||||
/** A target whose {@code public.orders} is absent ({@code owner} null, {@code exists} false) or held as given. */
|
||||
private static final class Target {
|
||||
final Connection connection = mock(Connection.class);
|
||||
final Statement statement = mock(Statement.class);
|
||||
final RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
final RedshiftZeroEtlWriter writer;
|
||||
|
||||
/** {@code columns} are the table's column names, each followed by its information_schema data type. */
|
||||
Target(boolean exists, String owner, String... columns) throws SQLException {
|
||||
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
|
||||
when(connectionFactory.open(any())).thenReturn(connection);
|
||||
when(connection.createStatement()).thenReturn(statement);
|
||||
PreparedStatement ownerQuery = mock(PreparedStatement.class);
|
||||
ResultSet ownerRow = mock(ResultSet.class);
|
||||
when(connection.prepareStatement(contains("to_regclass"))).thenReturn(ownerQuery);
|
||||
when(ownerQuery.executeQuery()).thenReturn(ownerRow);
|
||||
when(ownerRow.next()).thenReturn(true);
|
||||
when(ownerRow.getBoolean(1)).thenReturn(exists);
|
||||
when(ownerRow.getString(2)).thenReturn(owner);
|
||||
if (columns.length > 0) {
|
||||
columnsOf(connection, columns);
|
||||
}
|
||||
writer = new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class), connectionFactory,
|
||||
new ObjectMapper());
|
||||
}
|
||||
|
||||
boolean create() {
|
||||
return writer.createCurrentStateTable("111111111111", WAREHOUSE_ARN, orders(), "one");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsAndMarksTheCurrentStateTableUnderTheDynamoDbTableName() throws Exception {
|
||||
Target target = new Target(false, null);
|
||||
|
||||
assertTrue(target.create());
|
||||
|
||||
InOrder inOrder = inOrder(target.connection, target.statement);
|
||||
inOrder.verify(target.connection).setAutoCommit(false);
|
||||
inOrder.verify(target.statement).executeUpdate(contains("CREATE TABLE IF NOT EXISTS public.\"orders\" "
|
||||
+ "(\"id\" TEXT NOT NULL, \"value\" JSONB NOT NULL"));
|
||||
inOrder.verify(target.statement).executeUpdate(
|
||||
"COMMENT ON TABLE public.\"orders\" IS 'floci-zetl-integration:one'");
|
||||
inOrder.verify(target.connection).commit();
|
||||
verify(target.statement, never()).executeUpdate(contains("DROP TABLE"));
|
||||
verify(target.connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsATableTheIntegrationMarkedWithTheColumnsItWrites() throws Exception {
|
||||
Target target = new Target(true, "floci-zetl-integration:one", "id", "text", "value", "jsonb");
|
||||
|
||||
assertFalse(target.create());
|
||||
|
||||
verify(target.statement, never()).executeUpdate(any());
|
||||
verify(target.connection).commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsAfreshATableAnEarlierIntegrationLeft() throws Exception {
|
||||
Target target = new Target(true, "floci-zetl-integration:earlier", "id", "text", "value", "jsonb");
|
||||
when(target.redshiftService.integrationExists("111111111111", "earlier")).thenReturn(false);
|
||||
|
||||
assertTrue(target.create());
|
||||
|
||||
InOrder inOrder = inOrder(target.statement);
|
||||
inOrder.verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
|
||||
inOrder.verify(target.statement).executeUpdate(contains("CREATE TABLE IF NOT EXISTS public.\"orders\""));
|
||||
inOrder.verify(target.statement).executeUpdate(
|
||||
"COMMENT ON TABLE public.\"orders\" IS 'floci-zetl-integration:one'");
|
||||
verify(target.connection).commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsAfreshItsOwnTableWhoseKeysAreNotTheSources() throws Exception {
|
||||
Target target = new Target(true, "floci-zetl-integration:one", "order_id", "text", "value", "jsonb");
|
||||
|
||||
assertTrue(target.create());
|
||||
|
||||
verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startsAfreshItsOwnTableWhoseKeyHasAnotherTypeThanTheSources() throws Exception {
|
||||
// The source was made again with the same key name, a number now where it was a string.
|
||||
Target target = new Target(true, "floci-zetl-integration:one", "id", "numeric", "value", "jsonb");
|
||||
|
||||
assertTrue(target.create());
|
||||
|
||||
verify(target.statement).executeUpdate("DROP TABLE public.\"orders\"");
|
||||
verify(target.statement).executeUpdate(contains("\"id\" TEXT NOT NULL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesATableAnotherLiveIntegrationMarkedAndLeavesItAlone() throws Exception {
|
||||
Target target = new Target(true, "floci-zetl-integration:other", "id", "text", "value", "jsonb");
|
||||
when(target.redshiftService.integrationExists("111111111111", "other")).thenReturn(true);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, target::create);
|
||||
|
||||
assertEquals("InvalidParameterValue", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("is in use by zero-ETL integration other"));
|
||||
verify(target.statement, never()).executeUpdate(any());
|
||||
verify(target.connection).rollback();
|
||||
verify(target.connection, never()).commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesATableNoIntegrationMadeAndLeavesItAlone() throws Exception {
|
||||
Target target = new Target(true, null, "id", "text", "value", "jsonb");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, target::create);
|
||||
|
||||
assertEquals("InvalidParameterValue", e.getErrorCode());
|
||||
assertTrue(e.getMessage().contains("public.\"orders\""));
|
||||
assertTrue(e.getMessage().contains("was not created by a zero-ETL integration"));
|
||||
verify(target.statement, never()).executeUpdate(any());
|
||||
verify(target.connection).rollback();
|
||||
verify(target.connection, never()).commit();
|
||||
verify(target.connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesATableCarryingSomeoneElsesComment() throws Exception {
|
||||
Target target = new Target(true, "orders of the finance team", "id", "text", "value", "jsonb");
|
||||
|
||||
assertThrows(AwsException.class, target::create);
|
||||
|
||||
verify(target.statement, never()).executeUpdate(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptiesTheCurrentStateTable() throws Exception {
|
||||
Target target = new Target(true, "floci-zetl-integration:one");
|
||||
|
||||
target.writer.resetCurrentStateTable("111111111111", WAREHOUSE_ARN, orders());
|
||||
|
||||
verify(target.statement).executeUpdate("TRUNCATE TABLE public.\"orders\"");
|
||||
verify(target.connection).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailureNamesTheTableAndCarriesThePostgresMessage() throws Exception {
|
||||
Target target = new Target(false, null);
|
||||
when(target.statement.executeUpdate(any())).thenThrow(new SQLException("permission denied for schema public"));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class, target::create);
|
||||
|
||||
assertEquals("Could not create Redshift zero-ETL table public.\"orders\": permission denied for schema public",
|
||||
e.getMessage());
|
||||
verify(target.connection).rollback();
|
||||
}
|
||||
|
||||
|
||||
/** Stubs the information_schema lookup of a public table's columns, each name followed by its data type. */
|
||||
private static PreparedStatement columnsOf(Connection connection, String... namesAndTypes) throws SQLException {
|
||||
int count = namesAndTypes.length / 2;
|
||||
String[] names = new String[count];
|
||||
String[] types = new String[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
names[i] = namesAndTypes[2 * i];
|
||||
types[i] = namesAndTypes[2 * i + 1];
|
||||
}
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
ResultSet rows = mock(ResultSet.class);
|
||||
when(connection.prepareStatement(contains("information_schema.columns"))).thenReturn(statement);
|
||||
when(statement.executeQuery()).thenReturn(rows);
|
||||
Boolean[] next = new Boolean[count + 1];
|
||||
for (int i = 0; i < count; i++) {
|
||||
next[i] = true;
|
||||
}
|
||||
next[count] = false;
|
||||
when(rows.next()).thenReturn(next[0], Arrays.copyOfRange(next, 1, next.length));
|
||||
when(rows.getString(1)).thenReturn(names[0], Arrays.copyOfRange(names, 1, names.length));
|
||||
when(rows.getString(2)).thenReturn(types[0], Arrays.copyOfRange(types, 1, types.length));
|
||||
return statement;
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesUpsertsAndDeletesInOneTransaction() throws Exception {
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement upsert = mock(PreparedStatement.class);
|
||||
PreparedStatement delete = mock(PreparedStatement.class);
|
||||
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
|
||||
when(connectionFactory.open(any())).thenReturn(connection);
|
||||
when(connection.prepareStatement(contains("ON CONFLICT"))).thenReturn(upsert);
|
||||
when(connection.prepareStatement(contains("DELETE FROM"))).thenReturn(delete);
|
||||
ObjectNode keys = new ObjectMapper().createObjectNode();
|
||||
keys.putObject("id").put("S", "1");
|
||||
ObjectNode item = new ObjectMapper().createObjectNode();
|
||||
item.putObject("id").put("S", "1");
|
||||
item.putObject("note").put("S", "hello");
|
||||
|
||||
new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class), connectionFactory,
|
||||
new ObjectMapper()).applyChanges("111111111111", WAREHOUSE_ARN, orders(), List.of(
|
||||
new RedshiftZeroEtlCurrentState.Change(keys, item),
|
||||
new RedshiftZeroEtlCurrentState.Change(keys, null)));
|
||||
|
||||
InOrder inOrder = inOrder(connection, upsert, delete);
|
||||
inOrder.verify(connection).setAutoCommit(false);
|
||||
inOrder.verify(upsert).setString(1, "1");
|
||||
inOrder.verify(upsert).setString(2, "{\"id\":{\"S\":\"1\"},\"note\":{\"S\":\"hello\"}}");
|
||||
inOrder.verify(upsert).executeUpdate();
|
||||
inOrder.verify(delete).setString(1, "1");
|
||||
inOrder.verify(delete).executeUpdate();
|
||||
inOrder.verify(connection).commit();
|
||||
inOrder.verify(connection).close();
|
||||
verify(connection, never()).rollback();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedChangeRollsTheBatchBack() throws Exception {
|
||||
RedshiftService redshiftService = mock(RedshiftService.class);
|
||||
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement upsert = mock(PreparedStatement.class);
|
||||
when(redshiftService.describeClustersForAccount("111111111111", "warehouse")).thenReturn(List.of(cluster()));
|
||||
when(connectionFactory.open(any())).thenReturn(connection);
|
||||
when(connection.prepareStatement(any())).thenReturn(upsert);
|
||||
when(upsert.executeUpdate()).thenThrow(new SQLException("relation \"public.orders\" does not exist"));
|
||||
ObjectNode keys = new ObjectMapper().createObjectNode();
|
||||
keys.putObject("id").put("S", "1");
|
||||
|
||||
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, mock(RedshiftZeroEtlEndpoints.class),
|
||||
connectionFactory, new ObjectMapper());
|
||||
AwsException e = assertThrows(AwsException.class, () -> writer.applyChanges("111111111111", WAREHOUSE_ARN,
|
||||
orders(), List.of(new RedshiftZeroEtlCurrentState.Change(keys, keys))));
|
||||
|
||||
assertEquals("InternalFailure", e.getErrorCode());
|
||||
assertEquals("Could not apply Redshift zero-ETL changes to public.\"orders\": relation \"public.orders\" "
|
||||
+ "does not exist", e.getMessage());
|
||||
verify(connection).rollback();
|
||||
verify(connection, never()).commit();
|
||||
}
|
||||
|
||||
private static RedshiftZeroEtlCurrentState orders() {
|
||||
TableDefinition table = new TableDefinition();
|
||||
table.setTableName("orders");
|
||||
table.setKeySchema(List.of(new KeySchemaElement("id", "HASH")));
|
||||
table.setAttributeDefinitions(List.of(new AttributeDefinition("id", "S")));
|
||||
return RedshiftZeroEtlCurrentState.of(table);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesANamespaceThroughItsWorkgroupIntoTheNamespaceDatabase() throws Exception {
|
||||
String namespaceArn = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"
|
||||
|
||||
Reference in new issue
Block a user