diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 6c89c1f6c4..6fc7c3f870 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -877,7 +877,9 @@ 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 ` and `HEADER`, `NULL AS`, `FORMAT AS JSON 'auto'`, `FORMAT AS JSON 'auto ignorecase'` (or bare `JSON 'auto'`), - `MANIFEST`, and an explicit column list. + `MANIFEST`, `COMPUPDATE`, `STATUPDATE`, `TRIMBLANKS`, 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 a comma default delimiter. - `FORMAT AS JSON 'auto'` loads JSON objects, mapping JSON keys to table columns with exact case @@ -912,10 +914,12 @@ order) through its own S3 service and streams the rows into the backing PostgreS stored, and the statement text keeps them out of Floci's own messages. Combining key credentials with `IAM_ROLE`, or giving only one of the pair, is not intercepted, and neither is a blank key, secret, token or role. -- `EMPTYASNULL`, `BLANKSASNULL`, `REMOVEQUOTES` (not with `CSV` or `JSON`), `ACCEPTINVCHARS [AS 'c']` +- `EMPTYASNULL`, `BLANKSASNULL`, `TRIMBLANKS`, `REMOVEQUOTES` (not with `CSV` or `JSON`), `ACCEPTINVCHARS [AS 'c']` (default `?`, one ASCII character) and `TRUNCATECOLUMNS` rewrite field content before loading. Field level options need a single-byte `DELIMITER`, are not combined with `FORMAT AS JSON`, and normalise - `CRLF` line endings to `LF`. A nulled field is written as the `NULL AS` string, or `\N` in text + `CRLF` line endings to `LF`. `TRIMBLANKS` removes trailing white space (spaces and tabs) from `VARCHAR` columns; + combined with `EMPTYASNULL`, a field containing only spaces converts to `NULL`. A nulled field is written + as the `NULL AS` string, or `\N` in text mode and an empty unquoted field in CSV mode. `TRUNCATECOLUMNS` cuts a value to the declared `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 diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformer.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformer.java index 7d4b19256b..c2e3eec0bb 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformer.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformer.java @@ -221,17 +221,30 @@ final class CopyRecordTransformer { private void writeField(Field field, int column, ByteArrayOutputStream out) { byte[] value = field.value(); + boolean isVarchar = columnKinds == null + || (column < columnKinds.size() && columnKinds.get(column) == ColumnKind.TEXT); + // A NULL marker that ends in spaces is matched on the raw field, so trimming must leave it alone. + boolean rawNullMarker = !field.quoted() && Arrays.equals(value, nullMarker); + if (transforms.trimBlanks() && isVarchar && !rawNullMarker) { + value = trimTrailingSpaces(value, csv); + } + // Trimming a CSV field down to nothing yields an empty string, which an unquoted empty field would turn into NULL. + boolean trimmedToEmpty = csv && !field.quoted() && value.length == 0 && field.value().length > 0; boolean emptyField = !field.quoted() && value.length == 0; boolean nonCharacter = columnKinds != null && column < columnKinds.size() && columnKinds.get(column) != ColumnKind.TEXT && columnKinds.get(column) != ColumnKind.CHAR; - boolean nulled = (transforms.blanksAsNull() && isBlank(value)) + boolean nulled = (transforms.blanksAsNull() && isBlank(field.value())) || (transforms.emptyAsNull() && value.length == 0) || (emptyField && nonCharacter); if (nulled) { out.writeBytes(nullMarker); return; } + if (trimmedToEmpty && nullMarker.length == 0) { + out.writeBytes(new byte[]{DOUBLE_QUOTE, DOUBLE_QUOTE}); + return; + } // 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; @@ -257,6 +270,26 @@ final class CopyRecordTransformer { } } + private static byte[] trimTrailingSpaces(byte[] value, boolean csv) { + int end = value.length; + while (end > 0) { + if (value[end - 1] != ' ' && value[end - 1] != '\t') { + break; + } + if (!csv) { + int backslashes = 0; + for (int k = end - 2; k >= 0 && value[k] == BACKSLASH; k--) { + backslashes++; + } + if ((backslashes % 2) != 0) { + break; + } + } + end--; + } + return end == value.length ? value : Arrays.copyOf(value, end); + } + private boolean containsDelimiter(byte[] value) { for (byte b : value) { if (b == delimiter) { diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java index 572f52c391..9b67f69927 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/CopyStatementParser.java @@ -40,14 +40,15 @@ public final class CopyStatementParser { CopyTemporalFormat timeFormat, boolean acceptAnyDate, boolean fillRecord, - int maxError) { + int maxError, + boolean trimBlanks) { 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, false, 0); + null, null, false, false, 0, false); } public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes, @@ -55,7 +56,7 @@ public final class CopyStatementParser { CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat, boolean acceptAnyDate) { this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement, - dateFormat, timeFormat, acceptAnyDate, false, 0); + dateFormat, timeFormat, acceptAnyDate, false, 0, false); } public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes, @@ -63,7 +64,15 @@ public final class CopyStatementParser { CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat, boolean acceptAnyDate, boolean fillRecord) { this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement, - dateFormat, timeFormat, acceptAnyDate, fillRecord, 0); + dateFormat, timeFormat, acceptAnyDate, fillRecord, 0, false); + } + + public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes, + boolean truncateColumns, Character invalidCharReplacement, + CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat, + boolean acceptAnyDate, boolean fillRecord, int maxError) { + this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement, + dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, false); } /** @@ -76,7 +85,7 @@ public final class CopyStatementParser { /** Whether the options depend on the type of each column, which only the catalog can tell. */ public boolean needsColumnTypes() { - return temporal() || fillRecord; + return temporal() || fillRecord || trimBlanks; } /** Whether date or timestamp fields are read with a format other than PostgreSQL's own. */ @@ -85,7 +94,8 @@ public final class CopyStatementParser { } public boolean fieldLevel() { - return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal() || fillRecord; + return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal() || fillRecord + || trimBlanks; } public boolean any() { @@ -380,6 +390,11 @@ public final class CopyStatementParser { private static final Pattern CSV_PATTERN = Pattern.compile("(?i)\\b(?:FORMAT\\s+(?:AS\\s+)?)?CSV\\b"); private static final Pattern JSON_AUTO_PATTERN = Pattern.compile( "(?i)\\b(?:FORMAT\\s+(?:AS\\s+)?)?JSON(?:\\s+AS)?\\s+['\"]auto(?:\\s+(ignorecase))?['\"]"); + private static final Pattern COMPUPDATE_PATTERN = Pattern.compile( + "(?i)\\bCOMPUPDATE(?:\\s+(?:PRESET|ON|OFF|TRUE|FALSE))?\\b"); + private static final Pattern STATUPDATE_PATTERN = Pattern.compile( + "(?i)\\bSTATUPDATE(?:\\s+(?:ON|OFF|TRUE|FALSE))?\\b"); + private static final Pattern TRIMBLANKS_PATTERN = Pattern.compile("(?i)\\bTRIMBLANKS\\b"); /** * Options this simulator does not implement. A COPY carrying any of these is not intercepted: @@ -390,9 +405,8 @@ public final class CopyStatementParser { "(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD" + "|ENCRYPTED|ENCODING" + "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID" - + "|TRIMBLANKS" - + "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS|COMPUPDATE" - + "|STATUPDATE|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b"); + + "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS" + + "|NOLOAD|ROUNDEC|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"); @@ -725,6 +739,10 @@ public final class CopyStatementParser { boolean fillRecord = false; int maxError = 0; boolean seenMaxError = false; + boolean trimBlanks = false; + boolean seenCompupdate = false; + boolean seenStatupdate = false; + boolean seenTrimBlanks = false; boolean seenDateFormat = false; boolean seenTimeFormat = false; @@ -759,6 +777,9 @@ public final class CopyStatementParser { Matcher acceptAnyDateMatcher = ACCEPTANYDATE_PATTERN.matcher(options); Matcher fillRecordMatcher = FILLRECORD_PATTERN.matcher(options); Matcher maxErrorMatcher = MAXERROR_PATTERN.matcher(options); + Matcher compupdateMatcher = COMPUPDATE_PATTERN.matcher(options); + Matcher statupdateMatcher = STATUPDATE_PATTERN.matcher(options); + Matcher trimBlanksMatcher = TRIMBLANKS_PATTERN.matcher(options); AuthClauses auth = new AuthClauses(options, defaultIamRoleArn); int next; @@ -900,6 +921,25 @@ public final class CopyStatementParser { seenMaxError = true; maxError = parsed; offset = maxErrorMatcher.end(); + } else if (matchClause(compupdateMatcher, offset, len)) { + if (seenCompupdate) { + return null; + } + seenCompupdate = true; + offset = compupdateMatcher.end(); + } else if (matchClause(statupdateMatcher, offset, len)) { + if (seenStatupdate) { + return null; + } + seenStatupdate = true; + offset = statupdateMatcher.end(); + } else if (matchClause(trimBlanksMatcher, offset, len)) { + if (seenTrimBlanks) { + return null; + } + seenTrimBlanks = true; + trimBlanks = true; + offset = trimBlanksMatcher.end(); } else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) { if (next == AuthClauses.REJECT) { return null; @@ -928,7 +968,7 @@ public final class CopyStatementParser { } CopyTransforms transforms = new CopyTransforms( blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar, - dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError); + dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError, trimBlanks); if (transforms.any() && jsonAuto) { return null; } diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java index 87424b70c4..d1c9a218a7 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/S3CopySimulator.java @@ -577,7 +577,7 @@ public final class S3CopySimulator { } if (spec.transforms().needsColumnTypes() && columnKinds == null) { throw new S3TransferException(SQLSTATE_INTERNAL, - "COPY ... DATEFORMAT, TIMEFORMAT and FILLRECORD need catalog column types, which are only " + "COPY ... DATEFORMAT, TIMEFORMAT, FILLRECORD and TRIMBLANKS need catalog column types, which are only " + "available over the Simple Query protocol; connect with preferQueryMode=simple", null); } byte[] buffer = new byte[CHUNK]; @@ -626,7 +626,7 @@ public final class S3CopySimulator { "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); + + "DATEFORMAT, TIMEFORMAT, FILLRECORD, TRIMBLANKS)", null); } } diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformerTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformerTest.java index b5b588e6af..f0f8f0330a 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformerTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyRecordTransformerTest.java @@ -459,4 +459,105 @@ class CopyRecordTransformerTest { byte[] out = new CopyRecordTransformer(spec, null).apply(new byte[]{'a', (byte) 0xFF, '\n'}); assertEquals("a#\n", new String(out, StandardCharsets.UTF_8)); } + + @Test + void trimBlanksTrimsTrailingSpacesFromTextFields() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("hello|world\n", + apply("|", false, null, transforms, "hello |world \n")); + assertEquals(" hello|world\n", + apply("|", false, null, transforms, " hello|world\n")); + } + + @Test + void trimBlanksTrimsTrailingTabsAndSpaces() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("hello|world\n", + apply("|", false, null, transforms, "hello \t |world\t\n")); + } + + @Test + void trimBlanksWithEmptyAsNullConvertsAllSpacesToNull() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, true, false, false, null, null, null, false, false, 0, true); + assertEquals("\\N|hello\n", + apply("|", false, null, transforms, " |hello \n")); + } + + @Test + void trimBlanksWithoutEmptyAsNullConvertsAllSpacesToEmptyString() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("|hello\n", + apply("|", false, null, transforms, " |hello \n")); + } + + @Test + void trimBlanksWithBlanksAsNullConvertsAllSpacesToNull() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + true, false, false, false, null, null, null, false, false, 0, true); + assertEquals("\\N|hello\n", + apply("|", false, null, transforms, " |hello \n")); + } + + @Test + void trimBlanksInCsvModeTrimsTrailingSpaces() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("hello,world\n", + apply(",", true, null, transforms, "hello ,world \n")); + assertEquals("\"hello\",\"world\"\n", + apply(",", true, null, transforms, "\"hello \",\"world \"\n")); + } + + @Test + void trimBlanksAppliesOnlyToVarcharWhenColumnKindsProvided() { + List kinds = List.of( + CopyRecordTransformer.ColumnKind.TEXT, + CopyRecordTransformer.ColumnKind.CHAR, + CopyRecordTransformer.ColumnKind.OTHER); + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom( + "t", List.of(), "b", "k", "|", 0, false, false, null, null, false, false, false, transforms); + byte[] out = new CopyRecordTransformer(spec, null, kinds) + .apply("hello |world |123 \n".getBytes(StandardCharsets.UTF_8)); + assertEquals("hello|world |123 \n", new String(out, StandardCharsets.UTF_8)); + } + + @Test + void trimBlanksKeepsANullMarkerThatEndsInSpaces() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("N |hello\n", apply("|", false, "N ", transforms, "N |hello \n")); + assertEquals("N ,hello\n", apply(",", true, "N ", transforms, "N ,hello \n")); + } + + @Test + void trimBlanksQuotesACsvFieldThatTrimsToAnEmptyStringSoItIsNotNull() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("\"\",hello\n", apply(",", true, null, transforms, " ,hello \n")); + // a field that was empty to begin with stays NULL + assertEquals(",hello\n", apply(",", true, null, transforms, ",hello \n")); + } + + @Test + void trimBlanksWithEmptyAsNullStillNullsASpaceOnlyCsvField() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, true, false, false, null, null, null, false, false, 0, true); + assertEquals(",hello\n", apply(",", true, null, transforms, " ,hello \n")); + } + + @Test + void trimBlanksPreservesEscapedTrailingSpacesInTextMode() { + CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms( + false, false, false, false, null, null, null, false, false, 0, true); + assertEquals("hello\\ \n", + apply("|", false, null, transforms, "hello\\ \n")); + assertEquals("hello\\\\\n", + apply("|", false, null, transforms, "hello\\\\ \n")); + } } diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java index e9c6c1203b..92aeb94bfa 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/CopyStatementParserTest.java @@ -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 ESCAPE")); - assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TRIMBLANKS")); + assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' EXPLICIT_IDS")); } @@ -782,5 +782,41 @@ class CopyStatementParserTest { assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' JSON 's3://b/paths.json'")); assertNull(CopyStatementParser.parse("COPY tbl FROM 's3://b/k' PARQUET")); } + + @Test + void parsesCompupdateAndStatupdateOptions() { + for (String comp : List.of("COMPUPDATE", "COMPUPDATE PRESET", "COMPUPDATE ON", "COMPUPDATE OFF", "COMPUPDATE TRUE", "COMPUPDATE FALSE")) { + CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' " + comp); + assertNotNull(c); + assertEquals("t", c.targetTable()); + } + for (String stat : List.of("STATUPDATE", "STATUPDATE ON", "STATUPDATE OFF", "STATUPDATE TRUE", "STATUPDATE FALSE")) { + CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' " + stat); + assertNotNull(c); + assertEquals("t", c.targetTable()); + } + CopyStatementParser.S3CopyFrom both = copyFrom( + "COPY t FROM 's3://b/k' COMPUPDATE ON STATUPDATE OFF"); + assertNotNull(both); + assertEquals("t", both.targetTable()); + + assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' COMPUPDATE ON COMPUPDATE OFF")); + assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' STATUPDATE ON STATUPDATE OFF")); + } + + @Test + void parsesTrimblanksOption() { + CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' TRIMBLANKS"); + assertNotNull(c); + assertTrue(c.transforms().trimBlanks()); + assertTrue(c.transforms().fieldLevel()); + assertTrue(c.transforms().needsColumnTypes()); + + CopyStatementParser.S3CopyFrom without = copyFrom("COPY t FROM 's3://b/k'"); + assertNotNull(without); + assertFalse(without.transforms().trimBlanks()); + + assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TRIMBLANKS TRIMBLANKS")); + } }