diff --git a/src/main/java/io/floci/aws/services/rds/integration/PgOutputMessages.java b/src/main/java/io/floci/aws/services/rds/integration/PgOutputMessages.java new file mode 100644 index 0000000000..463346a497 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/integration/PgOutputMessages.java @@ -0,0 +1,164 @@ +package io.floci.aws.services.rds.integration; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * The messages of PostgreSQL's {@code pgoutput} logical decoding plugin, protocol version 1, as + * {@code pg_logical_slot_peek_binary_changes} returns them: one message per row. Values are in their text form, + * since the binary option is not asked for. Messages Floci has no use for, such as an origin or a type, are read + * as {@link Other}. + */ +final class PgOutputMessages { + + private PgOutputMessages() {} + + sealed interface Message permits Begin, Commit, Relation, Insert, Update, Delete, Truncate, Other {} + + record Begin() implements Message {} + + /** The end of a transaction; {@code endLsn} is where a slot advanced past it resumes. */ + record Commit(String endLsn) implements Message {} + + /** A table's schema, name and column names, in the order a tuple carries its values. */ + record Relation(int relationId, String schema, String table, List columns) implements Message {} + + record Insert(int relationId, Tuple row) implements Message {} + + /** + * An updated row. {@code oldRow} is the old primary key when the key changed, or the whole old row under + * {@code REPLICA IDENTITY FULL}; it is null otherwise. + */ + record Update(int relationId, Tuple oldRow, Tuple row) implements Message {} + + /** A deleted row, given by its old primary key, or by its whole old row under {@code REPLICA IDENTITY FULL}. */ + record Delete(int relationId, Tuple oldRow) implements Message {} + + record Truncate(List relationIds) implements Message {} + + record Other(char type) implements Message {} + + /** A row's values, in the order of its relation's columns. */ + record Tuple(List values) {} + + /** + * One value of a row: SQL NULL, its text, or {@link Kind#UNCHANGED} for a TOASTed value the change did not touch, + * which PostgreSQL leaves out of an update. + */ + record Value(Kind kind, String text) { + enum Kind { NULL, UNCHANGED, TEXT } + + static final Value NULL = new Value(Kind.NULL, null); + static final Value UNCHANGED = new Value(Kind.UNCHANGED, null); + } + + static Message decode(byte[] data) { + ByteBuffer in = ByteBuffer.wrap(data); + char type = (char) in.get(); + return switch (type) { + case 'B' -> new Begin(); + case 'C' -> { + in.get(); + in.getLong(); + yield new Commit(lsn(in.getLong())); + } + case 'R' -> relation(in); + case 'I' -> { + int relationId = in.getInt(); + expect(in, 'N'); + yield new Insert(relationId, tuple(in)); + } + case 'U' -> update(in); + case 'D' -> { + int relationId = in.getInt(); + char kind = (char) in.get(); + if (kind != 'K' && kind != 'O') { + throw new IllegalArgumentException("Unexpected tuple kind " + kind + " in a pgoutput delete"); + } + yield new Delete(relationId, tuple(in)); + } + case 'T' -> { + int count = in.getInt(); + in.get(); + List relationIds = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + relationIds.add(in.getInt()); + } + yield new Truncate(relationIds); + } + default -> new Other(type); + }; + } + + /** An LSN in the {@code X/Y} form PostgreSQL prints and parses. */ + static String lsn(long value) { + return (Long.toHexString(value >>> 32) + "/" + Long.toHexString(value & 0xFFFFFFFFL)).toUpperCase(Locale.ROOT); + } + + private static Relation relation(ByteBuffer in) { + int relationId = in.getInt(); + String schema = string(in); + String table = string(in); + in.get(); + int count = in.getShort(); + List columns = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + in.get(); + columns.add(string(in)); + in.getInt(); + in.getInt(); + } + return new Relation(relationId, schema.isEmpty() ? "pg_catalog" : schema, table, columns); + } + + private static Update update(ByteBuffer in) { + int relationId = in.getInt(); + char kind = (char) in.get(); + Tuple oldRow = null; + if (kind == 'K' || kind == 'O') { + oldRow = tuple(in); + kind = (char) in.get(); + } + if (kind != 'N') { + throw new IllegalArgumentException("Unexpected tuple kind " + kind + " in a pgoutput update"); + } + return new Update(relationId, oldRow, tuple(in)); + } + + private static Tuple tuple(ByteBuffer in) { + int count = in.getShort(); + List values = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + char kind = (char) in.get(); + values.add(switch (kind) { + case 'n' -> Value.NULL; + case 'u' -> Value.UNCHANGED; + case 't' -> { + byte[] text = new byte[in.getInt()]; + in.get(text); + yield new Value(Value.Kind.TEXT, new String(text, StandardCharsets.UTF_8)); + } + default -> throw new IllegalArgumentException("Unexpected value kind " + kind + " in a pgoutput tuple"); + }); + } + return new Tuple(values); + } + + private static void expect(ByteBuffer in, char expected) { + char kind = (char) in.get(); + if (kind != expected) { + throw new IllegalArgumentException("Expected tuple kind " + expected + " but read " + kind); + } + } + + private static String string(ByteBuffer in) { + int start = in.position(); + while (in.get() != 0) { + // Reads up to and past the terminating NUL. + } + return new String(in.array(), start, in.position() - start - 1, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java b/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java index 5f70fefd00..75979d6e35 100644 --- a/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java +++ b/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java @@ -4,6 +4,7 @@ import io.floci.aws.core.common.PostgresWire; import java.util.Map; import java.util.Optional; +import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -23,8 +24,26 @@ final class PostgresRedshiftTypes { String elementTypeName, String elementTypeType, boolean elementBuiltin, String formattedType) {} - /** A column of the replicated table: its Redshift type and how the source column is read out. */ - record MappedColumn(String name, String redshiftType, String selectExpression) {} + /** + * A column of the replicated table: its Redshift type, its type on the source, and how a value of the source + * type is read out, as an expression over an operand of that type. + */ + record MappedColumn(String name, String redshiftType, String sourceType, UnaryOperator reader) { + + /** The expression that reads the column out of the source table. */ + String selectExpression() { + return reader.apply(PostgresWire.quoteIdentifier(name)); + } + + /** + * The expression that turns one bound parameter, the source's text output of a value, into the value the + * Redshift column takes: the same conversion {@link #selectExpression()} gives the initial load, whose CSV + * also carries each value as its text. + */ + String valueExpression() { + return "CAST(CAST(" + reader.apply("CAST(? AS " + sourceType + ")") + " AS text) AS " + redshiftType + ")"; + } + } private static final String SUPER = "pg_catalog.super"; private static final String VARBYTE = "pg_catalog.varbyte"; @@ -79,17 +98,16 @@ final class PostgresRedshiftTypes { private PostgresRedshiftTypes() {} static Optional map(SourceColumn column) { - String quoted = PostgresWire.quoteIdentifier(column.name()); if (!column.builtin()) { return Optional.empty(); } String typeName = column.typeName(); switch (typeName) { case "int2vector" -> { - return mapped(column, SUPER, "to_jsonb(" + quoted + "::int2[])"); + return mapped(column, SUPER, value -> "to_jsonb(" + value + "::int2[])"); } case "oidvector" -> { - return mapped(column, SUPER, "to_jsonb(" + quoted + "::oid[])"); + return mapped(column, SUPER, value -> "to_jsonb(" + value + "::oid[])"); } default -> { } } @@ -99,31 +117,31 @@ final class PostgresRedshiftTypes { column.elementTypeType(), "", column.elementBuiltin(), null, null, false, formatted.endsWith("[]") ? formatted.substring(0, formatted.length() - 2) : formatted); return column.elementTypeName() != null && map(element).isPresent() - ? mapped(column, SUPER, "to_jsonb(" + quoted + ")") : Optional.empty(); + ? mapped(column, SUPER, value -> "to_jsonb(" + value + ")") : Optional.empty(); } if (!"b".equals(column.typeType())) { return Optional.empty(); } String asIs = AS_IS.get(typeName); if (asIs != null) { - return mapped(column, asIs, quoted); + return mapped(column, asIs, value -> value); } String asText = AS_TEXT.get(typeName); if (asText != null) { - return mapped(column, asText, quoted + "::text"); + return mapped(column, asText, value -> value + "::text"); } return switch (typeName) { - case "json", "jsonb" -> mapped(column, SUPER, quoted + "::jsonb"); - case "money" -> mapped(column, "DECIMAL(20,3)", quoted + "::numeric"); - case "oid", "xid", "cid" -> mapped(column, "BIGINT", quoted + "::text::bigint"); - case "xid8" -> mapped(column, "DECIMAL(20,0)", quoted + "::text::numeric"); - case "numeric" -> numeric(column, quoted); - case "bpchar" -> character(column, quoted); + case "json", "jsonb" -> mapped(column, SUPER, value -> value + "::jsonb"); + case "money" -> mapped(column, "DECIMAL(20,3)", value -> value + "::numeric"); + case "oid", "xid", "cid" -> mapped(column, "BIGINT", value -> value + "::text::bigint"); + case "xid8" -> mapped(column, "DECIMAL(20,0)", value -> value + "::text::numeric"); + case "numeric" -> numeric(column); + case "bpchar" -> character(column); default -> Optional.empty(); }; } - private static Optional numeric(SourceColumn column, String quoted) { + private static Optional numeric(SourceColumn column) { Matcher matcher = NUMERIC.matcher(column.formattedType()); if (!matcher.matches()) { return Optional.empty(); @@ -133,23 +151,24 @@ final class PostgresRedshiftTypes { if (precision > MAX_DECIMAL_PRECISION || scale < 0 || scale > precision) { return Optional.empty(); } - return mapped(column, "DECIMAL(" + precision + "," + scale + ")", quoted); + return mapped(column, "DECIMAL(" + precision + "," + scale + ")", value -> value); } - private static Optional character(SourceColumn column, String quoted) { + private static Optional character(SourceColumn column) { Matcher matcher = CHARACTER.matcher(column.formattedType()); if (!matcher.matches()) { // A bpchar without a length takes any length, so it is read as text. - return mapped(column, LONG_VARCHAR, quoted + "::text"); + return mapped(column, LONG_VARCHAR, value -> value + "::text"); } int length = Integer.parseInt(matcher.group(1)); if (length > MAX_CHAR_LENGTH) { return Optional.empty(); } - return mapped(column, "CHAR(" + length + ")", quoted); + return mapped(column, "CHAR(" + length + ")", value -> value); } - private static Optional mapped(SourceColumn column, String redshiftType, String expression) { - return Optional.of(new MappedColumn(column.name(), redshiftType, expression)); + private static Optional mapped(SourceColumn column, String redshiftType, + UnaryOperator reader) { + return Optional.of(new MappedColumn(column.name(), redshiftType, column.formattedType(), reader)); } } diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java index f90f41f5be..ca2b04593c 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java @@ -27,6 +27,7 @@ import java.sql.Types; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -336,6 +337,153 @@ public class RedshiftZeroEtlWriter { */ public long loadTable(String accountId, String targetArn, String database, ReplicatedTable table, InputStream csv) { + return inTransaction(accountId, targetArn, database, "loading " + table.qualifiedName(), + "load table " + table.qualifiedName() + " into database " + database, connection -> { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate("CREATE SCHEMA IF NOT EXISTS " + + PostgresWire.quoteIdentifier(table.schema())); + statement.executeUpdate("DROP TABLE IF EXISTS " + table.qualifiedName()); + statement.executeUpdate(table.ddl()); + return connection.unwrap(PGConnection.class).getCopyAPI() + .copyIn("COPY " + table.qualifiedName() + " FROM STDIN WITH (FORMAT csv)", csv); + } catch (IOException e) { + throw new UncheckedIOException("Could not read the rows of table " + table.qualifiedName(), e); + } + }); + } + + /** One value of a replicated row: {@code expression} reads the value's source text, bound to its one {@code ?}. */ + public record ColumnValue(String column, String expression, String text) {} + + /** + * A change to a replicated table. + * + *
    + *
  • {@link Kind#UPSERT}: the row of {@code values} replaces the one under the same primary key, or is added. + *
  • {@link Kind#UPDATE}: the row under the primary key of {@code keys} takes {@code values}, and the + * columns it leaves out keep theirs. + *
  • {@link Kind#DELETE}: the row under the primary key of {@code keys} is removed. + *
  • {@link Kind#TRUNCATE}: every row is removed. + *
+ */ + public record RowChange(Kind kind, ReplicatedTable table, List values, List keys) { + public enum Kind { UPSERT, UPDATE, DELETE, TRUNCATE } + + public RowChange { + values = List.copyOf(values); + keys = List.copyOf(keys); + } + } + + /** + * Applies changes to the tables of {@code database} on the target in order, in one transaction. An upsert and a + * delete name the whole row or its key, so changes applied again after a failure leave the same rows. + * + * @throws TargetUnavailableException when the target cannot be reached, so the caller may try again + */ + public void applyRowChanges(String accountId, String targetArn, String database, List changes) { + if (changes.isEmpty()) { + return; + } + inTransaction(accountId, targetArn, database, "replicating", + "replicate changes into database " + database, connection -> { + for (RowChange change : changes) { + apply(connection, change); + } + return null; + }); + } + + private static void apply(Connection connection, RowChange change) throws SQLException { + String sql = rowChangeSql(change); + if (sql == null) { + return; + } + List bound = switch (change.kind()) { + case UPSERT -> change.values(); + case UPDATE -> { + List valuesThenKeys = new ArrayList<>(change.values()); + valuesThenKeys.addAll(change.keys()); + yield valuesThenKeys; + } + case DELETE -> change.keys(); + case TRUNCATE -> List.of(); + }; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + for (int i = 0; i < bound.size(); i++) { + String text = bound.get(i).text(); + if (text == null) { + statement.setNull(i + 1, Types.VARCHAR); + } else { + statement.setString(i + 1, text); + } + } + statement.executeUpdate(); + } + } + + /** + * The statement that applies a change, with a parameter for each value and then each key, or null when the change + * leaves the row as it is. + */ + static String rowChangeSql(RowChange change) { + ReplicatedTable table = change.table(); + return switch (change.kind()) { + case UPSERT -> { + StringBuilder columns = new StringBuilder(); + StringBuilder values = new StringBuilder(); + StringBuilder updates = new StringBuilder(); + for (ColumnValue value : change.values()) { + String column = PostgresWire.quoteIdentifier(value.column()); + columns.append(columns.isEmpty() ? "" : ", ").append(column); + values.append(values.isEmpty() ? "" : ", ").append(value.expression()); + if (!table.primaryKey().contains(value.column())) { + updates.append(updates.isEmpty() ? "" : ", ").append(column).append(" = EXCLUDED.") + .append(column); + } + } + yield "INSERT INTO " + table.qualifiedName() + " (" + columns + ") VALUES (" + values + + ") ON CONFLICT (" + keyList(table) + ")" + + (updates.isEmpty() ? " DO NOTHING" : " DO UPDATE SET " + updates); + } + case UPDATE -> { + if (change.values().isEmpty()) { + yield null; + } + StringBuilder sets = new StringBuilder(); + for (ColumnValue value : change.values()) { + sets.append(sets.isEmpty() ? "" : ", ").append(PostgresWire.quoteIdentifier(value.column())) + .append(" = ").append(value.expression()); + } + yield "UPDATE " + table.qualifiedName() + " SET " + sets + keyCondition(change.keys()); + } + case DELETE -> "DELETE FROM " + table.qualifiedName() + keyCondition(change.keys()); + case TRUNCATE -> "TRUNCATE " + table.qualifiedName(); + }; + } + + private static String keyList(ReplicatedTable table) { + StringBuilder keys = new StringBuilder(); + for (String column : table.primaryKey()) { + keys.append(keys.isEmpty() ? "" : ", ").append(PostgresWire.quoteIdentifier(column)); + } + return keys.toString(); + } + + private static String keyCondition(List keys) { + if (keys.isEmpty()) { + throw new IllegalArgumentException("A replicated update or delete needs the row's primary key"); + } + StringBuilder condition = new StringBuilder(); + for (ColumnValue key : keys) { + condition.append(condition.isEmpty() ? " WHERE " : " AND ") + .append(PostgresWire.quoteIdentifier(key.column())).append(" = ").append(key.expression()); + } + return condition.toString(); + } + + /** A connection to {@code database} of the target, or {@link TargetUnavailableException} when there is none. */ + private Connection openDatabase(String accountId, String targetArn, String database) { RedshiftDataResourceResolver.DatabaseTarget resolved; try { resolved = target(accountId, targetArn, database); @@ -343,24 +491,33 @@ public class RedshiftZeroEtlWriter { throw new TargetUnavailableException("Could not resolve Redshift target " + targetArn + ": " + e.getMessage(), e); } - Connection opened; try { - opened = connectionFactory.open(resolved); + return connectionFactory.open(resolved); } catch (SQLException e) { throw new TargetUnavailableException("Could not connect to Redshift database " + database + ": " + e.getMessage(), e); } - try (Connection connection = opened) { + } + + @FunctionalInterface + private interface TransactionWork { + T run(Connection connection) throws SQLException; + } + + /** + * Runs {@code work} in one transaction on {@code database} of the target, committing when it returns and rolling + * back when it throws. A lost connection surfaces as {@link TargetUnavailableException}, naming what was + * {@code during}; any other SQL failure as {@code InternalFailure}, saying what could not be done. + */ + private T inTransaction(String accountId, String targetArn, String database, String during, String failure, + TransactionWork work) { + try (Connection connection = openDatabase(accountId, targetArn, database)) { connection.setAutoCommit(false); - try (Statement statement = connection.createStatement()) { - statement.executeUpdate("CREATE SCHEMA IF NOT EXISTS " + PostgresWire.quoteIdentifier(table.schema())); - statement.executeUpdate("DROP TABLE IF EXISTS " + table.qualifiedName()); - statement.executeUpdate(table.ddl()); - long rows = connection.unwrap(PGConnection.class).getCopyAPI() - .copyIn("COPY " + table.qualifiedName() + " FROM STDIN WITH (FORMAT csv)", csv); + try { + T result = work.run(connection); connection.commit(); - return rows; - } catch (SQLException | IOException | RuntimeException e) { + return result; + } catch (SQLException | RuntimeException e) { try { connection.rollback(); } catch (SQLException rollbackFailure) { @@ -371,13 +528,10 @@ public class RedshiftZeroEtlWriter { } catch (SQLException e) { if (isConnectionFailure(e)) { throw new TargetUnavailableException("Connection to Redshift database " + database - + " failed while loading " + table.qualifiedName() + ": " + e.getMessage(), e); + + " failed while " + during + ": " + e.getMessage(), e); } - LOG.warnv(e, "Could not load zero-ETL table {0} into database {1}", table.qualifiedName(), database); - throw new AwsException("InternalFailure", "Could not load table " + table.qualifiedName() - + " into database " + database + ": " + e.getMessage(), 500); - } catch (IOException e) { - throw new UncheckedIOException("Could not read the rows of table " + table.qualifiedName(), e); + LOG.warnv(e, "Zero-ETL could not {0}", failure); + throw new AwsException("InternalFailure", "Could not " + failure + ": " + e.getMessage(), 500); } } diff --git a/src/test/java/io/floci/aws/services/rds/integration/PgOutputBytes.java b/src/test/java/io/floci/aws/services/rds/integration/PgOutputBytes.java new file mode 100644 index 0000000000..435fe25e36 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/integration/PgOutputBytes.java @@ -0,0 +1,70 @@ +package io.floci.aws.services.rds.integration; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +/** Writes one pgoutput message in the plugin's big-endian layout, as protocol version 1 has it. */ +final class PgOutputBytes { + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private final DataOutputStream out = new DataOutputStream(bytes); + + PgOutputBytes type(char type) { + return byte1(type); + } + + PgOutputBytes byte1(int value) { + try { + out.writeByte(value); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return this; + } + + PgOutputBytes int16(int value) { + try { + out.writeShort(value); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return this; + } + + PgOutputBytes int32(int value) { + try { + out.writeInt(value); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return this; + } + + PgOutputBytes int64(long value) { + try { + out.writeLong(value); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return this; + } + + PgOutputBytes string(String value) { + byte[] text = value.getBytes(StandardCharsets.UTF_8); + bytes.writeBytes(text); + return byte1(0); + } + + PgOutputBytes text(String value) { + byte[] text = value.getBytes(StandardCharsets.UTF_8); + byte1('t').int32(text.length); + bytes.writeBytes(text); + return this; + } + + byte[] build() { + return bytes.toByteArray(); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/PgOutputMessagesTest.java b/src/test/java/io/floci/aws/services/rds/integration/PgOutputMessagesTest.java new file mode 100644 index 0000000000..a41e8b4c5b --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/integration/PgOutputMessagesTest.java @@ -0,0 +1,105 @@ +package io.floci.aws.services.rds.integration; + +import io.floci.aws.services.rds.integration.PgOutputMessages.Commit; +import io.floci.aws.services.rds.integration.PgOutputMessages.Delete; +import io.floci.aws.services.rds.integration.PgOutputMessages.Insert; +import io.floci.aws.services.rds.integration.PgOutputMessages.Other; +import io.floci.aws.services.rds.integration.PgOutputMessages.Relation; +import io.floci.aws.services.rds.integration.PgOutputMessages.Truncate; +import io.floci.aws.services.rds.integration.PgOutputMessages.Update; +import io.floci.aws.services.rds.integration.PgOutputMessages.Value; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** Decoding the pgoutput messages a replication slot gives, built here byte for byte as protocol version 1 has them. */ +class PgOutputMessagesTest { + + @Test + void decodesARelationWithItsSchemaTableAndColumns() { + byte[] data = new PgOutputBytes().type('R').int32(16385).string("sales").string("orders").byte1('d') + .int16(2) + .byte1(1).string("id").int32(23).int32(-1) + .byte1(0).string("note").int32(25).int32(-1) + .build(); + + Relation relation = (Relation) PgOutputMessages.decode(data); + + assertEquals(16385, relation.relationId()); + assertEquals("sales", relation.schema()); + assertEquals("orders", relation.table()); + assertThat(relation.columns(), contains("id", "note")); + } + + @Test + void decodesAnInsertWithTextAndNullValues() { + byte[] data = new PgOutputBytes().type('I').int32(16385).byte1('N').int16(2).text("7").byte1('n').build(); + + Insert insert = (Insert) PgOutputMessages.decode(data); + + assertEquals(16385, insert.relationId()); + assertThat(insert.row().values(), contains(new Value(Value.Kind.TEXT, "7"), Value.NULL)); + } + + @Test + void decodesAnUpdateWithItsOldKeyAndAnUnchangedToastedValue() { + byte[] data = new PgOutputBytes().type('U').int32(1).byte1('K').int16(2).text("1").byte1('n') + .byte1('N').int16(2).text("2").byte1('u').build(); + + Update update = (Update) PgOutputMessages.decode(data); + + assertThat(update.oldRow().values(), contains(new Value(Value.Kind.TEXT, "1"), Value.NULL)); + assertThat(update.row().values(), contains(new Value(Value.Kind.TEXT, "2"), Value.UNCHANGED)); + } + + @Test + void decodesAnUpdateThatKeepsItsKey() { + byte[] data = new PgOutputBytes().type('U').int32(1).byte1('N').int16(1).text("ünïcode").build(); + + Update update = (Update) PgOutputMessages.decode(data); + + assertNull(update.oldRow()); + assertThat(update.row().values(), contains(new Value(Value.Kind.TEXT, "ünïcode"))); + } + + @Test + void decodesADeleteByItsKey() { + byte[] data = new PgOutputBytes().type('D').int32(1).byte1('K').int16(1).text("9").build(); + + Delete delete = (Delete) PgOutputMessages.decode(data); + + assertThat(delete.oldRow().values(), contains(new Value(Value.Kind.TEXT, "9"))); + } + + @Test + void decodesATruncateOfSeveralTables() { + byte[] data = new PgOutputBytes().type('T').int32(2).byte1(0).int32(10).int32(11).build(); + + Truncate truncate = (Truncate) PgOutputMessages.decode(data); + + assertEquals(List.of(10, 11), truncate.relationIds()); + } + + @Test + void readsTheEndOfACommittedTransactionAsAnLsn() { + byte[] data = new PgOutputBytes().type('C').byte1(0).int64(0x16B3748L).int64(0x1_016B_3780L).int64(0) + .build(); + + Commit commit = (Commit) PgOutputMessages.decode(data); + + assertEquals("1/16B3780", commit.endLsn()); + } + + @Test + void readsAMessageItHasNoUseForAsOther() { + byte[] data = new PgOutputBytes().type('Y').int32(600).string("public").string("mood").build(); + + assertThat(PgOutputMessages.decode(data), instanceOf(Other.class)); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java b/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java index b25d5a5f18..e62b91b327 100644 --- a/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java +++ b/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java @@ -56,6 +56,8 @@ class PostgresRedshiftTypesTest { MappedColumn array = mapped(new SourceColumn("tags", "_text", "b", "A", true, "text", "b", true, "text[]")); assertEquals("pg_catalog.super", array.redshiftType()); assertEquals("to_jsonb(\"tags\")", array.selectExpression()); + assertEquals("CAST(CAST(to_jsonb(CAST(? AS text[])) AS text) AS pg_catalog.super)", + array.valueExpression()); assertEquals("DECIMAL(20,3)", mapped(base("money", "money")).redshiftType()); assertEquals("pg_catalog.varbyte", mapped(base("bytea", "bytea")).redshiftType()); } diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriterRowChangeTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriterRowChangeTest.java new file mode 100644 index 0000000000..996056655c --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriterRowChangeTest.java @@ -0,0 +1,216 @@ +package io.floci.aws.services.redshiftdata; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.redshift.RedshiftService; +import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.ColumnValue; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.ReplicatedTable; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.RowChange; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.TargetUnavailableException; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Types; +import java.util.List; + +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.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** The statements and transaction execution that apply an RDS zero-ETL integration's replicated row changes. */ +class RedshiftZeroEtlWriterRowChangeTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String TARGET_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ns-1"; + private static final ReplicatedTable LINES = new ReplicatedTable("sales", "order lines", + List.of(new ReplicatedTable.Column("id", "BIGINT"), new ReplicatedTable.Column("line", "INTEGER"), + new ReplicatedTable.Column("note", "VARCHAR(65535)")), + List.of("id", "line")); + + private static ColumnValue value(String column) { + return new ColumnValue(column, "CAST(? AS x)", "v"); + } + + private static ColumnValue value(String column, String text) { + return new ColumnValue(column, "CAST(? AS x)", text); + } + + private static RedshiftZeroEtlWriter writerWith(Connection connection) throws SQLException { + RedshiftZeroEtlEndpoints endpoints = mock(RedshiftZeroEtlEndpoints.class); + when(endpoints.targetWorkgroup(ACCOUNT_ID, TARGET_ARN)).thenReturn( + new RedshiftServerlessService.WorkgroupTarget(TARGET_ARN, "wg-1", "localhost", 5439, "dev", + "admin", "secret", "admin")); + RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class); + when(factory.open(any())).thenReturn(connection); + return new RedshiftZeroEtlWriter(mock(RedshiftService.class), endpoints, factory, new ObjectMapper()); + } + + @Test + void anUpsertReplacesTheNonKeyColumnsOnAKeyConflict() { + RowChange change = new RowChange(RowChange.Kind.UPSERT, LINES, + List.of(value("id"), value("line"), value("note")), List.of()); + + assertEquals("INSERT INTO \"sales\".\"order lines\" (\"id\", \"line\", \"note\") " + + "VALUES (CAST(? AS x), CAST(? AS x), CAST(? AS x)) ON CONFLICT (\"id\", \"line\") " + + "DO UPDATE SET \"note\" = EXCLUDED.\"note\"", + RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void anUpsertOfOnlyKeyColumnsDoesNothingOnAKeyConflict() { + RowChange change = new RowChange(RowChange.Kind.UPSERT, LINES, List.of(value("id"), value("line")), + List.of()); + + assertEquals("INSERT INTO \"sales\".\"order lines\" (\"id\", \"line\") VALUES (CAST(? AS x), CAST(? AS x)) " + + "ON CONFLICT (\"id\", \"line\") DO NOTHING", RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void anUpdateSetsItsValuesWhereTheKeyMatches() { + RowChange change = new RowChange(RowChange.Kind.UPDATE, LINES, List.of(value("note")), + List.of(value("id"), value("line"))); + + assertEquals("UPDATE \"sales\".\"order lines\" SET \"note\" = CAST(? AS x) " + + "WHERE \"id\" = CAST(? AS x) AND \"line\" = CAST(? AS x)", + RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void anUpdateWithNothingToSetIsLeftOut() { + RowChange change = new RowChange(RowChange.Kind.UPDATE, LINES, List.of(), List.of(value("id"))); + + assertNull(RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void aDeleteRemovesTheRowUnderItsKey() { + RowChange change = new RowChange(RowChange.Kind.DELETE, LINES, List.of(), + List.of(value("id"), value("line"))); + + assertEquals("DELETE FROM \"sales\".\"order lines\" WHERE \"id\" = CAST(? AS x) AND \"line\" = CAST(? AS x)", + RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void aDeleteWithoutAKeyIsRefused() { + RowChange change = new RowChange(RowChange.Kind.DELETE, LINES, List.of(), List.of()); + + assertThrows(IllegalArgumentException.class, () -> RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void aTruncateEmptiesTheTable() { + RowChange change = new RowChange(RowChange.Kind.TRUNCATE, LINES, List.of(), List.of()); + + assertEquals("TRUNCATE \"sales\".\"order lines\"", RedshiftZeroEtlWriter.rowChangeSql(change)); + } + + @Test + void applyRowChangesBindsUpdateValuesBeforeKeysAndCommits() throws SQLException { + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(statement); + RedshiftZeroEtlWriter writer = writerWith(connection); + RowChange update = new RowChange(RowChange.Kind.UPDATE, LINES, + List.of(value("note", "revised")), + List.of(value("id", "42"), value("line", "7"))); + + writer.applyRowChanges(ACCOUNT_ID, TARGET_ARN, "analytics", List.of(update)); + + InOrder order = inOrder(connection, statement); + order.verify(connection).setAutoCommit(false); + order.verify(connection).prepareStatement(RedshiftZeroEtlWriter.rowChangeSql(update)); + order.verify(statement).setString(1, "revised"); + order.verify(statement).setString(2, "42"); + order.verify(statement).setString(3, "7"); + order.verify(statement).executeUpdate(); + order.verify(statement).close(); + order.verify(connection).commit(); + order.verify(connection).close(); + verify(connection, never()).rollback(); + } + + @Test + void applyRowChangesBindsNullColumnValuesAsSqlNull() throws SQLException { + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(statement); + RedshiftZeroEtlWriter writer = writerWith(connection); + RowChange upsert = new RowChange(RowChange.Kind.UPSERT, LINES, + List.of(value("id", "10"), value("line", "1"), value("note", null)), List.of()); + + writer.applyRowChanges(ACCOUNT_ID, TARGET_ARN, "analytics", List.of(upsert)); + + verify(statement).setString(1, "10"); + verify(statement).setString(2, "1"); + verify(statement).setNull(3, Types.VARCHAR); + verify(statement).executeUpdate(); + verify(connection).commit(); + verify(connection, never()).rollback(); + } + + @Test + void applyRowChangesRollsBackWithoutCommittingWhenALaterChangeFails() throws SQLException { + Connection connection = mock(Connection.class); + PreparedStatement first = mock(PreparedStatement.class); + PreparedStatement second = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(first, second); + when(second.executeUpdate()).thenThrow(new SQLException("duplicate key", "23505")); + RedshiftZeroEtlWriter writer = writerWith(connection); + RowChange upsert = new RowChange(RowChange.Kind.UPSERT, LINES, + List.of(value("id", "1"), value("line", "1"), value("note", "ok")), List.of()); + RowChange delete = new RowChange(RowChange.Kind.DELETE, LINES, List.of(), + List.of(value("id", "2"), value("line", "1"))); + + assertThrows(AwsException.class, + () -> writer.applyRowChanges(ACCOUNT_ID, TARGET_ARN, "analytics", List.of(upsert, delete))); + + InOrder order = inOrder(connection, first, second); + order.verify(connection).setAutoCommit(false); + order.verify(first).executeUpdate(); + order.verify(second).executeUpdate(); + order.verify(connection).rollback(); + order.verify(connection).close(); + verify(connection, never()).commit(); + } + + @Test + void applyRowChangesTranslatesConnectionFailuresAfterRollback() throws SQLException { + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + when(connection.prepareStatement(anyString())).thenReturn(statement); + when(statement.executeUpdate()).thenThrow(new SQLException("connection reset", "08006")); + RedshiftZeroEtlWriter writer = writerWith(connection); + RowChange truncate = new RowChange(RowChange.Kind.TRUNCATE, LINES, List.of(), List.of()); + + assertThrows(TargetUnavailableException.class, + () -> writer.applyRowChanges(ACCOUNT_ID, TARGET_ARN, "analytics", List.of(truncate))); + + verify(connection).rollback(); + verify(connection, never()).commit(); + } + + @Test + void applyRowChangesSkipsOpeningAConnectionWhenThereAreNoChanges() { + RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class); + RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter( + mock(RedshiftService.class), mock(RedshiftZeroEtlEndpoints.class), factory, new ObjectMapper()); + + writer.applyRowChanges(ACCOUNT_ID, TARGET_ARN, "analytics", List.of()); + + verifyNoInteractions(factory); + } +}