feat(redshift): support FILLRECORD in COPY (#7269)

* feat(redshift): support FILLRECORD in COPY

A text or CSV record that stops short of the last columns is loaded with the
rest of them filled: a character column gets a zero-length string and any other
column NULL, as in Redshift. EMPTYASNULL and NULL AS '' make the character
columns NULL too. Without FILLRECORD nothing changes.

* fix(redshift): bound memory growth for FILLRECORD output

Count transformed output against COPY_TRANSFORM_MAX_OBJECT_BYTES and the shared COPY_TRANSFORM_HEAP_MIB budget as records are written, so short records expanded by FILLRECORD fail with the statement limit or memory budget error rather than exhausting the emulator heap.

* fix(redshift): load missing CHAR columns as NULL on FILLRECORD
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-02 09:33:31 -04:00
1 parent a69b3621a0
commit cd6e516929
7 files changed
+359 -39

No files matched your search

+9 -1
View File
@@ -811,8 +811,16 @@ order) through its own S3 service and streams the rows into the backing PostgreS
value into `NULL`, so a value PostgreSQL rejects fails the COPY; `TIMESTAMPTZ` columns are read by
PostgreSQL whatever the format, since AWS requires `'auto'` for a format other than its default there; a
two-digit `YY` year below 70 means 20YY and otherwise 19YY, which AWS does not document.
- `FILLRECORD` loads a text or CSV record that stops short of the last columns: the missing columns of a
`VARCHAR` or `TEXT` type get a zero-length string, as in AWS, and every other missing column gets
`NULL`. With `EMPTYASNULL`, or `NULL AS ''`, which behaves the same, the missing character columns get `NULL`
too. A column that does not allow `NULL` fails the COPY as it would without `FILLRECORD`, and a record with
too many fields still fails. The number and types of the columns come from the catalog (generated columns
left out), or from the column list, in which a name that matches no column counts as a non-character column.
A domain over a character type counts as a non-character column. It works only over the Simple Query
protocol, and it is not combined with `FORMAT AS JSON`.
- Any other clause (`FIXEDWIDTH`, `PARQUET`, `AVRO`, `ORC`, `MAXERROR`,
`FILLRECORD`, `ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
`ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
`KMS_KEY_ID`, and so on) is not recognized: the statement is forwarded unchanged and PostgreSQL
returns its own error.
- A multi-statement query whose COPY is followed by another statement is not intercepted; send the
@@ -4,6 +4,7 @@ import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.function.IntConsumer;
/**
* Applies the COPY options that change field content to the bytes of one S3 object before they
@@ -21,7 +22,7 @@ final class CopyRecordTransformer {
/** What a COPY column holds, as far as the date and time formats are concerned. */
enum ColumnKind {
DATE, TIMESTAMP, OTHER
DATE, TIMESTAMP, TEXT, OTHER
}
private record Field(int tokenEnd, byte[] value, boolean quoted) {
@@ -33,6 +34,7 @@ final class CopyRecordTransformer {
private final byte[] nullMarker;
private final List<Integer> columnMaxBytes;
private final List<ColumnKind> columnKinds;
private final boolean emptyNullString;
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes) {
this(spec, columnMaxBytes, null);
@@ -41,6 +43,7 @@ final class CopyRecordTransformer {
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
List<ColumnKind> columnKinds) {
this.columnKinds = columnKinds;
this.emptyNullString = spec.nullAs() != null && spec.nullAs().isEmpty();
this.transforms = spec.transforms();
this.csv = spec.csv();
String delimiterText = spec.delimiter() != null ? spec.delimiter() : (spec.csv() ? "," : "|");
@@ -51,16 +54,32 @@ final class CopyRecordTransformer {
}
byte[] apply(byte[] input) {
return apply(input, null);
}
byte[] apply(byte[] input, IntConsumer onOutputBytes) {
byte[] data = transforms.invalidCharReplacement() != null
? sanitizeUtf8(input, (byte) transforms.invalidCharReplacement().charValue())
: input;
if (!transforms.fieldLevel()) {
if (onOutputBytes != null) {
onOutputBytes.accept(data.length);
}
return data;
}
if (data.length == 0) {
if (onOutputBytes != null) {
onOutputBytes.accept(0);
}
return new byte[0];
}
ByteArrayOutputStream out = new ByteArrayOutputStream(data.length + 16);
int position = 0;
while (position < data.length) {
position = transformRecord(data, position, out);
if (onOutputBytes != null) {
onOutputBytes.accept(out.size());
}
}
return out.toByteArray();
}
@@ -120,14 +139,17 @@ final class CopyRecordTransformer {
writeField(field, column, out);
position = field.tokenEnd();
if (position >= data.length) {
fillMissingColumns(column + 1, out);
out.write(NEWLINE);
return data.length;
}
if (data[position] == NEWLINE) {
fillMissingColumns(column + 1, out);
out.write(NEWLINE);
return position + 1;
}
if (isCrlfAt(data, position)) {
fillMissingColumns(column + 1, out);
out.write(NEWLINE);
return Math.min(position + 2, data.length);
}
@@ -239,6 +261,28 @@ final class CopyRecordTransformer {
return false;
}
/**
* FILLRECORD: a record that stops short of the last columns gets the rest of them. A character column is
* filled with a zero-length string and any other column with NULL; EMPTYASNULL and {@code NULL AS ''} make an
* empty string NULL, so they NULL the character columns too. CSV needs the empty string quoted.
*/
private void fillMissingColumns(int fieldsWritten, ByteArrayOutputStream out) {
if (!transforms.fillRecord() || columnKinds == null) {
return;
}
for (int column = fieldsWritten; column < columnKinds.size(); column++) {
out.write(delimiter);
boolean emptyString = columnKinds.get(column) == ColumnKind.TEXT
&& !transforms.emptyAsNull() && !emptyNullString;
if (!emptyString) {
out.writeBytes(nullMarker);
} else if (csv) {
out.write(DOUBLE_QUOTE);
out.write(DOUBLE_QUOTE);
}
}
}
/**
* Rewrites a DATE or TIMESTAMP field from the DATEFORMAT or TIMEFORMAT to the ISO text PostgreSQL reads.
* Returns the field as it is when no format applies to its column, and null when ACCEPTANYDATE turns a
@@ -253,7 +297,7 @@ final class CopyRecordTransformer {
CopyTemporalFormat format = switch (kind) {
case DATE -> transforms.dateFormat();
case TIMESTAMP -> transforms.timeFormat();
case OTHER -> null;
case TEXT, OTHER -> null;
};
if (format == null || !format.converts()) {
return value;
@@ -29,14 +29,28 @@ public final class CopyStatementParser {
Character invalidCharReplacement,
CopyTemporalFormat dateFormat,
CopyTemporalFormat timeFormat,
boolean acceptAnyDate) {
boolean acceptAnyDate,
boolean fillRecord) {
public static final CopyTransforms NONE = new CopyTransforms(false, false, false, false, null);
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
boolean truncateColumns, Character invalidCharReplacement) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
null, null, false);
null, null, false, false);
}
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
boolean truncateColumns, Character invalidCharReplacement,
CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat,
boolean acceptAnyDate) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
dateFormat, timeFormat, acceptAnyDate, false);
}
/** Whether the options depend on the type of each column, which only the catalog can tell. */
public boolean needsColumnTypes() {
return temporal() || fillRecord;
}
/** Whether date or timestamp fields are read with a format other than PostgreSQL's own. */
@@ -45,7 +59,7 @@ public final class CopyStatementParser {
}
public boolean fieldLevel() {
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal();
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal() || fillRecord;
}
public boolean any() {
@@ -286,6 +300,7 @@ public final class CopyStatementParser {
private static final Pattern DATEFORMAT_PATTERN = Pattern.compile("(?i)\\bDATEFORMAT\\s+(?:AS\\s+)?'([^']*)'");
private static final Pattern TIMEFORMAT_PATTERN = Pattern.compile("(?i)\\bTIMEFORMAT\\s+(?:AS\\s+)?'([^']*)'");
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 CREDENTIALS_PATTERN = Pattern.compile(
"(?i)\\bCREDENTIALS\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile(
@@ -319,7 +334,7 @@ public final class CopyStatementParser {
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD|MAXERROR"
+ "|ENCRYPTED|ENCODING"
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|FILLRECORD|TRIMBLANKS"
+ "|TRIMBLANKS"
+ "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS|COMPUPDATE"
+ "|STATUPDATE|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
@@ -640,6 +655,7 @@ public final class CopyStatementParser {
CopyTemporalFormat dateFormat = null;
CopyTemporalFormat timeFormat = null;
boolean acceptAnyDate = false;
boolean fillRecord = false;
boolean seenDateFormat = false;
boolean seenTimeFormat = false;
@@ -672,6 +688,7 @@ public final class CopyStatementParser {
Matcher dateFormatMatcher = DATEFORMAT_PATTERN.matcher(options);
Matcher timeFormatMatcher = TIMEFORMAT_PATTERN.matcher(options);
Matcher acceptAnyDateMatcher = ACCEPTANYDATE_PATTERN.matcher(options);
Matcher fillRecordMatcher = FILLRECORD_PATTERN.matcher(options);
AuthClauses auth = new AuthClauses(options, defaultIamRoleArn);
int next;
@@ -799,6 +816,12 @@ public final class CopyStatementParser {
}
acceptAnyDate = true;
offset = acceptAnyDateMatcher.end();
} else if (matchClause(fillRecordMatcher, offset, len)) {
if (fillRecord) {
return null;
}
fillRecord = true;
offset = fillRecordMatcher.end();
} else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) {
if (next == AuthClauses.REJECT) {
return null;
@@ -827,7 +850,7 @@ public final class CopyStatementParser {
}
CopyTransforms transforms = new CopyTransforms(
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar,
dateFormat, timeFormat, acceptAnyDate);
dateFormat, timeFormat, acceptAnyDate, fillRecord);
if (transforms.any() && jsonAuto) {
return null;
}
@@ -332,11 +332,11 @@ public final class S3CopySimulator {
boolean noColumnList = spec.columns() == null || spec.columns().isEmpty();
boolean discoverForJson = spec.jsonAuto() && noColumnList;
boolean truncate = spec.transforms().truncateColumns();
boolean temporal = spec.transforms().temporal();
boolean columnTypes = spec.transforms().needsColumnTypes();
List<String> discoveredColumns = null;
List<Integer> columnMaxBytes = null;
List<CopyRecordTransformer.ColumnKind> columnKinds = null;
if (discoverForJson || truncate || temporal) {
if (discoverForJson || truncate || columnTypes) {
List<ColumnInfo> catalog = discoverColumnInfo(client, backend, spec, txStatus, onStatusChange);
if (catalog == null) {
return true;
@@ -347,7 +347,7 @@ public final class S3CopySimulator {
if (truncate) {
columnMaxBytes = alignMaxBytes(spec, catalog);
}
if (temporal) {
if (columnTypes) {
columnKinds = alignKinds(spec, catalog);
}
}
@@ -491,10 +491,10 @@ public final class S3CopySimulator {
"COPY ... TRUNCATECOLUMNS needs catalog column lengths, which are only available over "
+ "the Simple Query protocol; connect with preferQueryMode=simple", null);
}
if (spec.transforms().temporal() && columnKinds == null) {
if (spec.transforms().needsColumnTypes() && columnKinds == null) {
throw new S3TransferException(SQLSTATE_INTERNAL,
"COPY ... DATEFORMAT and TIMEFORMAT need catalog column types, which are only available over "
+ "the Simple Query protocol; connect with preferQueryMode=simple", null);
"COPY ... DATEFORMAT, TIMEFORMAT and FILLRECORD need catalog column types, which are only "
+ "available over the Simple Query protocol; connect with preferQueryMode=simple", null);
}
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
@@ -546,15 +546,36 @@ public final class S3CopySimulator {
backendOut.flush();
}
private static void checkTransformObjectLimit(long bytes) {
if (bytes > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
"COPY object exceeds the " + COPY_TRANSFORM_MAX_OBJECT_BYTES
+ "-byte limit for the field-level options "
+ "(EMPTYASNULL, BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS, TRUNCATECOLUMNS, "
+ "DATEFORMAT, TIMEFORMAT, FILLRECORD)", null);
}
}
private static void acquireTransformHeap(int[] heldMib, int wantedMib) {
while (heldMib[0] < wantedMib) {
if (!COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
"COPY memory budget exhausted; retry shortly", null);
}
heldMib[0]++;
}
}
/**
* Reads one decompressed object into heap and transforms it. The read is bounded by a per-object
* ceiling and by a budget shared across connections, so a large or highly compressed object fails
* its own statement instead of exhausting the emulator heap.
* Reads one decompressed object into heap and transforms it. The read and transformed output are
* bounded by a per-object ceiling and by a budget shared across connections, so a large or highly
* compressed object, or short rows expanded by FILLRECORD, fail their own statement instead of
* exhausting the emulator heap.
*/
private static byte[] transformObject(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
List<CopyRecordTransformer.ColumnKind> columnKinds,
InputStream in) throws IOException {
int heldMib = 0;
int[] heldMib = new int[]{0};
try {
ByteArrayOutputStream buffered = new ByteArrayOutputStream();
byte[] chunk = new byte[CHUNK];
@@ -562,26 +583,23 @@ public final class S3CopySimulator {
int read;
while ((read = in.read(chunk)) != -1) {
total += read;
if (total > COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException(SQLSTATE_PROGRAM_LIMIT_EXCEEDED,
"COPY object exceeds the " + COPY_TRANSFORM_MAX_OBJECT_BYTES
+ "-byte limit for the field-level options "
+ "(EMPTYASNULL, BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS, TRUNCATECOLUMNS, "
+ "DATEFORMAT, TIMEFORMAT)", null);
}
int wantedMib = (int) ((total * COPY_TRANSFORM_HEAP_FACTOR) / (1024 * 1024)) + 1;
while (heldMib < wantedMib) {
if (!COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
"COPY memory budget exhausted; retry shortly", null);
}
heldMib++;
}
checkTransformObjectLimit(total);
acquireTransformHeap(heldMib, (int) ((total * COPY_TRANSFORM_HEAP_FACTOR) / (1024 * 1024)) + 1);
buffered.write(chunk, 0, read);
}
return new CopyRecordTransformer(spec, columnMaxBytes, columnKinds).apply(buffered.toByteArray());
long inputTotal = total;
return new CopyRecordTransformer(spec, columnMaxBytes, columnKinds).apply(
buffered.toByteArray(),
outputSize -> {
checkTransformObjectLimit(outputSize);
acquireTransformHeap(heldMib,
(inputTotal == 0 && outputSize == 0) ? 0
: (int) ((inputTotal + 2L * outputSize) / (1024 * 1024)) + 1);
});
} finally {
COPY_TRANSFORM_HEAP_MIB.release(heldMib);
if (heldMib[0] > 0) {
COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
}
}
}
@@ -621,14 +639,21 @@ public final class S3CopySimulator {
return aligned;
}
/** 1082 = date, 1114 = timestamp. A timestamptz (1184) is read by PostgreSQL as it stands. */
private static CopyRecordTransformer.ColumnKind kindOf(String typeOid) {
/**
* 1082 = date, 1114 = timestamp, and 25 = text, 1043 = varchar for the character columns.
* CHAR (1042 = bpchar) is left as OTHER so missing columns load as NULL, matching AWS FILLRECORD.
* A timestamptz (1184) is read by PostgreSQL as it stands.
*/
static CopyRecordTransformer.ColumnKind kindOf(String typeOid) {
if ("1082".equals(typeOid)) {
return CopyRecordTransformer.ColumnKind.DATE;
}
if ("1114".equals(typeOid)) {
return CopyRecordTransformer.ColumnKind.TIMESTAMP;
}
if ("25".equals(typeOid) || "1043".equals(typeOid)) {
return CopyRecordTransformer.ColumnKind.TEXT;
}
return CopyRecordTransformer.ColumnKind.OTHER;
}
@@ -657,7 +682,7 @@ public final class S3CopySimulator {
String query = "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 "
+ "WHERE a.attrelid = to_regclass('" + quoteLiteral(spec.targetTable()) + "') "
+ "AND a.attnum > 0 AND NOT a.attisdropped "
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' "
+ "ORDER BY a.attnum";
OutputStream backendOut = backend.getOutputStream();
@@ -140,6 +140,98 @@ class CopyRecordTransformerTest {
applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", true), "a|00/00/00|2003-03-31 18:45:05\n"));
}
private static final List<CopyRecordTransformer.ColumnKind> FILL_KINDS = List.of(
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.TEXT,
CopyRecordTransformer.ColumnKind.DATE,
CopyRecordTransformer.ColumnKind.TEXT);
private static String applyFill(boolean csv, boolean emptyAsNull, String input) {
return applyFill(csv, null, new CopyStatementParser.CopyTransforms(
false, emptyAsNull, false, false, null, null, null, false, true), input);
}
private static String applyFill(boolean csv, String nullAs, CopyStatementParser.CopyTransforms transforms,
String input) {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", csv ? "," : "|", 0, false, csv, nullAs, null, false, false, false,
transforms);
return new String(new CopyRecordTransformer(spec, null, FILL_KINDS)
.apply(input.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}
@Test
void fillRecordUsesTheCustomNullString() {
CopyStatementParser.CopyTransforms fill = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
assertEquals("1|a|NA|\n", applyFill(false, "NA", fill, "1|a\n"));
}
@Test
void fillRecordWithAnEmptyNullStringNullsTheCharacterColumnsToo() {
CopyStatementParser.CopyTransforms fill = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
assertEquals("1|a||\n", applyFill(false, "", fill, "1|a\n"));
assertEquals("1,a,,\n", applyFill(true, "", fill, "1,a\n"));
}
@Test
void fillRecordLeavesARecordWithTooManyFieldsToPostgres() {
CopyStatementParser.CopyTransforms fill = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
assertEquals("1|a|2020-01-01|x|extra\n", applyFill(false, null, fill, "1|a|2020-01-01|x|extra\n"));
}
@Test
void fillRecordTreatsABlankLineAsOneEmptyField() {
assertEquals("||\\N|\n", applyFill(false, false, "\n"));
}
@Test
void fillRecordWorksWithTheDateFormatAndRemoveQuotesOfTheSameCopy() {
CopyStatementParser.CopyTransforms both = new CopyStatementParser.CopyTransforms(
false, false, true, false, null, CopyTemporalFormat.parse("MM/DD/YYYY", false), null, false, true);
assertEquals("1|a|2003-03-31|\n", applyFill(false, null, both, "1|\"a\"|03/31/2003\n"));
assertEquals("1|a|\\N|\n", applyFill(false, null, both, "1|\"a\"\n"));
}
@Test
void fillRecordGivesCharacterColumnsAnEmptyStringAndTheOthersNull() {
assertEquals("1|a|\\N|\n2|b|2020-01-01|x\n", applyFill(false, false, "1|a\n2|b|2020-01-01|x\n"));
assertEquals("1||\\N|\n", applyFill(false, false, "1\n"));
}
@Test
void fillRecordWithEmptyAsNullFillsCharacterColumnsWithNull() {
assertEquals("1|a|\\N|\\N\n", applyFill(false, true, "1|a\n"));
}
@Test
void fillRecordQuotesTheEmptyStringInCsvWhereAnEmptyFieldIsNull() {
assertEquals("1,a,,\"\"\n", applyFill(true, false, "1,a\n"));
assertEquals("1,a,,\n", applyFill(true, true, "1,a\n"));
}
@Test
void fillRecordLeavesCompleteAndCrlfRecordsAlone() {
assertEquals("1|a|2020-01-01|x\n", applyFill(false, false, "1|a|2020-01-01|x\r\n"));
assertEquals("1|a|\\N|\n", applyFill(false, false, "1|a\r\n"));
}
@Test
void fillRecordFillsAnUnterminatedLastRecord() {
assertEquals("1|a|\\N|\n", applyFill(false, false, "1|a"));
}
@Test
void aShortRecordIsLeftAloneWithoutFillRecord() {
assertEquals("1|a\n", apply("|", false, null, transforms(false, true, false, false, null), "1|a\n"));
}
@Test
void acceptAnyDateWithoutAFormatLoadsIsoValuesAndNullsTheRest() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
@@ -227,7 +227,7 @@ class CopyStatementParserTest {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 's3://mybucket/jsonpaths.json'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FIXEDWIDTH 'a:1,b:2'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP MAXERROR 10"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FILLRECORD"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TRIMBLANKS"));
}
@@ -520,6 +520,19 @@ class CopyStatementParserTest {
assertEquals("YYYY-MM-DD[ HH:MI:SS]", transforms.timeFormat().spec());
}
@Test
void copyParsesFillRecord() {
CopyStatementParser.CopyTransforms transforms =
copyFrom("COPY t FROM 's3://b/k' CSV FILLRECORD EMPTYASNULL").transforms();
assertTrue(transforms.fillRecord());
assertTrue(transforms.fieldLevel());
assertTrue(transforms.needsColumnTypes());
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FILLRECORD FILLRECORD"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS JSON 'auto' FILLRECORD"));
assertFalse(copyFrom("COPY t FROM 's3://b/k'").transforms().fillRecord());
}
@Test
void copyRejectsInvalidDateFormatOptions() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'nonsense'"));
@@ -1662,6 +1662,31 @@ class S3CopySimulatorTest {
S3CopySimulator.alignKinds(explicit, catalog));
}
@Test
void kindOf_mapsTheCatalogTypeOids() {
assertEquals(CopyRecordTransformer.ColumnKind.DATE, S3CopySimulator.kindOf("1082"));
assertEquals(CopyRecordTransformer.ColumnKind.TIMESTAMP, S3CopySimulator.kindOf("1114"));
assertEquals(CopyRecordTransformer.ColumnKind.TEXT, S3CopySimulator.kindOf("25"));
assertEquals(CopyRecordTransformer.ColumnKind.OTHER, S3CopySimulator.kindOf("1042"));
assertEquals(CopyRecordTransformer.ColumnKind.TEXT, S3CopySimulator.kindOf("1043"));
assertEquals(CopyRecordTransformer.ColumnKind.OTHER, S3CopySimulator.kindOf("1184"));
assertEquals(CopyRecordTransformer.ColumnKind.OTHER, S3CopySimulator.kindOf("23"));
assertEquals(CopyRecordTransformer.ColumnKind.OTHER, S3CopySimulator.kindOf(null));
}
@Test
void alignKinds_sizesTheResultToTheColumnListNotTheTable() {
List<S3CopySimulator.ColumnInfo> catalog = List.of(
new S3CopySimulator.ColumnInfo("id", null, CopyRecordTransformer.ColumnKind.OTHER),
new S3CopySimulator.ColumnInfo("name", 10, CopyRecordTransformer.ColumnKind.TEXT),
new S3CopySimulator.ColumnInfo("born", null, CopyRecordTransformer.ColumnKind.DATE));
CopyStatementParser.S3CopyFrom shortList = new CopyStatementParser.S3CopyFrom(
"t", List.of("id", "name"), "wh", "k", "|", 0, false, false, null, null);
assertEquals(List.of(CopyRecordTransformer.ColumnKind.OTHER, CopyRecordTransformer.ColumnKind.TEXT),
S3CopySimulator.alignKinds(shortList, catalog));
}
@Test
void streamCopyInput_rewritesDatesWithTheColumnKindsOfTheCatalog() throws Exception {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
@@ -1680,6 +1705,37 @@ class S3CopySimulatorTest {
assertEquals("1|2003-03-31\n", copyDataPayload(out.toByteArray()));
}
@Test
void streamCopyInput_fillsShortRecordsWithTheColumnKindsOfTheCatalog() throws Exception {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"people", List.of(), "wh", "p.txt", "|", 0, false, false, null, null,
false, false, false, transforms);
when(s3.getObject("wh", "p.txt")).thenReturn(new S3Object("wh", "p.txt",
"1\n2|b|7\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("p.txt"), s3, null, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
S3CopySimulator.streamCopyInput(input, null, null, List.of(CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.TEXT, CopyRecordTransformer.ColumnKind.OTHER), out);
assertEquals("1||\\N\n2|b|7\n", copyDataPayload(out.toByteArray()));
}
@Test
void streamCopyInput_withFillRecordAndNoCatalogFailsAndNamesSimpleQueryMode() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
assertTrue(failure.getMessage().contains("preferQueryMode=simple"), failure.getMessage());
}
@Test
void streamCopyInput_withDateFormatsAndNoCatalogFailsAndNamesSimpleQueryMode() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
@@ -1729,6 +1785,65 @@ class S3CopySimulatorTest {
}
}
@Test
void streamCopyInput_withFillRecordOutputOverTheObjectLimitFailsTheStatementAndReleasesTheBudget() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", "1\n2\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
long saved = S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES;
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = 16;
List<CopyRecordTransformer.ColumnKind> kinds = List.of(
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.TEXT,
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.OTHER);
try {
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, null, null, kinds, new ByteArrayOutputStream()));
assertTrue(failure.getMessage().contains("16-byte limit"), failure.getMessage());
assertEquals(availableBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
} finally {
S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES = saved;
}
}
@Test
void streamCopyInput_withFillRecordOutputExhaustingHeapBudgetFailsAndReleasesTheBudget() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, true);
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, false, null, null, false, false, false, transforms);
String inputData = "1\n".repeat(2000);
when(s3.getObject("wh", "k")).thenReturn(
new S3Object("wh", "k", inputData.getBytes(StandardCharsets.UTF_8), "text/plain"));
S3CopySimulator.CopyInput input = new S3CopySimulator.CopyInput(spec, List.of("k"), s3, null, null);
List<CopyRecordTransformer.ColumnKind> kinds = new ArrayList<>();
for (int i = 0; i < 300; i++) {
kinds.add(CopyRecordTransformer.ColumnKind.OTHER);
}
int availableBefore = S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits();
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.acquireUninterruptibly(availableBefore - 1);
try {
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, null, null, kinds, new ByteArrayOutputStream()));
assertTrue(failure.getMessage().contains("memory budget exhausted"), failure.getMessage());
assertEquals(1, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
} finally {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(availableBefore - 1);
}
assertEquals(availableBefore, S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.availablePermits());
}
@Test
void copyBackendSql_quotesDiscoveredColumnIdentifiers() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(