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

@@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
/** Internal COPY commands use named extended statements so client statements and portals survive. */
final class CopyBackendSession {
@@ -24,6 +25,15 @@ final class CopyBackendSession {
private String activeStatement;
private boolean parsed;
private char readyStatus = 'I';
private Consumer<CopyLoadError> loadErrorSink;
void loadErrorSink(Consumer<CopyLoadError> sink) {
loadErrorSink = sink;
}
Consumer<CopyLoadError> loadErrorSink() {
return loadErrorSink;
}
CopyBackendSession(Socket backend, FrameSink asynchronous) {
this.backend = backend;
@@ -154,6 +164,11 @@ final class CopyBackendSession {
// CopyFail must be consumed before recovery can issue an internal Sync.
}
} catch (S3TransferException expected) {
if (!"57014".equals(expected.sqlState())) {
// A server failure may already be queued before the producer fails on a later record.
expected.addSuppressed(exception);
throw expected;
}
exception.addSuppressed(expected);
}
throw exception;
@@ -209,7 +224,7 @@ final class CopyBackendSession {
failed = true;
Map<Character, String> fields = PostgresWire.parseFields(response.body(), 0);
throw new S3TransferException(fields.getOrDefault('C', "XX000"),
fields.getOrDefault('M', "COPY backend command failed"), null);
fields.getOrDefault('M', "COPY backend command failed"), null, fields);
}
if (response.type() == '1') {
parsed = true;
@@ -0,0 +1,234 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.ColumnInfo;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.CopyInput;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException;
import io.floci.aws.services.s3.model.S3Object;
import org.jboss.logging.Logger;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Streams ordinary loads with one backend COPY per object, retaining record-sized transformation limits. */
final class CopyBulkLoader {
private static final Logger LOG = Logger.getLogger(CopyBulkLoader.class);
private static final Pattern BACKEND_LINE = Pattern.compile("(?:^|\\n)COPY [^\\n]*?, line ([0-9]+)(?:,|\\n|$)");
private CopyBulkLoader() {
}
static long load(CopyBackendSession backend, CopyInput input, List<String> discovered, List<Integer> widths,
List<CopyRecordTransformer.ColumnKind> kinds, List<Integer> scales,
List<ColumnInfo> catalog, CopyLoadError.Context context) throws IOException {
CopyStatementParser.S3CopyFrom spec = input.spec();
List<String> jsonColumns = S3CopySimulator.jsonColumns(spec, discovered);
String sql = S3CopySimulator.copyBackendSql(spec, discovered);
long accepted = 0;
for (String key : input.keys()) {
S3CopySimulator.authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), key);
S3Object object = input.readObject(key);
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
try (Cursor cursor = new Cursor(spec, data, jsonColumns, widths, kinds, scales)) {
try {
accepted += backend.copy(sql, output -> {
// Buffer COPY frames too: a short record must not require its own socket write.
OutputStream buffered = new BufferedOutputStream(output, 8192);
try {
byte[] record;
while ((record = cursor.next()) != null) {
writeRecord(buffered, record);
}
} catch (IOException | RuntimeException exception) {
try {
// Finish any buffered frame before CopyBackendSession sends CopyFail.
buffered.flush();
} catch (IOException flushFailure) {
exception.addSuppressed(flushFailure);
}
throw exception;
}
buffered.flush();
});
} catch (S3TransferException exception) {
if (context != null && CopyEtlLoader.isRecordError(exception)) {
long backendLine = backendLine(exception);
if (backendLine >= 1) {
cursor.close();
diagnose(backend, context, spec, key, data, jsonColumns, widths, kinds, scales,
catalog, exception, backendLine);
} else {
CopyEtlLoader.recordError(backend, context, spec, key, cursor.line(), cursor.raw(), catalog, exception);
}
}
throw exception;
}
}
}
return accepted;
}
static void writeRecord(OutputStream output, byte[] record) throws IOException {
for (int offset = 0; offset < record.length; offset += 8192) {
int length = Math.min(8192, record.length - offset);
byte[] chunk = new byte[length];
System.arraycopy(record, offset, chunk, 0, length);
S3CopySimulator.writeCopyData(output, chunk, length);
}
}
private static void diagnose(CopyBackendSession backend, CopyLoadError.Context context,
CopyStatementParser.S3CopyFrom spec, String key, byte[] data,
List<String> jsonColumns, List<Integer> widths,
List<CopyRecordTransformer.ColumnKind> kinds, List<Integer> scales,
List<ColumnInfo> catalog, S3TransferException failure, long targetLine) {
// Replay only the failed object's immutable input bytes, never re-read a possibly replaced S3 object.
try (Cursor cursor = new Cursor(spec, data, jsonColumns, widths, kinds, scales)) {
BackendLines lines = new BackendLines(spec.csv() || spec.jsonAuto());
byte[] record;
while ((record = cursor.next()) != null) {
if (lines.advance(record) >= targetLine) {
CopyEtlLoader.recordError(backend, context, spec, key, cursor.line(), cursor.raw(), catalog, failure);
return;
}
}
} catch (IOException | RuntimeException exception) {
LOG.debugv(exception, "Unable to locate COPY diagnostic in {0}, backend line {1}", key, targetLine);
}
CopyEtlLoader.recordError(backend, context, spec, key, -1, new byte[0], catalog, failure);
}
private static long backendLine(S3TransferException failure) {
Matcher match = BACKEND_LINE.matcher(failure.fields().getOrDefault('W', ""));
if (match.find()) {
try {
return Long.parseLong(match.group(1));
} catch (NumberFormatException ignored) {
// An unrepresentable backend line cannot be mapped reliably to the input object.
}
}
return -1;
}
private static final class BackendLines {
private final boolean csv;
private long line;
private boolean endingKnown;
private boolean lineFeedEnding;
BackendLines(boolean csv) {
this.csv = csv;
}
long advance(byte[] record) {
line++;
if (!csv) {
return line;
}
boolean quoted = false;
for (byte value : record) {
if (value == '"') {
quoted = !quoted;
}
if (quoted) {
// PostgreSQL counts CR until the first record establishes its line-ending convention.
if (value == (lineFeedEnding ? '\n' : '\r')) {
line++;
}
} else if (value == '\r' || value == '\n') {
if (!endingKnown) {
endingKnown = true;
lineFeedEnding = value == '\n';
}
break;
}
}
return line;
}
}
static final class Cursor implements AutoCloseable {
private final CopyStatementParser.S3CopyFrom spec;
private final InputStream source;
private final CopyRecordReader records;
private final List<String> jsonColumns;
private final List<Integer> widths;
private final List<CopyRecordTransformer.ColumnKind> kinds;
private final List<Integer> scales;
private final int[] heldMib = new int[]{0};
private byte[] raw = new byte[0];
private long line;
Cursor(CopyStatementParser.S3CopyFrom spec, byte[] data, List<String> jsonColumns,
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds, List<Integer> scales) throws IOException {
this.spec = spec;
this.jsonColumns = jsonColumns;
this.widths = widths;
this.kinds = kinds;
this.scales = scales;
source = CopySourceInputStream.open(new ByteArrayInputStream(data), spec.gzip());
try {
S3CopySimulator.skipLines(source, spec.headerLines());
} catch (IOException | RuntimeException exception) {
source.close();
throw exception;
}
records = new CopyRecordReader(source, spec, !spec.transforms().toleratesErrors());
}
byte[] next() throws IOException {
while (true) {
releaseHeap();
try {
raw = records.next(wanted -> CopyEtlLoader.acquireTransformHeap(heldMib, wanted));
} catch (S3TransferException exception) {
releaseHeap();
raw = records.lastRecord();
line = records.recordLine() + spec.headerLines();
throw exception;
}
line = records.recordLine() + spec.headerLines();
if (raw == null) {
raw = new byte[0];
return null;
}
if (spec.transforms().ignoreBlankLines() && CopyEtlLoader.isBlankLine(raw)) {
continue;
}
try {
CopyEtlLoader.acquireTransformHeap(heldMib, (int) ((raw.length * 2L) / (1024 * 1024)) + 1);
return CopyEtlLoader.transform(spec, raw, jsonColumns, widths, kinds, scales, heldMib);
} catch (RuntimeException exception) {
releaseHeap();
throw exception;
}
}
}
byte[] raw() {
return raw;
}
long line() {
return line;
}
@Override
public void close() throws IOException {
releaseHeap();
source.close();
}
private void releaseHeap() {
if (heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
heldMib[0] = 0;
}
}
}
}
@@ -4,6 +4,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.redshift.proxy.CopyBulkLoader.Cursor;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.ColumnInfo;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.CopyInput;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException;
@@ -20,6 +21,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
/** Executes COPY transformations and error tolerance on the caller's PostgreSQL 15 session. */
@@ -33,10 +35,17 @@ final class CopyEtlLoader {
static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
char status, IntConsumer onStatusChange) throws IOException {
return runSimple(client, socket, spec, s3, iam, account, roles, status, onStatusChange, null);
}
static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3Statement spec,
S3Service s3, IamService iam, String account, List<String> roles,
char status, IntConsumer onStatusChange, Consumer<CopyLoadError> errorSink) throws IOException {
CopyBackendSession backend = new CopyBackendSession(socket, response -> {
client.getOutputStream().write(response.toPacketBytes());
client.getOutputStream().flush();
});
backend.loadErrorSink(errorSink);
long accepted = 0;
S3TransferException failure = null;
try {
@@ -118,17 +127,19 @@ final class CopyEtlLoader {
List<Integer> widths = spec.transforms().truncateColumns() ? S3CopySimulator.alignMaxBytes(spec, catalog) : null;
List<CopyRecordTransformer.ColumnKind> kinds = spec.transforms().needsColumnTypes()
? S3CopySimulator.alignKinds(spec, catalog) : null;
List<Integer> scales = S3CopySimulator.alignScales(spec, catalog);
CopyLoadError.Context context = backend.loadErrorSink() == null ? null : CopyLoadError.Context.create(
backend.query("SELECT (SELECT oid FROM pg_roles WHERE rolname = session_user), pg_backend_pid(), "
+ "to_regclass(" + PostgresWire.quoteLiteral(spec.targetTable()) + ")::oid"));
CopyInput input = exactObject
? S3CopySimulator.prepareObjectCopy(spec, s3, iam, account, roles, expectedETag, versionId)
: S3CopySimulator.prepareCopy(spec, s3, iam, account, roles);
try {
if (!spec.transforms().toleratesErrors()) {
return backend.copy(S3CopySimulator.copyBackendSql(spec, discovered),
output -> S3CopySimulator.streamCopyInput(input, discovered, widths, kinds, output));
}
try {
return RequestScopes.callAsChecked(S3CopySimulator.keyAccount(spec, s3, iam),
() -> loadRecords(backend, input, discovered, widths, kinds));
() -> spec.transforms().toleratesErrors()
? loadRecords(backend, input, discovered, widths, kinds, scales, catalog, context)
: CopyBulkLoader.load(backend, input, discovered, widths, kinds, scales, catalog, context));
} catch (IOException | RuntimeException exception) {
throw exception;
} catch (Exception exception) {
@@ -151,7 +162,7 @@ final class CopyEtlLoader {
return catalog;
}
private static void acquireTransformHeap(int[] heldMib, int wantedMib) {
static void acquireTransformHeap(int[] heldMib, int wantedMib) {
while (heldMib[0] < wantedMib) {
if (!S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
throw new S3TransferException("53400", "COPY memory budget exhausted; retry shortly", null);
@@ -161,7 +172,8 @@ final class CopyEtlLoader {
}
private static long loadRecords(CopyBackendSession backend, CopyInput input, List<String> discovered,
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds)
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds,
List<Integer> scales, List<ColumnInfo> catalog, CopyLoadError.Context context)
throws IOException {
CopyStatementParser.S3CopyFrom spec = input.spec();
List<String> jsonColumns = S3CopySimulator.jsonColumns(spec, discovered);
@@ -173,54 +185,47 @@ final class CopyEtlLoader {
S3CopySimulator.authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), key);
S3Object object = input.readObject(key);
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
try (InputStream raw = new ByteArrayInputStream(data);
InputStream source = CopySourceInputStream.open(raw, spec.gzip())) {
S3CopySimulator.skipLines(source, spec.headerLines());
CopyRecordReader records = new CopyRecordReader(source, spec);
int[] heldMib = new int[]{0};
try {
try (Cursor cursor = new Cursor(spec, data, jsonColumns, widths, kinds, scales)) {
while (true) {
byte[] record;
while ((record = records.next(wantedMib -> acquireTransformHeap(heldMib, wantedMib))) != null) {
backend.execute("SAVEPOINT " + rowSavepoint);
try {
acquireTransformHeap(heldMib, (int) ((record.length * 2L) / (1024 * 1024)) + 1);
byte[] transformed = transform(spec, record, jsonColumns, widths, kinds, heldMib);
accepted += backend.copy(sql, output -> {
for (int offset = 0; offset < transformed.length; offset += 8192) {
int length = Math.min(8192, transformed.length - offset);
byte[] chunk = new byte[length];
System.arraycopy(transformed, offset, chunk, 0, length);
S3CopySimulator.writeCopyData(output, chunk, length);
}
});
} catch (S3TransferException exception) {
backend.recover();
backend.execute("ROLLBACK TO SAVEPOINT " + rowSavepoint);
if (!RECORD_ERRORS.contains(exception.sqlState()) || ++rejected >= spec.transforms().maxError()) {
throw exception;
}
} finally {
if (heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
heldMib[0] = 0;
}
try {
record = cursor.next();
} catch (S3TransferException exception) {
recordError(backend, context, spec, key, cursor.line(), cursor.raw(), catalog, exception);
if (isRecordError(exception) && (spec.transforms().ignoreAllErrors()
|| ++rejected < spec.transforms().maxError())) {
continue;
}
backend.execute("RELEASE SAVEPOINT " + rowSavepoint);
throw exception;
}
} finally {
if (heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
heldMib[0] = 0;
if (record == null) {
break;
}
backend.execute("SAVEPOINT " + rowSavepoint);
try {
accepted += backend.copy(sql, output -> CopyBulkLoader.writeRecord(output, record));
} catch (S3TransferException exception) {
backend.recover();
backend.execute("ROLLBACK TO SAVEPOINT " + rowSavepoint);
recordError(backend, context, spec, key, cursor.line(), cursor.raw(), catalog, exception);
if (!isRecordError(exception) || (!spec.transforms().ignoreAllErrors()
&& ++rejected >= spec.transforms().maxError())) {
throw exception;
}
}
backend.execute("RELEASE SAVEPOINT " + rowSavepoint);
}
}
}
return accepted;
}
private static byte[] transform(CopyStatementParser.S3CopyFrom spec, byte[] record, List<String> jsonColumns,
static byte[] transform(CopyStatementParser.S3CopyFrom spec, byte[] record, List<String> jsonColumns,
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds,
int[] heldMib) throws IOException {
List<Integer> scales, int[] heldMib) throws IOException {
if (!spec.jsonAuto() && isBlankLine(record)) {
throw new S3TransferException("22P04", "COPY input line contained no data", null);
}
if (spec.jsonAuto()) {
ByteArrayOutputStream csv = new ByteArrayOutputStream();
OutputStream bounded = new OutputStream() {
@@ -250,16 +255,42 @@ final class CopyEtlLoader {
}
};
JsonLinesToCsvConverter.convert(new ByteArrayInputStream(record), jsonColumns, bounded, spec.jsonAutoIgnoreCase());
return csv.toByteArray();
CopyStatementParser.S3CopyFrom csvSpec = new CopyStatementParser.S3CopyFrom(spec.targetTable(),
spec.columns(), spec.bucket(), spec.keyOrPrefix(), ",", 0, false, true, null, null,
false, false, false, spec.transforms());
return new CopyRecordTransformer(csvSpec, widths, kinds, scales).apply(csv.toByteArray(), bytes -> {
checkOutputBudget(bytes, record.length + 2L * csv.size(), heldMib);
});
}
return new CopyRecordTransformer(spec, widths, kinds).apply(record, bytes -> {
if (bytes > S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException("54000", "COPY transformed record exceeds the size limit", null);
}
if (heldMib != null) {
acquireTransformHeap(heldMib, (int) ((record.length + 2L * bytes) / (1024 * 1024)) + 1);
}
return new CopyRecordTransformer(spec, widths, kinds, scales).apply(record, bytes -> {
checkOutputBudget(bytes, record.length, heldMib);
});
}
private static void checkOutputBudget(int bytes, long inputBytes, int[] heldMib) {
if (bytes > S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException("54000", "COPY transformed record exceeds the size limit", null);
}
if (heldMib != null) {
acquireTransformHeap(heldMib, (int) ((inputBytes + 2L * bytes) / (1024 * 1024)) + 1);
}
}
static boolean isBlankLine(byte[] record) {
return record.length == 1 && (record[0] == '\n' || record[0] == '\r')
|| record.length == 2 && record[0] == '\r' && record[1] == '\n';
}
static boolean isRecordError(S3TransferException exception) {
return RECORD_ERRORS.contains(exception.sqlState());
}
static void recordError(CopyBackendSession backend, CopyLoadError.Context context,
CopyStatementParser.S3CopyFrom spec, String key, long line, byte[] record,
List<ColumnInfo> catalog, S3TransferException exception) {
if (context != null && RECORD_ERRORS.contains(exception.sqlState())) {
backend.loadErrorSink().accept(CopyLoadError.from(context, spec, key, line, record, catalog, exception));
}
}
}
@@ -0,0 +1,116 @@
package io.floci.aws.services.redshift.proxy;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.ColumnInfo;
import io.floci.aws.services.redshift.proxy.S3CopySimulator.S3TransferException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/** A load diagnostic is independent of the transaction that attempted the load. */
record CopyLoadError(Context context, String filename, long lineNumber, String column, String type,
String columnLength, String rawLine, String rawFieldValue, int code, String reason) {
private static final AtomicInteger QUERY_IDS = new AtomicInteger();
record Context(int userId, int sessionId, long tableId, int queryId, Instant started) {
static Context create(List<List<String>> rows) {
List<String> values = rows.isEmpty() ? List.of("0", "0", "0") : rows.getFirst();
return new Context(Integer.parseInt(values.get(0)), Integer.parseInt(values.get(1)),
Long.parseLong(values.get(2)), QUERY_IDS.incrementAndGet(), Instant.now());
}
}
static CopyLoadError from(Context context, CopyStatementParser.S3CopyFrom spec, String key, long line,
byte[] record, List<ColumnInfo> columns, S3TransferException error) {
String column = error.fields().getOrDefault('c', "");
boolean backendError = error.fields().containsKey('M');
String rawField = backendError ? "" : error.fields().getOrDefault('d', "");
String detail = error.fields().getOrDefault('W', "");
int marker = detail.lastIndexOf(", column ");
if (column.isEmpty() && marker >= 0) {
int end = detail.indexOf(": ", marker + 9);
if (end >= 0) {
column = detail.substring(marker + 9, end);
rawField = detail.substring(end + 2);
if (rawField.startsWith("\"") && rawField.endsWith("\"")) {
rawField = rawField.substring(1, rawField.length() - 1);
}
}
}
List<String> names = spec.columns().isEmpty() ? columns.stream().map(ColumnInfo::name).toList()
: spec.columns().stream().map(S3CopySimulator::normalizeColumnName).toList();
if (!backendError && column.matches("[0-9]+")) {
int index = Integer.parseInt(column) - 1;
column = index >= 0 && index < names.size() ? names.get(index) : "";
}
String name = column;
ColumnInfo info = columns.stream().filter(value -> value.name().equals(name)).findFirst().orElse(null);
String type = info == null ? "" : typeName(info.typeOid());
String length = info != null && info.maxBytes() != null ? info.maxBytes().toString() : "";
int contentEnd = record.length;
while (contentEnd > 0 && (record[contentEnd - 1] == '\r' || record[contentEnd - 1] == '\n')) {
contentEnd--;
}
String raw = new String(record, 0, Math.min(contentEnd, 1024), StandardCharsets.UTF_8);
if (spec.jsonAuto()) {
boolean afterCarriageReturn = false;
for (int index = 0; index < contentEnd; index++) {
byte value = record[index];
if (value == '\r' || (value == '\n' && !afterCarriageReturn)) {
line++;
}
afterCarriageReturn = value == '\r';
}
}
return new CopyLoadError(context, limit("s3://" + spec.bucket() + "/" + key, 256), line,
limit(column, 127), type, length, ascii(raw, 1024), ascii(rawField, 1024),
errorCode(error.sqlState(), type, raw, error.getMessage()), limit(error.getMessage(), 100));
}
private static int errorCode(String state, String type, String raw, String message) {
return switch (state) {
case "22003" -> 1204;
case "22007", "22008" -> type.equals("timestamp") ? 1206 : 1205;
case "22001" -> 1204;
case "22021" -> 1220;
case "23502" -> 1213;
case "22P02" -> switch (type) {
case "numeric" -> 1209;
case "float4", "float8" -> 1208;
case "bool" -> 1210;
default -> 1207;
};
default -> raw.isEmpty() ? 1211 : message.contains("missing data for column") ? 1203
: message.contains("extra data after last expected column") ? 1202 : 1200;
};
}
private static String typeName(String oid) {
return switch (oid == null ? "" : oid) {
case "16" -> "bool";
case "20" -> "int8";
case "21" -> "int2";
case "23" -> "int4";
case "700" -> "float4";
case "701" -> "float8";
case "1700" -> "numeric";
case "1082" -> "date";
case "1114", "1184" -> "timestamp";
case "1042" -> "bpchar";
case "1043" -> "varchar";
case "25" -> "text";
default -> "";
};
}
static String limit(String value, int size) {
String cleaned = value == null ? "" : value.replace('\0', '.');
return cleaned.codePointCount(0, cleaned.length()) <= size ? cleaned
: cleaned.substring(0, cleaned.offsetByCodePoints(0, size));
}
private static String ascii(String value, int size) {
return limit(value, size).replaceAll("[^\\x00-\\x7f]", ".");
}
}
@@ -0,0 +1,91 @@
package io.floci.aws.services.redshift.proxy;
import org.jboss.logging.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.function.Consumer;
/** Uses an autocommit connection so COPY rollback cannot erase diagnostics. */
final class CopyLoadErrorLog implements Consumer<CopyLoadError>, AutoCloseable {
private static final Logger LOG = Logger.getLogger(CopyLoadErrorLog.class);
private static final String INSERT = "INSERT INTO floci_internal.copy_load_errors "
+ "(userid, session, tbl, query, starttime, filename, line_number, colname, type, col_length, "
+ "raw_line, raw_field_value, err_code, err_reason, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
private final ConnectionFactory connections;
private Connection connection;
private PreparedStatement statement;
private boolean closed;
CopyLoadErrorLog(ConnectionFactory connections) {
this.connections = connections;
}
@Override
public void accept(CopyLoadError error) {
if (closed) {
return;
}
try {
if (statement == null) {
connection = connections.open();
connection.setAutoCommit(true);
try (Statement settings = connection.createStatement()) {
settings.execute("SET lock_timeout = '250ms'");
settings.execute("SET statement_timeout = '1000ms'");
}
statement = connection.prepareStatement(INSERT);
}
statement.setInt(1, error.context().userId());
statement.setInt(2, error.context().sessionId());
statement.setLong(3, error.context().tableId());
statement.setInt(4, error.context().queryId());
statement.setObject(5, LocalDateTime.ofInstant(error.context().started(), ZoneOffset.UTC));
statement.setString(6, error.filename());
statement.setLong(7, error.lineNumber());
statement.setString(8, error.column());
statement.setString(9, error.type());
statement.setString(10, error.columnLength());
statement.setString(11, error.rawLine());
statement.setString(12, error.rawFieldValue());
statement.setInt(13, error.code());
statement.setString(14, error.reason());
statement.executeUpdate();
} catch (SQLException exception) {
LOG.warnv(exception, "Unable to record COPY load error for {0} at line {1}", error.filename(), error.lineNumber());
// A caller may hold the catalog lock. Do not wait again for every rejected row.
close();
}
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
if (statement != null) {
try {
statement.close();
} catch (SQLException exception) {
LOG.debugv(exception, "Unable to close COPY load error statement");
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException exception) {
LOG.debugv(exception, "Unable to close COPY load error connection");
}
}
}
@FunctionalInterface
interface ConnectionFactory {
Connection open() throws SQLException;
}
}
@@ -14,11 +14,21 @@ final class CopyRecordReader {
private final boolean removeQuotes;
private final boolean json;
private final int delimiter;
private final boolean jsonLines;
private long nextLine = 1;
private long recordLine = 1;
private boolean afterCarriageReturn;
private byte[] lastRecord = new byte[0];
CopyRecordReader(InputStream input, CopyStatementParser.S3CopyFrom spec) {
this(input, spec, false);
}
CopyRecordReader(InputStream input, CopyStatementParser.S3CopyFrom spec, boolean wholeJson) {
this.input = new PushbackInputStream(input, 1);
csv = spec.csv();
json = spec.jsonAuto();
jsonLines = !wholeJson;
removeQuotes = spec.transforms().removeQuotes();
String separator = spec.delimiter() != null ? spec.delimiter() : (csv ? "," : "|");
delimiter = separator.getBytes(StandardCharsets.UTF_8)[0] & 0xff;
@@ -30,15 +40,45 @@ final class CopyRecordReader {
byte[] next(IntConsumer memoryTracker) throws IOException {
ByteArrayOutputStream record = new ByteArrayOutputStream();
recordLine = nextLine;
int quote = 0;
int depth = 0;
boolean jsonString = false;
boolean jsonEscape = false;
boolean fieldStart = true;
int value;
while ((value = input.read()) != -1) {
if (json && !jsonLines && record.size() == 0 && Character.isWhitespace(value)) {
trackLine(value);
recordLine = nextLine;
continue;
}
append(record, value, memoryTracker);
if (json) {
if (value == '\n') {
if (jsonLines && value == '\n') {
return record.toByteArray();
}
if (!jsonLines) {
if (jsonEscape) {
jsonEscape = false;
} else if (jsonString && value == '\\') {
jsonEscape = true;
} else if (value == '"') {
jsonString = !jsonString;
} else if (!jsonString) {
if (value == '{' || value == '[') {
depth++;
} else if (value == '}' || value == ']') {
depth--;
if (depth == 0) {
record.write('\n');
return record.toByteArray();
}
} else if (value == '\n' && depth == 0) {
return record.toByteArray();
}
}
}
continue;
}
if (!csv && value == '\\') {
@@ -82,6 +122,7 @@ final class CopyRecordReader {
}
}
if (quote != 0) {
lastRecord = record.toByteArray();
throw new S3CopySimulator.S3TransferException("22P04", "COPY quoted field has no closing quote", null);
}
if (record.size() == 0) {
@@ -91,7 +132,22 @@ final class CopyRecordReader {
return record.toByteArray();
}
private static void append(ByteArrayOutputStream record, int value, IntConsumer memoryTracker) {
long recordLine() {
return recordLine;
}
byte[] lastRecord() {
return lastRecord;
}
private void trackLine(int value) {
if (value == '\r' || (value == '\n' && !afterCarriageReturn)) {
nextLine++;
}
afterCarriageReturn = value == '\r';
}
private void append(ByteArrayOutputStream record, int value, IntConsumer memoryTracker) {
if (record.size() >= S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3CopySimulator.S3TransferException("54000", "COPY record exceeds the transform size limit", null);
}
@@ -99,5 +155,6 @@ final class CopyRecordReader {
memoryTracker.accept((record.size() / (1024 * 1024)) + 1);
}
record.write(value);
trackLine(value);
}
}
@@ -1,9 +1,12 @@
package io.floci.aws.services.redshift.proxy;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.IntConsumer;
/**
@@ -35,6 +38,7 @@ final class CopyRecordTransformer {
private final List<Integer> columnMaxBytes;
private final List<ColumnKind> columnKinds;
private final boolean emptyNullString;
private final List<Integer> columnScales;
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes) {
this(spec, columnMaxBytes, null);
@@ -42,6 +46,12 @@ final class CopyRecordTransformer {
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
List<ColumnKind> columnKinds) {
this(spec, columnMaxBytes, columnKinds, null);
}
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
List<ColumnKind> columnKinds, List<Integer> columnScales) {
this.columnScales = columnScales;
this.columnKinds = columnKinds;
this.emptyNullString = spec.nullAs() != null && spec.nullAs().isEmpty();
this.transforms = spec.transforms();
@@ -61,7 +71,7 @@ final class CopyRecordTransformer {
byte[] data = transforms.invalidCharReplacement() != null
? sanitizeUtf8(input, (byte) transforms.invalidCharReplacement().charValue())
: input;
if (!transforms.fieldLevel()) {
if (!transforms.fieldLevel() && (columnScales == null || columnScales.stream().allMatch(scale -> scale == null))) {
if (onOutputBytes != null) {
onOutputBytes.accept(data.length);
}
@@ -76,7 +86,7 @@ final class CopyRecordTransformer {
ByteArrayOutputStream out = new ByteArrayOutputStream(data.length + 16);
int position = 0;
while (position < data.length) {
position = transformRecord(data, position, out);
position = transformRecord(data, position, out, onOutputBytes);
if (onOutputBytes != null) {
onOutputBytes.accept(out.size());
}
@@ -131,12 +141,29 @@ final class CopyRecordTransformer {
return overlongOrOutOfRange ? 0 : length;
}
private int transformRecord(byte[] data, int start, ByteArrayOutputStream out) {
private int transformRecord(byte[] data, int start, ByteArrayOutputStream out, IntConsumer onOutputBytes) {
if (transforms.ignoreBlankLines()) {
if (data[start] == NEWLINE) {
return start + 1;
}
if (isCrlfAt(data, start)) {
return Math.min(start + 2, data.length);
}
}
int position = start;
int column = 0;
while (true) {
Field field = scanField(data, position);
writeField(field, column, out);
try {
writeField(field, column, out);
} catch (S3CopySimulator.S3TransferException error) {
throw new S3CopySimulator.S3TransferException(error.sqlState(), error.getMessage(), error,
Map.of('c', Integer.toString(column + 1), 'd',
new String(field.value(), 0, Math.min(field.value().length, 1024), StandardCharsets.UTF_8)));
}
if (onOutputBytes != null) {
onOutputBytes.accept(out.size());
}
position = field.tokenEnd();
if (position >= data.length) {
fillMissingColumns(column + 1, out);
@@ -202,9 +229,10 @@ final class CopyRecordTransformer {
int j = start;
while (j < length && data[j] != delimiter && data[j] != NEWLINE) {
if (!csv && data[j] == BACKSLASH && j + 1 < length) {
j = textEscapeEnd(data, j);
} else {
j++;
}
j++;
}
int valueEnd = j;
if (j < length && data[j] == NEWLINE && j > start && data[j - 1] == CARRIAGE_RETURN) {
@@ -213,6 +241,25 @@ final class CopyRecordTransformer {
return new Field(j, Arrays.copyOfRange(data, start, valueEnd), false);
}
private static int textEscapeEnd(byte[] data, int position) {
int next = position + 1;
if (data[next] >= '0' && data[next] <= '7') {
int end = next;
while (end < data.length && end < next + 3 && data[end] >= '0' && data[end] <= '7') {
end++;
}
return end;
}
if (data[next] == 'x' && next + 1 < data.length && Character.digit(data[next + 1], 16) >= 0) {
int end = next + 2;
if (end < data.length && Character.digit(data[end], 16) >= 0) {
end++;
}
return end;
}
return next + 1;
}
/** A carriage return that ends the record: followed by a newline or by the end of the data. */
private static boolean isCrlfAt(byte[] data, int index) {
return index < data.length && data[index] == CARRIAGE_RETURN
@@ -248,7 +295,12 @@ final class CopyRecordTransformer {
// A field that already is the NULL marker must not be cut or reformatted: that would turn NULL into data.
boolean nullMarkerField = !field.quoted() && Arrays.equals(value, nullMarker);
boolean converted = false;
boolean decimalConverted = false;
if (!nullMarkerField) {
byte[] decimal = convertDecimal(value, column);
decimalConverted = decimal != value;
converted = decimalConverted;
value = decimal;
byte[] temporal = convertTemporal(value, column);
if (temporal == null) {
out.writeBytes(nullMarker);
@@ -260,7 +312,12 @@ final class CopyRecordTransformer {
}
}
byte[] limited = nullMarkerField ? value : truncate(value, column);
boolean needsEscaping = field.quoted() || (converted && containsDelimiter(limited));
if (decimalConverted && !csv) {
writeDecimalText(limited, out);
return;
}
boolean needsEscaping = field.quoted() || (converted && containsDelimiter(limited))
|| (decimalConverted && Arrays.equals(limited, nullMarker));
if (!needsEscaping) {
out.writeBytes(limited);
} else if (csv) {
@@ -270,6 +327,77 @@ final class CopyRecordTransformer {
}
}
private byte[] convertDecimal(byte[] value, int column) {
if (columnScales == null || column >= columnScales.size() || columnScales.get(column) == null || value.length == 0) {
return value;
}
try {
byte[] decoded = csv ? value : decodeTextEscapes(value);
BigDecimal decimal = new BigDecimal(trimNumericWhitespace(new String(decoded, StandardCharsets.UTF_8)));
if (decimal.precision() - (long) decimal.scale() > 1000) {
throw new ArithmeticException("Numeric value exceeds the supported precision");
}
RoundingMode rounding = transforms.roundDecimal() ? RoundingMode.HALF_UP : RoundingMode.DOWN;
if (decimal.scale() - (long) decimal.precision() > columnScales.get(column) + 1L) {
decimal = BigDecimal.ZERO;
}
return decimal.setScale(columnScales.get(column), rounding).toPlainString().getBytes(StandardCharsets.UTF_8);
} catch (NumberFormatException ignored) {
// Let PostgreSQL report invalid numeric text with its normal SQLSTATE and column context.
return value;
} catch (ArithmeticException exception) {
throw new S3CopySimulator.S3TransferException("22003", "COPY numeric value out of range", exception);
}
}
private static String trimNumericWhitespace(String text) {
int start = 0;
int end = text.length();
while (start < end && isNumericWhitespace(text.charAt(start))) {
start++;
}
while (end > start && isNumericWhitespace(text.charAt(end - 1))) {
end--;
}
return text.substring(start, end);
}
private static boolean isNumericWhitespace(char character) {
return character == ' ' || (character >= '\t' && character <= '\r');
}
private void writeDecimalText(byte[] value, ByteArrayOutputStream out) {
byte[] encoded = encodeDecimalText(value, false);
out.writeBytes(Arrays.equals(encoded, nullMarker) ? encodeDecimalText(value, true) : encoded);
}
private byte[] encodeDecimalText(byte[] value, boolean escapeFirst) {
ByteArrayOutputStream out = new ByteArrayOutputStream(value.length + 4);
for (int i = 0; i < value.length; i++) {
byte b = value[i];
if (i == 0 && escapeFirst && b == delimiter && b >= '0' && b <= '7') {
// The default encoding already uses octal here; hex gives the marker a different spelling.
out.write(BACKSLASH);
out.write('x');
out.write(Character.forDigit((b >>> 4) & 15, 16));
out.write(Character.forDigit(b & 15, 16));
} else if (b == delimiter || (i == 0 && escapeFirst)) {
out.write(BACKSLASH);
// An escaped octal digit consumes following digits, so always emit all three octal digits.
if ((b >= '0' && b <= '7') || (i == 0 && escapeFirst)) {
out.write('0' + ((b >>> 6) & 7));
out.write('0' + ((b >>> 3) & 7));
out.write('0' + (b & 7));
} else {
out.write(b);
}
} else {
out.write(b);
}
}
return out.toByteArray();
}
private static byte[] trimTrailingSpaces(byte[] value, boolean csv) {
int end = value.length;
while (end > 0) {
@@ -53,10 +53,21 @@ public final class CopyStatementParser {
boolean acceptAnyDate,
boolean fillRecord,
int maxError,
boolean trimBlanks) {
boolean trimBlanks,
boolean ignoreBlankLines,
boolean roundDecimal,
boolean ignoreAllErrors) {
public static final CopyTransforms NONE = new CopyTransforms(false, false, false, false, null);
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
boolean truncateColumns, Character invalidCharReplacement,
CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat,
boolean acceptAnyDate, boolean fillRecord, int maxError, boolean trimBlanks) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, trimBlanks, false, false, false);
}
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
boolean truncateColumns, Character invalidCharReplacement) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
@@ -92,12 +103,12 @@ public final class CopyStatementParser {
* the COPY at the first error, which is how it runs without the option.
*/
public boolean toleratesErrors() {
return maxError > 1;
return ignoreAllErrors || maxError > 1;
}
/** Whether the options depend on the type of each column, which only the catalog can tell. */
public boolean needsColumnTypes() {
return temporal() || fillRecord || trimBlanks;
return temporal() || fillRecord || trimBlanks || roundDecimal;
}
/** Whether date or timestamp fields are read with a format other than PostgreSQL's own. */
@@ -107,7 +118,7 @@ public final class CopyStatementParser {
public boolean fieldLevel() {
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal() || fillRecord
|| trimBlanks;
|| trimBlanks || ignoreBlankLines || roundDecimal;
}
public boolean any() {
@@ -376,6 +387,9 @@ public final class CopyStatementParser {
private static final Pattern ACCEPTANYDATE_PATTERN = Pattern.compile("(?i)\\bACCEPTANYDATE\\b");
private static final Pattern FILLRECORD_PATTERN = Pattern.compile("(?i)\\bFILLRECORD\\b");
private static final Pattern MAXERROR_PATTERN = Pattern.compile("(?i)\\bMAXERROR\\s+(?:AS\\s+)?(\\d{1,9})\\b");
private static final Pattern IGNOREBLANKLINES_PATTERN = Pattern.compile("(?i)\\bIGNOREBLANKLINES\\b");
private static final Pattern ROUNDEC_PATTERN = Pattern.compile("(?i)\\bROUNDEC\\b");
private static final Pattern IGNOREALLERRORS_PATTERN = Pattern.compile("(?i)\\bIGNOREALLERRORS\\b");
private static final int MAX_MAXERROR = 100_000;
private static final Pattern CREDENTIALS_PATTERN = Pattern.compile(
"(?i)\\bCREDENTIALS\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
@@ -417,8 +431,8 @@ public final class CopyStatementParser {
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD"
+ "|ENCRYPTED|ENCODING"
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS"
+ "|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
+ "|ESCAPE|EXPLICIT_IDS"
+ "|NOLOAD|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
/** A {@code ;} followed by another statement: only a lone trailing {@code ;} is tolerated. */
private static final Pattern TRAILING_STATEMENT = Pattern.compile(";\\s*\\S");
@@ -755,6 +769,9 @@ public final class CopyStatementParser {
boolean fillRecord = false;
int maxError = 0;
boolean seenMaxError = false;
boolean ignoreBlankLines = false;
boolean roundDecimal = false;
boolean ignoreAllErrors = false;
boolean trimBlanks = false;
boolean seenCompupdate = false;
boolean seenStatupdate = false;
@@ -793,6 +810,9 @@ public final class CopyStatementParser {
Matcher acceptAnyDateMatcher = ACCEPTANYDATE_PATTERN.matcher(options);
Matcher fillRecordMatcher = FILLRECORD_PATTERN.matcher(options);
Matcher maxErrorMatcher = MAXERROR_PATTERN.matcher(options);
Matcher ignoreBlankLinesMatcher = IGNOREBLANKLINES_PATTERN.matcher(options);
Matcher roundDecimalMatcher = ROUNDEC_PATTERN.matcher(options);
Matcher ignoreAllErrorsMatcher = IGNOREALLERRORS_PATTERN.matcher(options);
Matcher compupdateMatcher = COMPUPDATE_PATTERN.matcher(options);
Matcher statupdateMatcher = STATUPDATE_PATTERN.matcher(options);
Matcher trimBlanksMatcher = TRIMBLANKS_PATTERN.matcher(options);
@@ -929,7 +949,28 @@ public final class CopyStatementParser {
}
fillRecord = true;
offset = fillRecordMatcher.end();
} else if (matchClause(ignoreBlankLinesMatcher, offset, len)) {
if (ignoreBlankLines) {
return null;
}
ignoreBlankLines = true;
offset = ignoreBlankLinesMatcher.end();
} else if (matchClause(roundDecimalMatcher, offset, len)) {
if (roundDecimal) {
return null;
}
roundDecimal = true;
offset = roundDecimalMatcher.end();
} else if (matchClause(ignoreAllErrorsMatcher, offset, len)) {
if (ignoreAllErrors || seenMaxError) {
return null;
}
ignoreAllErrors = true;
offset = ignoreAllErrorsMatcher.end();
} else if (matchClause(maxErrorMatcher, offset, len)) {
if (ignoreAllErrors) {
return null;
}
int parsed = seenMaxError ? -1 : Integer.parseInt(maxErrorMatcher.group(1));
if (parsed < 0 || parsed > MAX_MAXERROR) {
return null;
@@ -984,8 +1025,10 @@ public final class CopyStatementParser {
}
CopyTransforms transforms = new CopyTransforms(
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar,
dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, trimBlanks);
if (transforms.any() && jsonAuto) {
dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, trimBlanks,
ignoreBlankLines, roundDecimal, ignoreAllErrors);
if (jsonAuto && (blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || invalidChar != null
|| transforms.temporal() || fillRecord || trimBlanks)) {
return null;
}
if (transforms.removeQuotes() && csv) {
@@ -10,6 +10,7 @@ import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor;
import io.floci.aws.services.s3.S3Service;
import org.jboss.logging.Logger;
import org.postgresql.ds.PGSimpleDataSource;
import java.io.IOException;
import java.net.BindException;
@@ -279,9 +280,24 @@ public class RedshiftAuthProxy {
RoleConfiguration roles = roleConfiguration;
RedshiftAuditLogPublisher bridgeAudit = login.dataApi ? null : auditLogPublisher;
SpectrumInterceptor bridgeSpectrum = login.dataApi ? null : spectrumInterceptor;
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, roles.iamRoleArns(), bridgeSpectrum, clusterKey, login.database,
roles.defaultIamRoleArn(), bridgeAudit, login.username, parquetWriter).run();
roles.defaultIamRoleArn(), bridgeAudit, login.username, parquetWriter);
try (CopyLoadErrorLog loadErrors = new CopyLoadErrorLog(() -> {
PGSimpleDataSource source = new PGSimpleDataSource();
source.setServerNames(new String[]{backendHost});
source.setPortNumbers(new int[]{backendPort});
source.setDatabaseName(login.database);
source.setUser(masterUsername);
source.setPassword(masterPassword);
source.setConnectTimeout(Math.max(1, backendConnectTimeoutMillis / 1000));
source.setSocketTimeout(10);
source.setSslMode("disable");
return source.getConnection();
})) {
bridge.loadErrorSink(loadErrors);
bridge.run();
}
publishConnection(client, login, "disconnection");
} else {
publishConnection(client, login, login.backendUnavailable ? "connection_error" : "authentication failure");
@@ -34,6 +34,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Replaces the transparent {@code bridge()} for Redshift connections so SQL in Simple and Extended
@@ -85,6 +86,12 @@ public class RedshiftInterceptingBridge {
private final Map<String, ExtendedSpectrumExchange.PortalCursor> spectrumCursors = new HashMap<>();
private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
private final CopyBackendSession copyBackend;
private Consumer<CopyLoadError> loadErrorSink;
void loadErrorSink(Consumer<CopyLoadError> sink) {
loadErrorSink = sink;
copyBackend.loadErrorSink(sink);
}
private final ReentrantLock backendLock;
/** Budget of {@link #runWithBackendOwned} only; the Extended Query paths keep {@link #PUMP_PARK_WAIT_MS}. */
@@ -318,8 +325,10 @@ public class RedshiftInterceptingBridge {
boolean intercepted = runWithBackendOwned(() -> switch (statement) {
case CopyStatementParser.S3CopyJobRun run -> CopyEtlLoader.runSimple(
client, backend, run, s3Service, iamService, clusterAccountId, iamRoleArns,
coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
case CopyStatementParser.S3CopyFrom copy -> S3CopySimulator.runCopyFrom(
coordinator.lastReadyStatus(), status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), loadErrorSink);
case CopyStatementParser.S3CopyFrom copy -> loadErrorSink != null ? CopyEtlLoader.runSimple(
client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}), loadErrorSink) : S3CopySimulator.runCopyFrom(
client, backend, copy, s3Service, iamService, clusterAccountId, iamRoleArns, coordinator.lastReadyStatus(),
status -> coordinator.onBackendFrame('Z', new byte[]{(byte) status}));
case CopyStatementParser.S3Unload unload -> S3CopySimulator.runUnload(
@@ -111,10 +111,20 @@ public final class S3CopySimulator {
public static final class S3TransferException extends RuntimeException {
private final String sqlState;
private final Map<Character, String> fields;
public S3TransferException(String sqlState, String message, Throwable cause) {
this(sqlState, message, cause, Map.of());
}
S3TransferException(String sqlState, String message, Throwable cause, Map<Character, String> fields) {
super(message, cause);
this.sqlState = sqlState;
this.fields = Map.copyOf(fields);
}
Map<Character, String> fields() {
return fields;
}
public String sqlState() {
@@ -566,7 +576,7 @@ public final class S3CopySimulator {
: spec.columns().stream().map(S3CopySimulator::normalizeColumnName).toList();
}
private static String normalizeColumnName(String identifier) {
static String normalizeColumnName(String identifier) {
if (identifier != null && identifier.length() >= 2
&& identifier.startsWith("\"") && identifier.endsWith("\"")) {
return identifier.substring(1, identifier.length() - 1).replace("\"\"", "\"");
@@ -708,12 +718,20 @@ public final class S3CopySimulator {
}
}
record ColumnInfo(String name, Integer maxBytes, CopyRecordTransformer.ColumnKind kind) {
record ColumnInfo(String name, Integer maxBytes, CopyRecordTransformer.ColumnKind kind, Integer scale, String typeOid) {
ColumnInfo(String name, Integer maxBytes, CopyRecordTransformer.ColumnKind kind) {
this(name, maxBytes, kind, null, null);
}
ColumnInfo(String name, Integer maxBytes) {
this(name, maxBytes, CopyRecordTransformer.ColumnKind.OTHER);
}
}
static List<Integer> alignScales(CopyStatementParser.S3CopyFrom spec, List<ColumnInfo> catalog) {
return align(spec, catalog, ColumnInfo::scale);
}
/** Positional max character length per COPY column; null entries mean no limit. */
static List<Integer> alignMaxBytes(CopyStatementParser.S3CopyFrom spec, List<ColumnInfo> catalog) {
return align(spec, catalog, ColumnInfo::maxBytes);
@@ -787,7 +805,9 @@ public final class S3CopySimulator {
static String columnInfoQuery(CopyStatementParser.S3CopyFrom spec) {
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
return "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
+ "THEN a.atttypmod - 4 END, a.atttypid FROM pg_catalog.pg_attribute a "
+ "THEN a.atttypmod - 4 END, a.atttypid, "
+ "CASE WHEN a.atttypid = 1700 AND a.atttypmod >= 4 "
+ "THEN (((a.atttypmod - 4) & 2047) # 1024) - 1024 END FROM pg_catalog.pg_attribute a "
+ "WHERE a.attrelid = to_regclass(" + PostgresWire.quoteLiteral(spec.targetTable()) + ") "
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' "
+ "ORDER BY a.attnum";
@@ -797,7 +817,8 @@ public final class S3CopySimulator {
Integer maxBytes = values.size() >= 2 && values.get(1) != null
? Integer.valueOf(values.get(1)) : null;
String typeOid = values.size() >= 3 ? values.get(2) : null;
return new ColumnInfo(values.get(0), maxBytes, kindOf(typeOid));
Integer scale = values.size() >= 4 && values.get(3) != null ? Integer.valueOf(values.get(3)) : null;
return new ColumnInfo(values.get(0), maxBytes, kindOf(typeOid), scale, typeOid);
}
private static List<ColumnInfo> discoverColumnInfo(Socket client, Socket backend,