mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
1e61e16056
commit
59c2b46e1c
22 files changed
+1833
-97
No files matched your search
+44
-12
@@ -326,6 +326,9 @@ and see their own rows in `sys_copy_job`; superusers can see all rows.
|
||||
|
||||
COPY options are stored for execution time, including formats the ordinary COPY simulator does not yet
|
||||
implement. The COPY JOB restrictions above are checked at creation time.
|
||||
The `MAXERROR` and `IGNOREALLERRORS` restrictions follow the
|
||||
[AWS COPY JOB parameter rules](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-JOB.html),
|
||||
which explicitly exclude both options. Ordinary COPY supports them; COPY JOB intentionally does not.
|
||||
|
||||
`COPY JOB RUN` scans the job's S3 prefix and loads files not yet committed by that job, including with
|
||||
`AUTO OFF`. An active S3 event integration runs matching `AUTO ON` jobs in provisioned clusters and
|
||||
@@ -916,7 +919,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
|
||||
- Supported options: `DELIMITER`, `FORMAT CSV` (or a bare `CSV`), `GZIP`, `IGNOREHEADER <n>` and
|
||||
`HEADER`, `NULL AS`, `FORMAT AS JSON 'auto'`, `FORMAT AS JSON 'auto ignorecase'` (or bare `JSON 'auto'`),
|
||||
`MANIFEST`, `COMPUPDATE`, `STATUPDATE`, `TRIMBLANKS`, and an explicit column list.
|
||||
`MANIFEST`, `COMPUPDATE`, `STATUPDATE`, `TRIMBLANKS`, `IGNOREBLANKLINES`, `ROUNDEC`,
|
||||
`IGNOREALLERRORS`, and an explicit column list.
|
||||
- `COMPUPDATE [PRESET | ON | OFF | TRUE | FALSE]` and `STATUPDATE [ON | OFF | TRUE | FALSE]` (or bare `COMPUPDATE`
|
||||
and `STATUPDATE`) are accepted and treated as no-ops for single-node PostgreSQL compatibility.
|
||||
- The default framing is pipe-delimited text, matching Redshift. `FORMAT CSV` switches to CSV with
|
||||
@@ -927,13 +931,20 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
values abort the load. When columns are not specified in the COPY statement, table column names and
|
||||
order are automatically discovered from the database catalog when the statement executes, through
|
||||
Simple Query, Extended Query and the Data API. Nested objects and arrays are serialized as JSON strings.
|
||||
With `MAXERROR` greater than 1, input is processed as JSON lines so a malformed line can be skipped;
|
||||
With `MAXERROR` greater than 1 or `IGNOREALLERRORS`, input is processed as JSON lines so a malformed line can be skipped;
|
||||
multiline pretty-printed JSON is supported only without error tolerance.
|
||||
- `MANIFEST` resolves file keys from a JSON manifest file (`{"entries": [{"url": "s3://...", "mandatory": boolean}]}`),
|
||||
compatible with output from `UNLOAD ... MANIFEST`. Missing files marked `mandatory: true` abort the load.
|
||||
When `mandatory` is omitted, it defaults to `false`. All entries in the manifest must reside in the same S3
|
||||
bucket as the manifest file itself; cross-bucket manifest entries are rejected as an intentional deviation.
|
||||
- `IGNOREHEADER` and `HEADER` skip lines from the start of every resolved object, as AWS does for a parallel load of several files.
|
||||
- `IGNOREBLANKLINES` skips empty physical records, including CRLF records. Whitespace-only fields,
|
||||
quoted empty strings and empty lines inside quoted CSV fields remain data. Without this option,
|
||||
an empty text or CSV record is a load error.
|
||||
- `ROUNDEC` rounds `DECIMAL`/`NUMERIC` values to the target column scale, with ties away from zero.
|
||||
Without it, COPY truncates the fractional digits towards zero, matching Redshift rather than
|
||||
PostgreSQL's default rounding. Column scales are discovered at execution and respect an explicit
|
||||
COPY column order. Text, CSV and JSON auto loads use the same decimal conversion.
|
||||
- `GZIP` is the only input compression recognized; `BZIP2`, `LZOP` and `ZSTD` are not.
|
||||
- `IAM_ROLE '<role-arn>'` is supported. The role must be associated with the cluster (at
|
||||
`CreateCluster` or through `ModifyClusterIamRoles`; connections opened before a change keep the
|
||||
@@ -963,8 +974,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
`CHAR`/`VARCHAR` length in bytes (Redshift's meaning of the declared length, so `éééé` into
|
||||
`VARCHAR(3)` loads `é`), never inside a multi-byte character or a backslash escape. Its column
|
||||
lengths come from the database catalog at execution, through Simple Query, Extended Query and the Data API.
|
||||
A field-level option
|
||||
buffers each decompressed object in memory, so an object over 64 MiB, or a heap budget shared
|
||||
A transformed record
|
||||
is buffered in memory, so a record over 64 MiB, or a heap budget shared
|
||||
across connections that is used up, fails the COPY instead of exhausting the emulator.
|
||||
- `DATEFORMAT [AS] 'format'` reads the fields of `DATE` columns and `TIMEFORMAT [AS] 'format'` those of
|
||||
`TIMESTAMP` columns, using the dateparts and timeparts `YY`, `YYYY`, `MM`, `MON`, `DD`, `HH`/`HH24`, `HH12`,
|
||||
@@ -973,7 +984,7 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
of day, which is dropped; a `TIMEFORMAT` without one gives midnight. A format that names a time zone, or
|
||||
any other text, is not recognized and the statement is forwarded to PostgreSQL. A value that does not
|
||||
match its format is a record error counted against `MAXERROR`; the message names the column and the format,
|
||||
and Floci writes no `stl_load_errors` row. `ACCEPTANYDATE` loads such a value as
|
||||
and the failure is recorded in `stl_load_errors`. `ACCEPTANYDATE` loads such a value as
|
||||
`NULL` instead; when no format is given it reads the ISO form of a date, with an optional time of day, and
|
||||
turns anything else into `NULL`. An empty unquoted field of a `DATE`, `TIMESTAMP` or other non-character column
|
||||
is loaded as `NULL`, as in AWS, without requiring `ACCEPTANYDATE` or `EMPTYASNULL`. Numeric parts with no
|
||||
@@ -982,8 +993,9 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
recognized.
|
||||
Like `TRUNCATECOLUMNS`, these and the empty non-character rule read column types from the catalog, so
|
||||
they apply only with the options that query column types (`DATEFORMAT`, `TIMEFORMAT`, `FILLRECORD`), through
|
||||
Simple Query, Extended Query and the Data API, and are not combined with `FORMAT AS JSON`; a plain `COPY` without those options does
|
||||
not read the catalog. Floci deviations: `'auto'` is accepted but converts
|
||||
Simple Query, Extended Query and the Data API, and are not combined with `FORMAT AS JSON`.
|
||||
A plain `COPY` also discovers catalog metadata for decimal conversion and diagnostics.
|
||||
Floci deviations: `'auto'` is accepted but converts
|
||||
nothing, leaving every value to PostgreSQL, which reads ISO 8601, Julian and `YYYYMMDD HHMISS` but not every
|
||||
form Redshift recognizes (for example `BC` dates and `YYYY.DDD`), and with it `ACCEPTANYDATE` cannot turn a
|
||||
value into `NULL`, so a value PostgreSQL rejects fails the COPY; `TIMESTAMPTZ` columns are read by
|
||||
@@ -1003,12 +1015,32 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
Conversion, date/time format, field-count, encoding, string-length and `NOT NULL` errors can be skipped.
|
||||
The `n`-th record error, counted across all source objects, rolls back the entire COPY; earlier statements
|
||||
in an explicit transaction remain subject to the caller's transaction and savepoints. Access denied,
|
||||
cancellation, storage and unexpected internal errors are never ignored. An unterminated CSV quote or
|
||||
unreadable compressed object aborts the load because the next record boundary cannot be established.
|
||||
cancellation, storage and unexpected internal errors are never ignored. An unterminated quoted record
|
||||
consumes the remainder of its object and counts as one rejected record; unreadable compressed objects abort the load.
|
||||
The returned `COPY` count includes accepted rows only. Floci deviations: tolerant loads use one COPY
|
||||
per record, which costs more round trips and runs PostgreSQL statement triggers per record; PostgreSQL
|
||||
deferred-constraint timing is not promised as Redshift behavior. Tolerant records are buffered within
|
||||
the transform size and shared memory limits. No `stl_load_errors` row or Redshift load-summary message is written.
|
||||
deferred-constraint timing is not promised as Redshift behavior. Records are buffered within
|
||||
the transform size and shared memory limits. No Redshift load-summary message is written.
|
||||
Non-tolerant loads stream each S3 object through one backend COPY, including when diagnostics or
|
||||
decimal conversion are enabled. A failed object's input is replayed locally to map PostgreSQL's
|
||||
error line back to its original physical line; successful loads need no replay.
|
||||
- `IGNOREALLERRORS` skips all record conversion errors without an error-count limit. It cannot be
|
||||
combined with `MAXERROR`, including `MAXERROR 0`. COPY JOB rejects both options, matching the AWS
|
||||
restriction linked above rather than extending the ordinary COPY option to jobs.
|
||||
Unsupported columnar formats remain unsupported; authorization, missing targets and infrastructure
|
||||
failures still fail the COPY.
|
||||
- Record failures write `stl_load_errors`, including failures skipped by `MAXERROR` or `IGNOREALLERRORS`.
|
||||
Diagnostics identify the S3 object, physical line, target table, session, column when available,
|
||||
raw record and field value, Redshift error code and a bounded reason. Each load receives a local
|
||||
diagnostic query ID; it is not linked to `svl_qlog`. JSON diagnostics use the last physical line
|
||||
of the object. A separate autocommit backend connection retains diagnostics when COPY fails or the
|
||||
caller rolls back. The connection and prepared statement are opened lazily and reused for the client
|
||||
connection, with a 250 ms lock timeout and 1 second statement timeout. A failed diagnostic write is
|
||||
logged without replacing the original load error, and disables further diagnostic writes for that
|
||||
client connection to avoid repeated waits. The read-only catalog view shows ordinary users their own
|
||||
session user's records and superusers all records; raw rows live in a private backing table. Existing
|
||||
catalog rows are retained when an older cluster's catalog is bootstrapped again.
|
||||
Floci deviations: `position` and `copy_job_id` are zero, and unknown error categories use code 1200.
|
||||
- Any other clause (`FIXEDWIDTH`, `PARQUET`, `AVRO`, `ORC`,
|
||||
`ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
|
||||
`KMS_KEY_ID`, and so on) is not recognized: the statement is forwarded unchanged and PostgreSQL
|
||||
@@ -1117,7 +1149,7 @@ When a Redshift cluster container starts, Floci bootstraps common Redshift syste
|
||||
- `svv_columns`: Column catalog list (`table_catalog`, `table_schema`, `table_name`, `column_name`, `ordinal_position`, `column_default`, `is_nullable`, `data_type`).
|
||||
- `svv_tables`: Table catalog list (`table_catalog`, `table_schema`, `table_name`, `table_type`).
|
||||
- `stv_tbl_perm`: Table persistence metadata (`id`, `name`, `db_id`, `temp`, `backup`).
|
||||
- `stl_load_errors`: Table exposing the documented Redshift load-error schema for catalog and tooling compatibility.
|
||||
- `stl_load_errors`: COPY record failures, retained independently of the load transaction.
|
||||
- `svl_qlog`: Query execution log view (`userid`, `query`, `xid`, `pid`, `starttime`, `endtime`, `elapsed`, `aborted`, `label`).
|
||||
- `pg_user_info`: User catalog information (`usesysid`, `usename`, `usecreatedb`, `usesuper`, `useconnlimit`, `syslogaccess`).
|
||||
- `svl_user_info`: Standard Redshift user information view matching AWS documented columns.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -103,8 +103,20 @@ FROM pg_catalog.pg_class c
|
||||
CROSS JOIN (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database()) d
|
||||
WHERE c.relkind = 'r';
|
||||
|
||||
-- 6. stl_load_errors: load error log table for COPY commands
|
||||
CREATE TABLE IF NOT EXISTS pg_catalog.stl_load_errors (
|
||||
-- 6. stl_load_errors: private autonomous writer, with per-session catalog visibility.
|
||||
-- Keep raw input outside the public catalog and expose only the filtered view.
|
||||
CREATE SCHEMA IF NOT EXISTS floci_internal;
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_catalog.pg_class
|
||||
WHERE oid = to_regclass('pg_catalog.stl_load_errors') AND relkind = 'r') THEN
|
||||
ALTER TABLE pg_catalog.stl_load_errors SET SCHEMA floci_internal;
|
||||
ALTER TABLE floci_internal.stl_load_errors RENAME TO copy_load_errors;
|
||||
REVOKE ALL ON TABLE floci_internal.copy_load_errors FROM PUBLIC;
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
CREATE TABLE IF NOT EXISTS floci_internal.copy_load_errors (
|
||||
userid integer DEFAULT 1,
|
||||
slice integer DEFAULT 0,
|
||||
tbl integer DEFAULT 0,
|
||||
@@ -125,6 +137,13 @@ CREATE TABLE IF NOT EXISTS pg_catalog.stl_load_errors (
|
||||
start_offset bigint DEFAULT 0,
|
||||
copy_job_id bigint DEFAULT 0
|
||||
);
|
||||
REVOKE ALL ON TABLE floci_internal.copy_load_errors FROM PUBLIC;
|
||||
CREATE OR REPLACE VIEW pg_catalog.stl_load_errors WITH (security_barrier = true) AS
|
||||
SELECT * FROM floci_internal.copy_load_errors
|
||||
WHERE userid = (SELECT oid::integer FROM pg_catalog.pg_roles WHERE rolname = session_user)
|
||||
OR (SELECT rolsuper FROM pg_catalog.pg_roles WHERE rolname = session_user);
|
||||
REVOKE ALL ON TABLE pg_catalog.stl_load_errors FROM PUBLIC;
|
||||
GRANT SELECT ON TABLE pg_catalog.stl_load_errors TO PUBLIC;
|
||||
|
||||
-- 7. svl_qlog: dynamic query execution log view
|
||||
DROP VIEW IF EXISTS pg_catalog.svl_qlog CASCADE;
|
||||
@@ -613,5 +632,4 @@ GRANT USAGE ON SCHEMA floci_internal TO PUBLIC;
|
||||
-- Schema access for COPY JOB must not expose the unrelated privileged catalog writers.
|
||||
REVOKE EXECUTE ON FUNCTION floci_internal.refresh_external_catalog(text, jsonb) FROM PUBLIC;
|
||||
REVOKE EXECUTE ON FUNCTION floci_internal.purge_external_schema(text) FROM PUBLIC;
|
||||
GRANT ALL ON TABLE pg_catalog.stl_load_errors TO PUBLIC;
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO PUBLIC;
|
||||
+154
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user