feat(redshift): implement remaining COPY options and load diagnostics (#8075)

Stream records through CopyBulkLoader.Cursor in loadRecords and reuse writeRecord, eliminating duplicate decompression, line skipping, record reading, heap tracking and blank line filtering.

Verify Cursor record iteration, line tracking and raw byte capture, along with writeRecord chunking across PostgreSQL CopyData wire frames.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-12 09:10:43 -04:00
1 parent 1e61e16056
commit 59c2b46e1c
22 files changed
+1833 -97

No files matched your search

@@ -0,0 +1,154 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftCopyDiagnosticsIntegrationTest {
@Inject
RedshiftService redshift;
@Inject
S3Service s3;
private final String id = "copy-diagnostics-" + UUID.randomUUID().toString().substring(0, 8);
private Cluster cluster;
@BeforeAll
void start() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for a Redshift cluster");
cluster = redshift.createCluster(id, "dc2.large", "admin", "Secret123");
s3.createBucket(id, "us-east-1");
s3.putObject(id, "private", "private-record\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
}
@AfterAll
void stop() throws Exception {
if (cluster != null) {
redshift.deleteCluster(id);
}
}
@Test
void catalogLockDoesNotStallEachRejectedRowOrReplaceTheCopyError() throws Exception {
s3.putObject(id, "locked", "invalid-number\n".repeat(100).getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection locker = connect("admin"); Statement lock = locker.createStatement();
Connection caller = connect("admin"); Statement copy = caller.createStatement()) {
copy.execute("CREATE TABLE diagnostics_locked_target (id integer)");
copy.setQueryTimeout(5);
locker.setAutoCommit(false);
lock.execute("LOCK TABLE floci_internal.copy_load_errors IN ACCESS EXCLUSIVE MODE");
try {
assertTimeout(Duration.ofSeconds(5), () -> assertEquals(0,
copy.executeUpdate("COPY diagnostics_locked_target FROM 's3://" + id + "/locked' IGNOREALLERRORS")));
SQLException error = assertThrows(SQLException.class, () -> copy.execute(
"COPY diagnostics_locked_target FROM 's3://" + id + "/private'"));
assertEquals("22P02", error.getSQLState());
} finally {
locker.rollback();
}
}
}
@Test
void ordinaryUsersSeeOnlyTheirOwnDiagnosticsAndCannotMutateOrReadBackingData() throws Exception {
try (Connection admin = connect("admin"); Statement owner = admin.createStatement()) {
owner.execute("CREATE ROLE diagnostics_alice LOGIN PASSWORD 'Secret123'");
owner.execute("CREATE ROLE diagnostics_bob LOGIN PASSWORD 'Secret123'");
owner.execute("GRANT diagnostics_bob TO diagnostics_alice");
owner.execute("CREATE TABLE diagnostics_target (id integer)");
owner.execute("GRANT ALL ON diagnostics_target TO diagnostics_alice, diagnostics_bob");
for (String user : new String[]{"diagnostics_alice", "diagnostics_bob"}) {
try (Connection connection = connect(user); Statement statement = connection.createStatement()) {
assertThrows(SQLException.class, () -> statement.execute("COPY diagnostics_target FROM 's3://"
+ id + "/private'"));
assertEquals(1, count(statement, "stl_load_errors"));
try (ResultSet rows = statement.executeQuery("SELECT userid, raw_line FROM stl_load_errors")) {
assertTrue(rows.next());
assertEquals("private-record", rows.getString("raw_line").trim());
int userId = rows.getInt("userid");
assertFalse(rows.next());
assertEquals(userId, scalar(statement, "SELECT oid FROM pg_roles WHERE rolname = current_user"));
}
assertDenied(statement, "SELECT * FROM floci_internal.copy_load_errors");
assertDenied(statement, "DELETE FROM stl_load_errors");
assertDenied(statement, "UPDATE stl_load_errors SET raw_line = 'forged'");
assertDenied(statement, "INSERT INTO stl_load_errors (raw_line) VALUES ('forged')");
assertDenied(statement, "INSERT INTO floci_internal.copy_load_errors (raw_line) VALUES ('forged')");
}
}
try (Connection alice = connect("diagnostics_alice"); Statement statement = alice.createStatement()) {
statement.execute("SET ROLE diagnostics_bob");
assertThrows(SQLException.class, () -> statement.execute("COPY diagnostics_target FROM 's3://"
+ id + "/private'"));
assertEquals(2, count(statement, "stl_load_errors"));
statement.execute("RESET ROLE");
assertEquals(2, count(statement, "stl_load_errors"));
}
assertEquals(3, count(owner, "stl_load_errors"));
assertEquals(3, count(owner, "floci_internal.copy_load_errors"));
// Recreate the older PUBLIC-writable catalog to exercise the upgrade path with retained rows.
owner.execute("DROP VIEW pg_catalog.stl_load_errors");
owner.execute("ALTER TABLE floci_internal.copy_load_errors RENAME TO stl_load_errors");
owner.execute("ALTER TABLE floci_internal.stl_load_errors SET SCHEMA pg_catalog");
owner.execute("GRANT ALL ON pg_catalog.stl_load_errors TO PUBLIC");
try (InputStream input = getClass().getResourceAsStream("/redshift/bootstrap-catalog.sql")) {
assertNotNull(input);
String bootstrap = new String(input.readAllBytes(), StandardCharsets.UTF_8);
owner.execute(bootstrap);
owner.execute(bootstrap);
}
assertEquals(3, count(owner, "stl_load_errors"));
try (Connection alice = connect("diagnostics_alice"); Statement statement = alice.createStatement()) {
assertEquals(2, count(statement, "stl_load_errors"));
assertDenied(statement, "SELECT * FROM floci_internal.copy_load_errors");
assertDenied(statement, "DELETE FROM stl_load_errors");
assertThrows(SQLException.class, () -> statement.execute("COPY diagnostics_target FROM 's3://"
+ id + "/private'"));
assertEquals(3, count(statement, "stl_load_errors"));
}
assertEquals(4, count(owner, "stl_load_errors"));
}
}
private Connection connect(String user) throws SQLException {
return RedshiftConnections.waitForConnection(RedshiftConnections.jdbcUrl(cluster)
+ "?sslmode=disable&gssEncMode=disable", user, "Secret123");
}
private static int count(Statement statement, String table) throws SQLException {
return scalar(statement, "SELECT count(*) FROM " + table);
}
private static int scalar(Statement statement, String sql) throws SQLException {
try (ResultSet rows = statement.executeQuery(sql)) {
assertTrue(rows.next());
return rows.getInt(1);
}
}
private static void assertDenied(Statement statement, String sql) {
SQLException error = assertThrows(SQLException.class, () -> statement.execute(sql));
assertEquals("42501", error.getSQLState());
}
}
@@ -85,6 +85,91 @@ class RedshiftCopyEtlIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void escapedDecimalsConvertInBothBulkAndTolerantLoads(String mode) throws Exception {
String table = table();
put(table, "12\\.345\n\\0612.345\n12\\056345\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (amount decimal(8,2))");
for (String options : List.of("", "ROUNDEC", "IGNOREALLERRORS", "ROUNDEC IGNOREALLERRORS")) {
assertEquals(3, statement.executeUpdate(copy(table, table, options)));
try (ResultSet rows = statement.executeQuery("SELECT min(amount), max(amount) FROM " + table)) {
assertTrue(rows.next());
String expected = options.contains("ROUNDEC") ? "12.35" : "12.34";
assertEquals(expected, rows.getString(1));
assertEquals(expected, rows.getString(2));
}
statement.execute("TRUNCATE " + table);
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void decimalCopyTruncatesByDefaultAndRoundsOnlyWithRoundec(String mode) throws Exception {
String table = table();
put(table, "20.259|text\n-20.255|negative\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (amount decimal(8,2), label text)");
for (String option : List.of("", "ROUNDEC")) {
assertEquals(2, statement.executeUpdate(copy(table, table, option)));
try (ResultSet rows = statement.executeQuery("SELECT amount FROM " + table + " ORDER BY amount")) {
assertTrue(rows.next());
assertEquals(option.isEmpty() ? "-20.25" : "-20.26", rows.getString(1));
assertTrue(rows.next());
assertEquals(option.isEmpty() ? "20.25" : "20.26", rows.getString(1));
}
statement.execute("TRUNCATE " + table);
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void ignoreBlankLinesPreservesWhitespaceAndQuotedNewlines(String mode) throws Exception {
String table = table();
put(table, "\n\r\n\"hello\n\nworld\"\n \n\"\"\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (label text)");
assertEquals(3, statement.executeUpdate(copy(table, table, "CSV IGNOREBLANKLINES")));
assertEquals(3, count(statement, table));
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM " + table + " WHERE label = E'hello\\n\\nworld'")) {
assertTrue(rows.next());
assertEquals(1, rows.getInt(1));
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void loadErrorsSurviveFailedCopyAndExplicitRollback(String mode) throws Exception {
String table = table();
put(table, "id|label\n1|good\nbad|broken\n2|last\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, label text)");
assertThrows(SQLException.class, () -> statement.execute(copy(table, table, "IGNOREHEADER 1")));
assertEquals(0, count(statement, table));
connection.setAutoCommit(false);
assertEquals(2, statement.executeUpdate(copy(table, table, "IGNOREHEADER 1 IGNOREALLERRORS")));
connection.rollback();
connection.setAutoCommit(true);
assertEquals(0, count(statement, table));
try (ResultSet rows = statement.executeQuery("SELECT filename, line_number, colname, raw_line, err_code "
+ "FROM stl_load_errors WHERE filename = 's3://" + id + "/" + table + "'")) {
for (int error = 0; error < 2; error++) {
assertTrue(rows.next());
assertEquals("s3://" + id + "/" + table, rows.getString(1));
assertEquals(3, rows.getLong(2));
assertEquals("id", rows.getString(3).trim());
assertEquals("bad|broken", rows.getString(4).trim());
assertEquals(1207, rows.getInt(5));
}
assertFalse(rows.next());
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void maxErrorLoadsGoodRowsAndCountsErrorsAcrossObjects(String mode) throws Exception {
@@ -0,0 +1,299 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.services.redshift.proxy.CopyBulkLoader.Cursor;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CopyEtlLoaderTest {
@Test
void bulkLoadingDecodesEscapedDecimalsUsingCatalogScales() throws Exception {
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
"12\\.345\n\\0612.345\n12\\056345\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data'");
ByteArrayOutputStream copied = new ByteArrayOutputStream();
try (ServerSocket listener = new ServerSocket(0);
Socket client = new Socket("localhost", listener.getLocalPort()); Socket server = listener.accept()) {
client.setSoTimeout(5000);
server.setSoTimeout(5000);
FakeCopyBackend fake = new FakeCopyBackend(server);
fake.countRowsWith(rows -> rows.lines().count());
CompletableFuture<Void> serving = CompletableFuture.runAsync(() -> {
try {
fake.serveUntilSync(copied, sql -> { }, sql -> sql.startsWith("SELECT a.attname")
? List.of(Arrays.asList("amount", null, "1700", "2")) : List.of());
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
CopyBackendSession backend = new CopyBackendSession(client, frame -> { });
assertEquals(3, CopyEtlLoader.execute(backend, spec, s3, null, null, List.of(), false));
backend.finish(false);
backend.synchronize();
serving.get(5, TimeUnit.SECONDS);
assertEquals("12.34\n12.34\n12.34\n", copied.toString(StandardCharsets.UTF_8));
assertEquals(1, fake.copyCommands());
}
}
@Test
void bulkDiagnosticsMapPastSkippedHeadersAndBlankLines() throws Exception {
runLoad("IGNOREHEADER 1 IGNOREBLANKLINES", "header\n\n1\nbad\n2\n", 0, 1, true);
}
@Test
void bulkDiagnosticsMapPastQuotedCsvNewlines() throws Exception {
// PostgreSQL does not count a quoted LF before the first record establishes its line-ending mode.
runLoad("CSV", "1,\"first\nsecond\"\nbad,value\n", 0, 1, true, 1207, "bad,value", 3, 2);
}
@Test
void bulkDiagnosticsMapQuotedNewlinesAfterTheFirstCsvRecord() throws Exception {
runLoad("CSV", "0,simple\n1,\"first\nsecond\"\nbad,value\n", 0, 1, true, 1207, "bad,value", 4);
}
@Test
void bulkDiagnosticsMapQuotedCsvCarriageReturns() throws Exception {
runLoad("CSV", "1,\"first\r\nsecond\"\r\nbad,value\r\n", 0, 1, true, 1207, "bad,value", 3);
}
@Test
void bulkBackendFailurePrecedesALaterLocalRecordError() throws Exception {
runLoad("", "bad\n" + "1\n".repeat(5000) + "\n", 0, 1, true, 1207, "bad", 1);
}
@Test
void bulkDiagnosticsMapPastEscapedTextNewlines() throws Exception {
runLoad("", "1|first\\\nsecond\nbad|value\n", 0, 1, true, 1207, "bad|value", 3);
}
@Test
void diagnosticsDoNotTurnAnOrdinaryLoadIntoPerRowBackendCommands() throws Exception {
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
"1\n2\n3\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data'");
List<CopyLoadError> errors = new ArrayList<>();
try (ServerSocket listener = new ServerSocket(0);
Socket client = new Socket("localhost", listener.getLocalPort()); Socket server = listener.accept()) {
client.setSoTimeout(5000);
server.setSoTimeout(5000);
FakeCopyBackend fake = new FakeCopyBackend(server);
fake.countRowsWith(rows -> rows.lines().count());
CompletableFuture<Void> serving = CompletableFuture.runAsync(() -> {
try {
fake.serveUntilSync(new ByteArrayOutputStream(), sql -> { },
sql -> sql.startsWith("SELECT (SELECT oid") ? List.of(List.of("10", "42", "99")) : List.of());
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
CopyBackendSession backend = new CopyBackendSession(client, frame -> { });
backend.loadErrorSink(errors::add);
assertEquals(3, CopyEtlLoader.execute(backend, spec, s3, null, null, List.of(), false));
backend.finish(false);
backend.synchronize();
serving.get(5, TimeUnit.SECONDS);
assertEquals(1, fake.copyCommands());
assertEquals(0, fake.rowSavepoints());
assertTrue(errors.isEmpty());
}
}
@Test
void ignoreAllErrorsLoadsGoodRecordsAndLogsRejectedRows() throws Exception {
runLoad("IGNOREHEADER 1 IGNOREALLERRORS", "header\n1\nbad\n2\nbad\n3\n", 3, 2, false);
}
@Test
void firstErrorIsLoggedEvenWhenTheWholeLoadFails() throws Exception {
runLoad("", "1\nbad\n2\n", 0, 1, true);
}
@Test
void maxErrorStillFailsAtItsThreshold() throws Exception {
runLoad("MAXERROR 2", "1\nbad\n2\nbad\n", 0, 2, true);
}
@Test
void ignoreBlankLinesKeepsPhysicalErrorLineNumbers() throws Exception {
runLoad("IGNOREBLANKLINES IGNOREALLERRORS", "\n1\n\r\nbad\n2\n", 2, 1, false);
}
@Test
void blankLinesFailByDefaultAndAreLogged() throws Exception {
runLoad("", "1\n\n2\n", 0, 1, true, 1211);
}
@Test
void ignoreAllErrorsToleratesBlankLinesWhenNotBlankSkipped() throws Exception {
runLoad("IGNOREALLERRORS", "1\n\n2\n", 2, 1, false, 1211, "", 2);
}
@Test
void ignoreAllErrorsDecompressesGzipThroughCursor() throws Exception {
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(compressed)) {
gzip.write("1\nbad\n2\n".getBytes(StandardCharsets.UTF_8));
}
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
compressed.toByteArray(), "application/gzip"));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data' GZIP IGNOREALLERRORS");
List<CopyLoadError> errors = new ArrayList<>();
try (ServerSocket listener = new ServerSocket(0);
Socket client = new Socket("localhost", listener.getLocalPort()); Socket server = listener.accept()) {
client.setSoTimeout(5000);
server.setSoTimeout(5000);
CompletableFuture<Void> serving = CompletableFuture.runAsync(() -> {
try {
FakeCopyBackend fake = new FakeCopyBackend(server);
fake.rejectRows(row -> row.startsWith("bad"));
fake.serveUntilSync(new ByteArrayOutputStream(), sql -> { },
sql -> sql.startsWith("SELECT (SELECT oid") ? List.of(List.of("10", "42", "99")) : List.of());
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
CopyBackendSession backend = new CopyBackendSession(client, frame -> { });
backend.loadErrorSink(errors::add);
assertEquals(2, CopyEtlLoader.execute(backend, spec, s3, null, null, List.of(), false));
backend.finish(false);
backend.synchronize();
serving.get(5, TimeUnit.SECONDS);
assertEquals(1, errors.size());
assertEquals("bad", errors.getFirst().rawLine());
assertEquals(2, errors.getFirst().lineNumber());
}
}
@Test
void cursorReleasesHeapPermitsEvenWhenRecordParsingFails() throws Exception {
int permitsBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
try {
runLoad("", "1\n\n2\n", 0, 1, true, 1211);
} finally {
assertEquals(permitsBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
}
}
@Test
void writeRecordChunksLongRowsAcrossPostgresCopyDataFrames() throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] longRecord = "a".repeat(20000).getBytes(StandardCharsets.UTF_8);
CopyBulkLoader.writeRecord(output, longRecord);
byte[] bytes = output.toByteArray();
assertEquals(20015, bytes.length);
assertEquals('d', bytes[0]);
assertEquals('d', bytes[8197]);
assertEquals('d', bytes[8197 * 2]);
}
@Test
void cursorIteratesTransformedRecordsAndTracksLineAndRaw() throws Exception {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data' CSV IGNOREHEADER 1");
byte[] data = "h1,h2\n1,first\n2,second\n".getBytes(StandardCharsets.UTF_8);
try (Cursor cursor = new Cursor(spec, data, null, null, null, null)) {
byte[] first = cursor.next();
assertNotNull(first);
assertEquals("1,first\n", new String(first, StandardCharsets.UTF_8));
assertEquals(2, cursor.line());
assertEquals("1,first\n", new String(cursor.raw(), StandardCharsets.UTF_8));
byte[] second = cursor.next();
assertNotNull(second);
assertEquals("2,second\n", new String(second, StandardCharsets.UTF_8));
assertEquals(3, cursor.line());
assertEquals("2,second\n", new String(cursor.raw(), StandardCharsets.UTF_8));
assertNull(cursor.next());
}
}
private static void runLoad(String options, String data, long expectedCount, int expectedErrors, boolean failure)
throws Exception {
runLoad(options, data, expectedCount, expectedErrors, failure, 1207);
}
private static void runLoad(String options, String data, long expectedCount, int expectedErrors, boolean failure, int code)
throws Exception {
runLoad(options, data, expectedCount, expectedErrors, failure, code, code == 1211 ? "" : "bad",
options.contains("IGNOREBLANKLINES") ? 4 : options.contains("IGNOREHEADER") ? 3 : 2);
}
private static void runLoad(String options, String data, long expectedCount, int expectedErrors, boolean failure,
int code, String expectedRaw, long expectedLine) throws Exception {
runLoad(options, data, expectedCount, expectedErrors, failure, code, expectedRaw, expectedLine, 0);
}
private static void runLoad(String options, String data, long expectedCount, int expectedErrors, boolean failure,
int code, String expectedRaw, long expectedLine, int backendLine) throws Exception {
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
data.getBytes(StandardCharsets.UTF_8), "text/plain"));
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data' " + options);
List<CopyLoadError> errors = new ArrayList<>();
try (ServerSocket listener = new ServerSocket(0);
Socket client = new Socket("localhost", listener.getLocalPort()); Socket server = listener.accept()) {
client.setSoTimeout(5000);
server.setSoTimeout(5000);
CompletableFuture<Void> serving = CompletableFuture.runAsync(() -> {
try {
FakeCopyBackend fake = new FakeCopyBackend(server);
fake.rejectRows(row -> row.startsWith("bad"));
fake.reportedErrorLine(backendLine);
fake.serveUntilSync(new ByteArrayOutputStream(), sql -> { },
sql -> sql.startsWith("SELECT (SELECT oid") ? List.of(List.of("10", "42", "99")) : List.of());
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
CopyBackendSession backend = new CopyBackendSession(client, frame -> { });
backend.loadErrorSink(errors::add);
if (failure) {
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> CopyEtlLoader.execute(backend, spec, s3, null, null, List.of(), false));
assertEquals(code == 1211 ? "22P04" : "22P02", error.sqlState());
} else {
assertEquals(expectedCount, CopyEtlLoader.execute(backend, spec, s3, null, null, List.of(), false));
}
backend.finish(failure);
backend.synchronize();
serving.get(5, TimeUnit.SECONDS);
assertEquals(expectedErrors, errors.size());
for (CopyLoadError error : errors) {
assertEquals("s3://bucket/data", error.filename());
assertEquals(code == 1211 ? "" : "id", error.column());
assertEquals(expectedRaw, error.rawLine());
assertEquals(code == 1211 ? "" : "bad", error.rawFieldValue());
assertEquals(code, error.code());
assertEquals(42, error.context().sessionId());
assertEquals(99, error.context().tableId());
}
assertEquals(expectedLine, errors.getFirst().lineNumber());
}
}
}
@@ -0,0 +1,110 @@
package io.floci.aws.services.redshift.proxy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class CopyLoadErrorLogTest {
private final CopyLoadErrorLog.ConnectionFactory connections = mock(CopyLoadErrorLog.ConnectionFactory.class);
private final Connection connection = mock(Connection.class);
private final PreparedStatement insert = mock(PreparedStatement.class);
private final Statement settings = mock(Statement.class);
private CopyLoadErrorLog log;
@BeforeEach
void setup() throws Exception {
when(connections.open()).thenReturn(connection);
when(connection.createStatement()).thenReturn(settings);
when(connection.prepareStatement(anyString())).thenReturn(insert);
log = new CopyLoadErrorLog(connections);
}
@Test
void opensLazilyAndReusesAutocommitConnectionAndPreparedStatement() throws Exception {
verifyNoInteractions(connections);
log.accept(error());
log.accept(error());
verify(connections).open();
verify(connection).setAutoCommit(true);
verify(connection).prepareStatement(contains("floci_internal.copy_load_errors"));
verify(insert, times(2)).executeUpdate();
verify(connection, never()).close();
verify(insert, times(2)).setString(11, "private raw record");
}
@Test
void boundsLockAndStatementWaitsBeforeInserting() throws Exception {
log.accept(error());
verify(settings).execute("SET lock_timeout = '250ms'");
verify(settings).execute("SET statement_timeout = '1000ms'");
verify(settings).close();
}
@Test
void failedInsertDisablesDiagnosticsForTheBridgeAndClosesResources() throws Exception {
when(insert.executeUpdate()).thenThrow(new SQLException("locked", "55P03"));
assertDoesNotThrow(() -> log.accept(error()));
assertDoesNotThrow(() -> log.accept(error()));
verify(connections).open();
verify(insert).executeUpdate();
verify(insert).close();
verify(connection).close();
}
@Test
void connectionFailureIsAttemptedOnlyOnce() throws Exception {
when(connections.open()).thenThrow(new SQLException("unavailable"));
assertDoesNotThrow(() -> log.accept(error()));
assertDoesNotThrow(() -> log.accept(error()));
verify(connections).open();
}
@Test
void settingFailureClosesConnectionAndDoesNotInsert() throws Exception {
when(settings.execute(anyString())).thenThrow(new SQLException("settings failed"));
assertDoesNotThrow(() -> log.accept(error()));
verify(connection).close();
verify(connection, never()).prepareStatement(anyString());
}
@Test
void closeIsIdempotentAndPreventsReopening() throws Exception {
log.accept(error());
AutoCloseable closeable = assertInstanceOf(AutoCloseable.class, log);
closeable.close();
closeable.close();
log.accept(error());
verify(insert).close();
verify(connection).close();
verify(connections).open();
verify(insert).executeUpdate();
}
@Test
void closeWithoutErrorsDoesNotConnect() throws Exception {
assertInstanceOf(AutoCloseable.class, log).close();
verifyNoInteractions(connections);
}
@Test
void closeFailureStillClosesConnectionAndRetainsOriginalFailure() throws Exception {
when(insert.executeUpdate()).thenThrow(new SQLException("original"));
doThrow(new SQLException("close failed")).when(insert).close();
assertDoesNotThrow(() -> log.accept(error()));
verify(connection).close();
}
private CopyLoadError error() {
return new CopyLoadError(new CopyLoadError.Context(10, 20, 30, 40, Instant.EPOCH),
"s3://bucket/key", 7, "id", "int4", "", "private raw record", "bad", 1207, "Invalid digit");
}
}
@@ -0,0 +1,69 @@
package io.floci.aws.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class CopyLoadErrorTest {
@Test
void longJsonDiagnosticsKeepTheLastPhysicalLineAndBoundTheRawPreview() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' JSON 'auto'");
String input = "{\r\n\"name\":\"" + "a".repeat(2048) + "\"\r\n}\n";
CopyLoadError diagnostic = CopyLoadError.from(CopyLoadError.Context.create(List.of()), spec, "k", 5,
input.getBytes(StandardCharsets.UTF_8), List.of(),
new S3CopySimulator.S3TransferException("22P04", "bad JSON", null));
assertEquals(7, diagnostic.lineNumber());
assertEquals(1024, diagnostic.rawLine().length());
}
@Test
void backendColumnNamesThatAreNumbersAreNotTreatedAsPositions() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t (\"2\", id) FROM 's3://b/k'");
S3CopySimulator.S3TransferException error = new S3CopySimulator.S3TransferException("23502", "null value", null,
Map.of('c', "2", 'M', "null value"));
CopyLoadError diagnostic = CopyLoadError.from(CopyLoadError.Context.create(List.of()), spec, "k", 1,
"\\N|1\n".getBytes(StandardCharsets.UTF_8), List.of(), error);
assertEquals("2", diagnostic.column());
}
@Test
void transformErrorsResolveReorderedColumnsAndPreserveRawValues() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t (day, id) FROM 's3://b/k' DATEFORMAT 'DD/MM/YYYY'");
List<S3CopySimulator.ColumnInfo> columns = List.of(
S3CopySimulator.columnInfo(Arrays.asList("id", null, "23", null)),
S3CopySimulator.columnInfo(Arrays.asList("day", null, "1082", null)));
S3CopySimulator.S3TransferException error = new S3CopySimulator.S3TransferException("22007", "invalid date", null,
Map.of('c', "1", 'd', "bad-date"));
CopyLoadError diagnostic = CopyLoadError.from(CopyLoadError.Context.create(List.of()), spec, "k", 12,
"bad-date|1\n".getBytes(StandardCharsets.UTF_8), columns, error);
assertEquals("day", diagnostic.column());
assertEquals("date", diagnostic.type());
assertEquals(1205, diagnostic.code());
assertEquals("bad-date", diagnostic.rawFieldValue());
assertEquals("bad-date|1", diagnostic.rawLine());
}
@Test
void catalogScalesFollowTheCopyColumnOrder() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t (amount, id) FROM 's3://b/k'");
List<S3CopySimulator.ColumnInfo> columns = List.of(
S3CopySimulator.columnInfo(Arrays.asList("id", null, "23", null)),
S3CopySimulator.columnInfo(Arrays.asList("amount", null, "1700", "2")));
assertEquals(Arrays.asList(2, null), S3CopySimulator.alignScales(spec, columns));
}
@Test
void diagnosticLimitsReplaceNulsWithoutSplittingUnicodeCharacters() {
assertEquals("a.b", CopyLoadError.limit("a\0b", 100));
assertEquals("a😀", CopyLoadError.limit("a😀b", 2));
}
}
@@ -11,6 +11,29 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CopyRecordReaderTest {
@Test
void physicalLineNumbersIncludeQuotedAndEscapedNewlines() throws IOException {
CopyRecordReader reader = reader("1,\"a\n\nb\"\r\n\r\n2,last\n", "CSV");
assertEquals("1,\"a\n\nb\"\r\n", next(reader));
assertEquals(1, reader.recordLine());
assertEquals("\r\n", next(reader));
assertEquals(4, reader.recordLine());
assertEquals("2,last\n", next(reader));
assertEquals(5, reader.recordLine());
}
@Test
void wholeJsonModeRetainsPrettyPrintedObjectsAndBracesInsideStrings() throws IOException {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' JSON 'auto'");
CopyRecordReader reader = new CopyRecordReader(new ByteArrayInputStream(
"{\n\"name\":\"a}b\"\n}\n{\"name\":\"last\"}".getBytes(StandardCharsets.UTF_8)), spec, true);
assertEquals("{\n\"name\":\"a}b\"\n}\n", next(reader));
assertEquals("{\"name\":\"last\"}\n", next(reader));
assertEquals(4, reader.recordLine());
assertNull(next(reader));
}
private static CopyRecordReader reader(String content, String options) {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data' " + options);
@@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -12,6 +13,93 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class CopyRecordTransformerTest {
@Test
void expandedDecimalsAreBudgetedBeforeTheNextFieldIsWritten() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' CSV");
AtomicInteger observed = new AtomicInteger();
assertThrows(IllegalArgumentException.class, () -> new CopyRecordTransformer(spec, null, null, List.of(0, 0, 0))
.apply("1e3,1e3,1e3\n".getBytes(StandardCharsets.UTF_8), size -> {
observed.set(size);
if (size > 3) {
throw new IllegalArgumentException("Output budget exceeded");
}
}));
assertEquals(4, observed.get());
}
@Test
void decimalScaleUsesTruncationByDefaultAndRoundecRoundsTiesAwayFromZero() {
for (String option : List.of("", "ROUNDEC")) {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' CSV " + option);
byte[] output = new CopyRecordTransformer(spec, null, null, Arrays.asList(2, 2, null))
.apply("20.259,-20.255,20.259\n,,\\N\n".getBytes(StandardCharsets.UTF_8));
assertEquals(option.isEmpty() ? "20.25,-20.25,20.259\n,,\\N\n" : "20.26,-20.26,20.259\n,,\\N\n",
new String(output, StandardCharsets.UTF_8));
}
}
@Test
void textDecimalsDecodeCopyEscapesBeforeTruncationAndRounding() {
String input = "12\\.345|-12\\.345|\\0612.345|12\\056345|12\\x2e345|\\x312.345|12.34\\65\n";
assertEquals("12.34|-12.34|12.34|12.34|12.34|12.34|12.34\n",
applyDecimals("", input, List.of(2, 2, 2, 2, 2, 2, 2)));
assertEquals("12.35|-12.35|12.35|12.35|12.35|12.35|12.35\n",
applyDecimals("ROUNDEC", input, List.of(2, 2, 2, 2, 2, 2, 2)));
}
@Test
void decimalConversionPreservesInvalidTextAndRawNullMarkers() {
String input = "\\N|not\\.numeric|12\\\\.345|12\\.345\n";
assertEquals("\\N|not\\.numeric|12\\\\.345|12.34\n",
applyDecimals("", input, List.of(2, 2, 2, 2)));
assertEquals("12\\.345|12.34\n",
applyDecimals("NULL AS '12\\.345'", "12\\.345|12.345\n", List.of(2, 2)));
assertEquals("\\00012.345|12.345\\b\n",
applyDecimals("", "\\00012.345|12.345\\b\n", List.of(2, 2)));
assertEquals("12.34\n", applyDecimals("", "\\t12.345\\v\n", List.of(2)));
}
@Test
void csvDecimalsKeepLiteralBackslashes() {
String input = "12\\.345,\"12\\.345\",12.345\n";
assertEquals("12\\.345,\"12\\.345\",12.34\n", applyDecimals("CSV", input, List.of(2, 2, 2)));
}
@Test
void convertedDecimalsEscapePointAndDigitDelimiters() {
assertEquals("12\\.34.x\n", applyDecimals("DELIMITER '.'", "12\\.345.x\n", Arrays.asList(2, null)));
assertEquals("12.\\06343x\n", applyDecimals("DELIMITER '3'", "12.\\063453x\n", Arrays.asList(2, null)));
}
@Test
void convertedDecimalsCannotBecomeCustomNullMarkers() {
assertEquals("\\0612.34\n", applyDecimals("NULL AS '12.34'", "12\\.345\n", List.of(2)));
assertEquals("\"12.34\"\n", applyDecimals("CSV NULL AS '12.34'", "12.345\n", List.of(2)));
assertEquals("\\0612\\.34\n",
applyDecimals("DELIMITER '.' NULL AS '12\\.34'", "12\\.345\n", List.of(2)));
assertEquals("\\x312.34\n",
applyDecimals("DELIMITER '1' NULL AS '\\0612.34'", "\\0612.345\n", List.of(2)));
}
private static String applyDecimals(String options, String input, List<Integer> scales) {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' " + options);
byte[] output = new CopyRecordTransformer(spec, null, null, scales)
.apply(input.getBytes(StandardCharsets.UTF_8));
return new String(output, StandardCharsets.UTF_8);
}
@Test
void ignoreBlankLinesDoesNotDiscardWhitespaceOrQuotedEmptyFields() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/k' CSV IGNOREBLANKLINES");
assertEquals("\"a\n\nb\"\n \n\"\"\n,\n",
new String(new CopyRecordTransformer(spec, null).apply(
"\n\r\n\"a\n\nb\"\n \n\"\"\n,\n".getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
}
private static CopyStatementParser.CopyTransforms transforms(
boolean blanks, boolean empty, boolean removeQuotes, boolean truncate, Character invalid) {
return new CopyStatementParser.CopyTransforms(blanks, empty, removeQuotes, truncate, invalid);
@@ -13,6 +13,23 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class CopyStatementParserTest {
@Test
void remainingCopyOptionsAreAcceptedTogether() {
assertNotNull(copyFrom("COPY t FROM 's3://b/k' IGNOREBLANKLINES ROUNDEC IGNOREALLERRORS"));
assertNotNull(copyFrom("COPY t FROM 's3://b/k' CSV IGNOREBLANKLINES ROUNDEC MAXERROR 2"));
assertNotNull(copyFrom("COPY t FROM 's3://b/k' JSON 'auto' IGNOREALLERRORS"));
}
@Test
void ignoreAllErrorsCannotBeCombinedWithMaxErrorOrRepeated() {
assertNull(copyFrom("COPY t FROM 's3://b/k' IGNOREALLERRORS MAXERROR 0"));
assertNull(copyFrom("COPY t FROM 's3://b/k' MAXERROR 2 IGNOREALLERRORS"));
for (String option : List.of("IGNOREALLERRORS", "IGNOREBLANKLINES", "ROUNDEC")) {
assertNull(copyFrom("COPY t FROM 's3://b/k' " + option + " " + option));
assertNull(copyFrom("COPY t FROM 's3://b/k' " + option + "suffix"));
}
}
@Test
void copyAndUnloadAcceptDefaultIamRole() {
CopyStatementParser.S3CopyFrom copy = assertInstanceOf(CopyStatementParser.S3CopyFrom.class,
@@ -6,15 +6,43 @@ import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.ToLongFunction;
/** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */
final class FakeCopyBackend {
private final Socket socket;
private Function<String, List<List<String>>> rows = sql -> List.of();
private Predicate<String> rejectRow = row -> false;
private ToLongFunction<String> rowCount = row -> 1;
private int copyCommands;
private int rowSavepoints;
private int reportedErrorLine;
void reportedErrorLine(int line) {
reportedErrorLine = line;
}
void countRowsWith(ToLongFunction<String> counter) {
rowCount = counter;
}
int copyCommands() {
return copyCommands;
}
int rowSavepoints() {
return rowSavepoints;
}
void rejectRows(Predicate<String> predicate) {
rejectRow = predicate;
}
FakeCopyBackend(Socket socket) {
this.socket = socket;
@@ -45,6 +73,8 @@ final class FakeCopyBackend {
boolean copyCompleted = false;
boolean finishing = false;
int closed = 0;
boolean csvCopy = false;
ByteArrayOutputStream copyRecord = new ByteArrayOutputStream();
PostgresWireDecoder.FrontendMessage message;
while ((message = decoder.nextMessage()) != null) {
if (failed && message.type() != 'S') {
@@ -63,6 +93,9 @@ final class FakeCopyBackend {
}
case 'E' -> {
String sql = portals.get(decoder.decodeExecute(message).portalName());
if (sql.startsWith("SAVEPOINT floci_row_")) {
rowSavepoints++;
}
if (sql.equals("BEGIN")) {
transaction = true;
} else if (sql.equals("COMMIT") || sql.equals("ROLLBACK")) {
@@ -78,12 +111,15 @@ final class FakeCopyBackend {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("22012", "division by zero"));
failed = true;
} else if (sql.startsWith("COPY ")) {
copyCommands++;
csvCopy = sql.contains("FORMAT csv");
PostgresWire.write(out, 'G', new byte[]{0, 0, 0});
} else {
for (List<String> row : rows.apply(sql)) {
List<List<String>> queryRows = rows.apply(sql);
for (List<String> row : queryRows) {
PostgresWire.write(out, 'D', dataRow(row));
}
if (sql.startsWith("SELECT a.attname")) {
if (sql.startsWith("SELECT a.attname") && queryRows.isEmpty()) {
PostgresWire.write(out, 'D', new byte[]{0, 3}, PostgresWire.int32(2), new byte[]{'i', 'd'},
PostgresWire.int32(-1), PostgresWire.int32(2), new byte[]{'2', '3'});
}
@@ -94,13 +130,46 @@ final class FakeCopyBackend {
observer.executed(sql);
}
}
case 'd' -> copied.write(message.body());
case 'd' -> copyRecord.write(message.body());
case 'c' -> {
PostgresWire.write(out, 'C', PostgresWire.cStringBytes("COPY 1"));
String content = copyRecord.toString(StandardCharsets.UTF_8);
List<String> records = content.lines().toList();
int rejected = -1;
for (int index = 0; index < records.size(); index++) {
if (rejectRow.test(records.get(index))) {
rejected = index;
break;
}
}
if (rejected >= 0) {
int errorLine = rejected + 1;
if (!csvCopy) {
for (int index = 0; index < rejected; index++) {
String prior = records.get(index);
int slashes = 0;
for (int offset = prior.length() - 1; offset >= 0 && prior.charAt(offset) == '\\'; offset--) {
slashes++;
}
if ((slashes % 2) != 0) {
errorLine--;
}
}
}
recordError(out, reportedErrorLine > 0 ? reportedErrorLine : errorLine);
failed = true;
} else {
copied.write(copyRecord.toByteArray());
PostgresWire.write(out, 'C', PostgresWire.cStringBytes("COPY " + rowCount.applyAsLong(content)));
}
copyRecord.reset();
copyCompleted = true;
}
case 'f' -> {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("57014", "COPY input failed"));
if (copyRecord.toString(StandardCharsets.UTF_8).lines().anyMatch(rejectRow)) {
recordError(out, 1);
} else {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("57014", "COPY input failed"));
}
failed = true;
}
case 'C' -> {
@@ -132,10 +201,21 @@ final class FakeCopyBackend {
void executed(String sql) throws Exception;
}
private static void recordError(OutputStream out, int line) throws Exception {
byte[] error = S3CopySimulator.errorBody("22P02", "invalid integer");
PostgresWire.write(out, 'E', Arrays.copyOf(error, error.length - 1),
new byte[]{'W'}, PostgresWire.cStringBytes("COPY events, line " + line
+ ", column id: \"bad\""), new byte[1]);
}
private static byte[] dataRow(List<String> row) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()});
for (String value : row) {
if (value == null) {
bytes.write(PostgresWire.int32(-1));
continue;
}
byte[] field = value.getBytes(StandardCharsets.UTF_8);
bytes.write(PostgresWire.int32(field.length));
bytes.write(field);