feat(redshift): support MAXERROR in COPY (#7291)

* feat(redshift): support MAXERROR in COPY

MAXERROR n of 2 or more now asks the backend to skip records it cannot convert
(ON_ERROR ignore) and to fail the COPY at the n-th one (REJECT_LIMIT n - 1),
which needs a PostgreSQL 18 backend. A MAXERROR of 0 or 1 fails at the first
error, as without the option.

* test(redshift): add PostgreSQL 18 MAXERROR integration test

* test(redshift): use shared DockerAvailability and RedshiftConnections in PostgreSQL 18 IT

Address review feedback on PR #7291:
- Call testing.DockerAvailability.isAvailable() instead of carrying a private copy of the probe.
- Use RedshiftConnections.waitForConnection(cluster) instead of duplicating the JDBC connection wait helper.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-02 11:58:15 -04:00
1 parent 6a390496eb
commit d4eeada135
7 files changed
+270 -11

No files matched your search

+16 -3
View File
@@ -798,8 +798,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
`TIMEFORMAT` also takes `'epochsecs'` and `'epochmillisecs'`, read as UTC. A `DATEFORMAT` may name a time
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 fails the COPY, as it does with Redshift's default `MAXERROR` of 0; the message names the
column and the format, and Floci writes no `stl_load_errors` row. `ACCEPTANYDATE` loads such a value as
match its format fails the COPY, whatever `MAXERROR` says; the message names the column and the format, and
Floci writes no `stl_load_errors` row. `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`. Numeric parts with no separator between them, as in `YYYYMMDD`, need their
full width, a part may be named once, and `HH12` needs `AM` or `PM`; any other format string is not
@@ -819,7 +819,20 @@ order) through its own S3 service and streams the rows into the backing PostgreS
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`,
- `MAXERROR [AS] n` (0 to 100000) lets the load go on past records that cannot be converted. With `n` of 0 or 1 the
COPY fails at the first error, as it does without the option. With a larger `n` Floci asks the backend to skip
the failing records (`ON_ERROR ignore`) and to fail the COPY, rolling it back, once `n` of them have been
skipped (`REJECT_LIMIT n - 1`). This uses the PostgreSQL `COPY` options of the same names, so it needs a
PostgreSQL 18 backend (set `floci.services.redshift.image-version`, for example `postgres:18-alpine`); the
default backend rejects the option as unknown and the COPY fails with that error. The COPY fails when the
`n`-th record is rejected, counted across all the files of the load. Floci deviations: only a value that the
backend cannot convert to its column type is skipped, whereas Redshift also skips a record with too many or too
few fields, a `NOT NULL` violation and other errors, which still fail the COPY here. So do a value that does
not match a `DATEFORMAT` or `TIMEFORMAT` (use `ACCEPTANYDATE` to load it as `NULL`), a quoted field without its
closing quote under `REMOVEQUOTES`, and a line that `FORMAT AS JSON 'auto'` cannot read, since Floci rejects
those before the backend sees them. The backend reports the count of skipped records in its own notice, not
Redshift's `Load into table ... completed` message, and no `stl_load_errors` row is written.
- 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
returns its own error.
@@ -286,8 +286,8 @@ final class CopyRecordTransformer {
/**
* 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
* value that does not match into NULL; without it such a value fails the COPY, as it does with the
* default MAXERROR of 0.
* value that does not match into NULL; without it such a value fails the COPY, whatever MAXERROR says,
* because it never reaches the backend that skips records under MAXERROR.
*/
private byte[] convertTemporal(byte[] value, int column) {
if (!transforms.temporal() || columnKinds == null || column >= columnKinds.size()) {
@@ -30,14 +30,15 @@ public final class CopyStatementParser {
CopyTemporalFormat dateFormat,
CopyTemporalFormat timeFormat,
boolean acceptAnyDate,
boolean fillRecord) {
boolean fillRecord,
int maxError) {
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);
null, null, false, false, 0);
}
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
@@ -45,7 +46,23 @@ public final class CopyStatementParser {
CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat,
boolean acceptAnyDate) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
dateFormat, timeFormat, acceptAnyDate, false);
dateFormat, timeFormat, acceptAnyDate, false, 0);
}
public CopyTransforms(boolean blanksAsNull, boolean emptyAsNull, boolean removeQuotes,
boolean truncateColumns, Character invalidCharReplacement,
CopyTemporalFormat dateFormat, CopyTemporalFormat timeFormat,
boolean acceptAnyDate, boolean fillRecord) {
this(blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidCharReplacement,
dateFormat, timeFormat, acceptAnyDate, fillRecord, 0);
}
/**
* Whether the load goes on past a record the backend cannot convert. A {@code MAXERROR} of 0 or 1 fails
* the COPY at the first error, which is how it runs without the option.
*/
public boolean toleratesErrors() {
return maxError > 1;
}
/** Whether the options depend on the type of each column, which only the catalog can tell. */
@@ -301,6 +318,8 @@ public final class CopyStatementParser {
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 MAXERROR_PATTERN = Pattern.compile("(?i)\\bMAXERROR\\s+(?:AS\\s+)?(\\d{1,9})\\b");
private static final int MAX_MAXERROR = 100_000;
private static final Pattern CREDENTIALS_PATTERN = Pattern.compile(
"(?i)\\bCREDENTIALS\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile(
@@ -331,7 +350,7 @@ public final class CopyStatementParser {
* silently loading the data with the wrong framing.
*/
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD|MAXERROR"
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD"
+ "|ENCRYPTED|ENCODING"
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|TRIMBLANKS"
@@ -656,6 +675,8 @@ public final class CopyStatementParser {
CopyTemporalFormat timeFormat = null;
boolean acceptAnyDate = false;
boolean fillRecord = false;
int maxError = 0;
boolean seenMaxError = false;
boolean seenDateFormat = false;
boolean seenTimeFormat = false;
@@ -689,6 +710,7 @@ public final class CopyStatementParser {
Matcher timeFormatMatcher = TIMEFORMAT_PATTERN.matcher(options);
Matcher acceptAnyDateMatcher = ACCEPTANYDATE_PATTERN.matcher(options);
Matcher fillRecordMatcher = FILLRECORD_PATTERN.matcher(options);
Matcher maxErrorMatcher = MAXERROR_PATTERN.matcher(options);
AuthClauses auth = new AuthClauses(options, defaultIamRoleArn);
int next;
@@ -822,6 +844,14 @@ public final class CopyStatementParser {
}
fillRecord = true;
offset = fillRecordMatcher.end();
} else if (matchClause(maxErrorMatcher, offset, len)) {
int parsed = seenMaxError ? -1 : Integer.parseInt(maxErrorMatcher.group(1));
if (parsed < 0 || parsed > MAX_MAXERROR) {
return null;
}
seenMaxError = true;
maxError = parsed;
offset = maxErrorMatcher.end();
} else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) {
if (next == AuthClauses.REJECT) {
return null;
@@ -850,7 +880,7 @@ public final class CopyStatementParser {
}
CopyTransforms transforms = new CopyTransforms(
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar,
dateFormat, timeFormat, acceptAnyDate, fillRecord);
dateFormat, timeFormat, acceptAnyDate, fillRecord, maxError);
if (transforms.any() && jsonAuto) {
return null;
}
@@ -459,6 +459,11 @@ public final class S3CopySimulator {
if (spec.nullAs() != null) {
sql.append(", NULL '").append(quoteLiteral(spec.nullAs())).append("'");
}
if (spec.transforms().toleratesErrors()) {
// MAXERROR fails the load at the error_count-th error; REJECT_LIMIT tolerates that many errors, not
// more. Both options need a PostgreSQL 18 backend, which an older one rejects as an unknown option.
sql.append(", ON_ERROR ignore, REJECT_LIMIT ").append(spec.transforms().maxError() - 1);
}
sql.append(")");
return sql.toString();
}
@@ -0,0 +1,132 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
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.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(RedshiftMaxErrorPostgres18IntegrationTest.Postgres18Profile.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftMaxErrorPostgres18IntegrationTest {
public static class Postgres18Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.redshift.image-version", "postgres:18-alpine");
}
}
private static final String CLUSTER_ID = "it-maxerror-pg18";
private static final String BUCKET = "it-maxerror-pg18-bucket";
@Inject
RedshiftService service;
@Inject
RedshiftSnapshotScheduler snapshotScheduler;
@Inject
S3Service s3;
private Cluster cluster;
@BeforeAll
void createCluster() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift Docker integration tests");
cluster = service.createCluster(CLUSTER_ID, "dc2.large", "admin", "Secret123");
s3.createBucket(BUCKET, "us-east-1");
}
@AfterAll
void deleteCluster() {
if (cluster != null) {
service.deleteCluster(CLUSTER_ID);
snapshotScheduler.tick(Instant.now());
}
}
@Test
void maxError2LoadsGoodRowsPastOneBadValueAndFailsOnSecond() throws Exception {
s3.putObject(BUCKET, "one-error.txt",
"1|alice\nnot_a_number|bob\n2|charlie\n".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
s3.putObject(BUCKET, "two-errors.txt",
"1|alice\nbad_1|bob\nbad_2|charlie\n2|david\n".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
try (Connection connection = RedshiftConnections.waitForConnection(cluster);
Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE t_maxerror_two (id int, name text)");
// MAXERROR 2 tolerates 1 conversion error (REJECT_LIMIT 1) and loads the good rows past it
stmt.execute("COPY t_maxerror_two (id, name) FROM 's3://" + BUCKET + "/one-error.txt' "
+ "DELIMITER '|' MAXERROR 2");
try (ResultSet rs = stmt.executeQuery("SELECT count(*), min(id), max(id) FROM t_maxerror_two")) {
assertTrue(rs.next());
assertEquals(2, rs.getInt(1));
assertEquals(1, rs.getInt(2));
assertEquals(2, rs.getInt(3));
}
// A second bad value reaches the error count of 2 and aborts the COPY
stmt.execute("CREATE TABLE t_maxerror_fail (id int, name text)");
assertThrows(SQLException.class, () -> stmt.execute(
"COPY t_maxerror_fail (id, name) FROM 's3://" + BUCKET + "/two-errors.txt' "
+ "DELIMITER '|' MAXERROR 2"));
try (ResultSet rs = stmt.executeQuery("SELECT count(*) FROM t_maxerror_fail")) {
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
}
}
}
@Test
void maxError0And1FailAtFirstConversionError() throws Exception {
s3.putObject(BUCKET, "one-error-default.txt",
"1|alice\nnot_a_number|bob\n2|charlie\n".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
try (Connection connection = RedshiftConnections.waitForConnection(cluster);
Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE t_maxerror_default (id int, name text)");
// MAXERROR 0 fails at the first error
assertThrows(SQLException.class, () -> stmt.execute(
"COPY t_maxerror_default (id, name) FROM 's3://" + BUCKET + "/one-error-default.txt' "
+ "DELIMITER '|' MAXERROR 0"));
// MAXERROR 1 also fails at the first error
assertThrows(SQLException.class, () -> stmt.execute(
"COPY t_maxerror_default (id, name) FROM 's3://" + BUCKET + "/one-error-default.txt' "
+ "DELIMITER '|' MAXERROR 1"));
try (ResultSet rs = stmt.executeQuery("SELECT count(*) FROM t_maxerror_default")) {
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
}
}
}
}
@@ -226,7 +226,7 @@ class CopyStatementParserTest {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS PARQUET"));
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' GZIP ESCAPE"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TRIMBLANKS"));
}
@@ -520,6 +520,54 @@ class CopyStatementParserTest {
assertEquals("YYYY-MM-DD[ HH:MI:SS]", transforms.timeFormat().spec());
}
@Test
void copyParsesMaxError() {
CopyStatementParser.CopyTransforms tolerant =
copyFrom("COPY t FROM 's3://b/k' MAXERROR AS 10").transforms();
assertEquals(10, tolerant.maxError());
assertTrue(tolerant.toleratesErrors());
assertFalse(tolerant.fieldLevel());
assertEquals(100_000, copyFrom("COPY t FROM 's3://b/k' MAXERROR 100000").transforms().maxError());
assertTrue(copyFrom("COPY t FROM 's3://b/k' FORMAT AS JSON 'auto' MAXERROR 5").transforms()
.toleratesErrors());
}
@Test
void aMaxErrorOfZeroOrOneFailsAtTheFirstErrorAsWithoutTheOption() {
for (String count : new String[] {"0", "1"}) {
CopyStatementParser.CopyTransforms transforms =
copyFrom("COPY t FROM 's3://b/k' MAXERROR " + count).transforms();
assertFalse(transforms.toleratesErrors(), count);
}
assertEquals(0, copyFrom("COPY t FROM 's3://b/k'").transforms().maxError());
}
@Test
void copyRejectsAMaxErrorOutOfRangeOrRepeated() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR 100001"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR 5 MAXERROR 6"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR -1"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR AS"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR abc"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' MAXERROR 1234567890"));
}
@Test
void maxErrorReadsLeadingZerosAndFollowsAnyClauseOrder() {
assertEquals(7, copyFrom("COPY t FROM 's3://b/k' MAXERROR 007").transforms().maxError());
CopyStatementParser.S3CopyFrom before = copyFrom("COPY t FROM 's3://b/k' MAXERROR 5 GZIP IGNOREHEADER 1");
CopyStatementParser.S3CopyFrom after = copyFrom("COPY t FROM 's3://b/k' GZIP IGNOREHEADER 1 MAXERROR 5");
assertEquals(5, before.transforms().maxError());
assertEquals(5, after.transforms().maxError());
assertTrue(before.gzip() && after.gzip());
assertEquals(1, after.headerLines());
}
@Test
void copyParsesFillRecord() {
CopyStatementParser.CopyTransforms transforms =
@@ -1662,6 +1662,37 @@ class S3CopySimulatorTest {
S3CopySimulator.alignKinds(explicit, catalog));
}
private static String backendCopy(int maxError, boolean csv) {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, null, null, false, false, maxError);
return S3CopySimulator.copyBackendSql(new CopyStatementParser.S3CopyFrom(
"t", List.of(), "wh", "k", "|", 0, false, csv, null, null, false, false, false, transforms), null);
}
@Test
void copyBackendSql_asksTheBackendToSkipConversionErrorsUpToMaxErrorMinusOne() {
assertTrue(backendCopy(10, false).endsWith(", ON_ERROR ignore, REJECT_LIMIT 9)"), backendCopy(10, false));
assertTrue(backendCopy(2, true).contains("FORMAT csv"), backendCopy(2, true));
assertTrue(backendCopy(2, true).endsWith(", ON_ERROR ignore, REJECT_LIMIT 1)"), backendCopy(2, true));
}
@Test
void copyBackendSql_buildsTheWholeStatementFromAParsedMaxError() {
CopyStatementParser.S3Statement parsed = CopyStatementParser.parse(
"COPY t FROM 's3://wh/k' DELIMITER '|' NULL AS 'x' GZIP IGNOREHEADER 1 MAXERROR AS 10");
assertEquals("COPY t FROM STDIN WITH (FORMAT text, DELIMITER '|', NULL 'x', ON_ERROR ignore, "
+ "REJECT_LIMIT 9)",
S3CopySimulator.copyBackendSql((CopyStatementParser.S3CopyFrom) parsed, null));
}
@Test
void copyBackendSql_failsAtTheFirstErrorForAMaxErrorOfZeroOrOne() {
assertFalse(backendCopy(0, false).contains("ON_ERROR"), backendCopy(0, false));
assertFalse(backendCopy(1, false).contains("ON_ERROR"), backendCopy(1, false));
assertFalse(backendCopy(1, false).contains("REJECT_LIMIT"), backendCopy(1, false));
}
@Test
void kindOf_mapsTheCatalogTypeOids() {
assertEquals(CopyRecordTransformer.ColumnKind.DATE, S3CopySimulator.kindOf("1082"));