feat(redshift): support DATEFORMAT, TIMEFORMAT and ACCEPTANYDATE in COPY (#7263)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-01 21:55:35 -04:00
1 parent 62cf61614b
commit 105d6732f3
9 files changed
+918 -24

No files matched your search

+20 -1
View File
@@ -792,8 +792,27 @@ order) through its own S3 service and streams the rows into the backing PostgreS
over Extended Query the COPY fails with an error that names this requirement. A field-level option
buffers each decompressed object in memory, so an object 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`,
`MI`, `SS` (with up to six fractional digits) and `AM`/`PM`, with any other punctuation as separators.
`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
`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
recognized.
Like `TRUNCATECOLUMNS`, these read column types from the catalog, so they work only over the Simple Query
protocol and are not combined with `FORMAT AS JSON`. 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
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.
- Any other clause (`FIXEDWIDTH`, `PARQUET`, `AVRO`, `ORC`, `MAXERROR`,
`DATEFORMAT`, `TIMEFORMAT`, `ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
`FILLRECORD`, `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
@@ -19,6 +19,11 @@ final class CopyRecordTransformer {
private static final byte DOUBLE_QUOTE = '"';
private static final byte SINGLE_QUOTE = '\'';
/** What a COPY column holds, as far as the date and time formats are concerned. */
enum ColumnKind {
DATE, TIMESTAMP, OTHER
}
private record Field(int tokenEnd, byte[] value, boolean quoted) {
}
@@ -27,8 +32,15 @@ final class CopyRecordTransformer {
private final byte delimiter;
private final byte[] nullMarker;
private final List<Integer> columnMaxBytes;
private final List<ColumnKind> columnKinds;
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes) {
this(spec, columnMaxBytes, null);
}
CopyRecordTransformer(CopyStatementParser.S3CopyFrom spec, List<Integer> columnMaxBytes,
List<ColumnKind> columnKinds) {
this.columnKinds = columnKinds;
this.transforms = spec.transforms();
this.csv = spec.csv();
String delimiterText = spec.delimiter() != null ? spec.delimiter() : (spec.csv() ? "," : "|");
@@ -193,9 +205,23 @@ final class CopyRecordTransformer {
out.writeBytes(nullMarker);
return;
}
// A field that already is the NULL marker must not be cut: that would turn NULL into data.
byte[] limited = !field.quoted() && Arrays.equals(value, nullMarker) ? value : truncate(value, column);
if (!field.quoted()) {
// 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;
if (!nullMarkerField) {
byte[] temporal = convertTemporal(value, column);
if (temporal == null) {
out.writeBytes(nullMarker);
return;
}
if (temporal != value) {
converted = true;
value = temporal;
}
}
byte[] limited = nullMarkerField ? value : truncate(value, column);
boolean needsEscaping = field.quoted() || (converted && containsDelimiter(limited));
if (!needsEscaping) {
out.writeBytes(limited);
} else if (csv) {
writeCsvQuoted(limited, out);
@@ -204,6 +230,47 @@ final class CopyRecordTransformer {
}
}
private boolean containsDelimiter(byte[] value) {
for (byte b : value) {
if (b == delimiter) {
return true;
}
}
return false;
}
/**
* 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.
*/
private byte[] convertTemporal(byte[] value, int column) {
if (!transforms.temporal() || columnKinds == null || column >= columnKinds.size()) {
return value;
}
ColumnKind kind = columnKinds.get(column);
CopyTemporalFormat format = switch (kind) {
case DATE -> transforms.dateFormat();
case TIMESTAMP -> transforms.timeFormat();
case OTHER -> null;
};
if (format == null || !format.converts()) {
return value;
}
String text = new String(value, StandardCharsets.UTF_8);
try {
String iso = kind == ColumnKind.DATE ? format.toDate(text) : format.toTimestamp(text);
return iso.getBytes(StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
if (transforms.acceptAnyDate()) {
return null;
}
throw malformed("invalid " + (kind == ColumnKind.DATE ? "date" : "timestamp") + " in column "
+ (column + 1) + ": " + e.getMessage());
}
}
private static boolean isBlank(byte[] value) {
if (value.length == 0) {
return false;
@@ -26,12 +26,26 @@ public final class CopyStatementParser {
boolean emptyAsNull,
boolean removeQuotes,
boolean truncateColumns,
Character invalidCharReplacement) {
Character invalidCharReplacement,
CopyTemporalFormat dateFormat,
CopyTemporalFormat timeFormat,
boolean acceptAnyDate) {
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);
}
/** Whether date or timestamp fields are read with a format other than PostgreSQL's own. */
public boolean temporal() {
return (dateFormat != null && dateFormat.converts()) || (timeFormat != null && timeFormat.converts());
}
public boolean fieldLevel() {
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns;
return blanksAsNull || emptyAsNull || removeQuotes || truncateColumns || temporal();
}
public boolean any() {
@@ -269,6 +283,9 @@ public final class CopyStatementParser {
private static final Pattern TRUNCATECOLUMNS_PATTERN = Pattern.compile("(?i)\\bTRUNCATECOLUMNS\\b");
private static final Pattern ACCEPTINVCHARS_PATTERN = Pattern.compile(
"(?i)\\bACCEPTINVCHARS(?:\\s+(?:AS\\s+)?'([ -&(-~])')?");
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 CREDENTIALS_PATTERN = Pattern.compile(
"(?i)\\bCREDENTIALS\\s+(?:AS\\s+)?(?:'((?:[^']|'')*)'|\"([^\"]*)\")");
private static final Pattern ACCESS_KEY_ID_PATTERN = Pattern.compile(
@@ -300,9 +317,9 @@ public final class CopyStatementParser {
*/
private static final Pattern UNSUPPORTED_CLAUSE = Pattern.compile(
"(?i)\\b(FIXEDWIDTH|PARQUET|AVRO|ORC|SHAPEFILE|BZIP2|LZOP|ZSTD|MAXERROR"
+ "|DATEFORMAT|TIMEFORMAT|ENCRYPTED|ENCODING"
+ "|ENCRYPTED|ENCODING"
+ "|MASTER_SYMMETRIC_KEY|KMS_KEY_ID"
+ "|ACCEPTANYDATE|FILLRECORD|TRIMBLANKS"
+ "|FILLRECORD|TRIMBLANKS"
+ "|IGNOREBLANKLINES|ESCAPE|EXPLICIT_IDS|COMPUPDATE"
+ "|STATUPDATE|NOLOAD|ROUNDEC|QUOTE|SSH|READRATIO|COMPROWS|DIMENSION)\\b");
@@ -620,7 +637,12 @@ public final class CopyStatementParser {
boolean removeQuotes = false;
boolean truncateColumns = false;
Character invalidChar = null;
CopyTemporalFormat dateFormat = null;
CopyTemporalFormat timeFormat = null;
boolean acceptAnyDate = false;
boolean seenDateFormat = false;
boolean seenTimeFormat = false;
boolean seenTruncateColumns = false;
boolean seenBlanksAsNull = false;
boolean seenEmptyAsNull = false;
@@ -647,6 +669,9 @@ public final class CopyStatementParser {
Matcher removeQuotesMatcher = REMOVEQUOTES_PATTERN.matcher(options);
Matcher truncateColumnsMatcher = TRUNCATECOLUMNS_PATTERN.matcher(options);
Matcher acceptInvCharsMatcher = ACCEPTINVCHARS_PATTERN.matcher(options);
Matcher dateFormatMatcher = DATEFORMAT_PATTERN.matcher(options);
Matcher timeFormatMatcher = TIMEFORMAT_PATTERN.matcher(options);
Matcher acceptAnyDateMatcher = ACCEPTANYDATE_PATTERN.matcher(options);
AuthClauses auth = new AuthClauses(options, defaultIamRoleArn);
int next;
@@ -754,6 +779,26 @@ public final class CopyStatementParser {
? Character.valueOf(acceptInvCharsMatcher.group(1).charAt(0))
: Character.valueOf('?');
offset = acceptInvCharsMatcher.end();
} else if (matchClause(dateFormatMatcher, offset, len)) {
dateFormat = seenDateFormat ? null : CopyTemporalFormat.parse(dateFormatMatcher.group(1), false);
if (dateFormat == null) {
return null;
}
seenDateFormat = true;
offset = dateFormatMatcher.end();
} else if (matchClause(timeFormatMatcher, offset, len)) {
timeFormat = seenTimeFormat ? null : CopyTemporalFormat.parse(timeFormatMatcher.group(1), true);
if (timeFormat == null) {
return null;
}
seenTimeFormat = true;
offset = timeFormatMatcher.end();
} else if (matchClause(acceptAnyDateMatcher, offset, len)) {
if (acceptAnyDate) {
return null;
}
acceptAnyDate = true;
offset = acceptAnyDateMatcher.end();
} else if ((next = auth.consume(offset, len)) != AuthClauses.NO_MATCH) {
if (next == AuthClauses.REJECT) {
return null;
@@ -772,8 +817,17 @@ public final class CopyStatementParser {
delimiter = csv ? "," : "|";
}
// ACCEPTANYDATE turns a value that does not match its format into NULL, so it needs a format to
// judge by: without DATEFORMAT or TIMEFORMAT that is the ISO form PostgreSQL reads too.
if (acceptAnyDate && dateFormat == null) {
dateFormat = CopyTemporalFormat.defaultIso();
}
if (acceptAnyDate && timeFormat == null) {
timeFormat = CopyTemporalFormat.defaultIso();
}
CopyTransforms transforms = new CopyTransforms(
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar);
blanksAsNull, emptyAsNull, removeQuotes, truncateColumns, invalidChar,
dateFormat, timeFormat, acceptAnyDate);
if (transforms.any() && jsonAuto) {
return null;
}
@@ -0,0 +1,341 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The format a COPY {@code DATEFORMAT} or {@code TIMEFORMAT} names, and the conversion of a source value
* into the ISO text PostgreSQL reads. A format is a string of dateparts and timeparts with separators between
* them, {@code 'auto'}, or for TIMEFORMAT an epoch keyword. {@code 'auto'} is left to PostgreSQL, whose own
* parser already reads most of the forms Redshift recognizes, so it converts nothing.
*/
final class CopyTemporalFormat {
private enum Mode {
PATTERN, ISO, AUTO, EPOCH_SECONDS, EPOCH_MILLISECONDS
}
/** Tokens in the order they are tried, so a longer one is never cut short by a prefix of it. */
private static final List<String> TOKENS = List.of(
"YYYY", "HH24", "HH12", "MON", "YY", "MM", "DD", "HH", "MI", "SS", "AM", "PM");
private static final Pattern EPOCH = Pattern.compile("-?\\d+");
private static final Pattern ISO = Pattern.compile(
"^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:[ T](\\d{1,2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,6}))?)?)?$");
private static final int TWO_DIGIT_YEAR_PIVOT = 70;
private static final int MAX_YEAR = 9999;
private final String spec;
private final Mode mode;
private final Pattern pattern;
private final List<String> groups;
private CopyTemporalFormat(String spec, Mode mode, Pattern pattern, List<String> groups) {
this.spec = spec;
this.mode = mode;
this.pattern = pattern;
this.groups = groups;
}
/**
* What a field is read with when ACCEPTANYDATE names no format: the ISO form of a date, optionally followed
* by a time of day, which is what the default formats and PostgreSQL both read. A value in any other shape
* is the one ACCEPTANYDATE turns into NULL.
*/
static CopyTemporalFormat defaultIso() {
return new CopyTemporalFormat("YYYY-MM-DD[ HH:MI:SS]", Mode.ISO, ISO, List.of());
}
/**
* Reads the quoted argument of DATEFORMAT or TIMEFORMAT; null when it is not a format Redshift accepts.
* The keywords {@code auto}, {@code epochsecs} and {@code epochmillisecs} are case-sensitive.
*
* @param time true for TIMEFORMAT, which also accepts the epoch keywords and refuses a time zone part
*/
static CopyTemporalFormat parse(String spec, boolean time) {
if (spec == null || spec.isEmpty()) {
return null;
}
if ("auto".equals(spec)) {
return new CopyTemporalFormat(spec, Mode.AUTO, null, List.of());
}
if (time && "epochsecs".equals(spec)) {
return new CopyTemporalFormat(spec, Mode.EPOCH_SECONDS, null, List.of());
}
if (time && "epochmillisecs".equals(spec)) {
return new CopyTemporalFormat(spec, Mode.EPOCH_MILLISECONDS, null, List.of());
}
return compile(spec);
}
/** One element of a format string: a token, or a separator character. */
private record Part(String token, char separator) {
boolean isToken() {
return token != null;
}
boolean isNumeric() {
return token != null && !"MON".equals(token) && !"AM".equals(token) && !"PM".equals(token);
}
}
private static CopyTemporalFormat compile(String spec) {
List<Part> parts = new ArrayList<>();
int position = 0;
while (position < spec.length()) {
String token = tokenAt(spec, position);
if (token != null) {
parts.add(new Part(token, '\0'));
position += token.length();
continue;
}
char c = spec.charAt(position);
if (Character.isLetterOrDigit(c)) {
return null;
}
parts.add(new Part(null, c));
position++;
}
if (!partsAreConsistent(parts)) {
return null;
}
StringBuilder regex = new StringBuilder("^");
List<String> groups = new ArrayList<>();
for (int i = 0; i < parts.size(); i++) {
Part part = parts.get(i);
if (!part.isToken()) {
regex.append(Pattern.quote(String.valueOf(part.separator())));
continue;
}
// Numeric tokens with nothing between them cannot be told apart by a variable width.
boolean adjacent = part.isNumeric() && ((i > 0 && parts.get(i - 1).isNumeric())
|| (i + 1 < parts.size() && parts.get(i + 1).isNumeric()));
regex.append(regexFor(part.token(), adjacent));
groups.add(part.token());
if ("SS".equals(part.token())) {
groups.add("FRACTION");
}
}
return new CopyTemporalFormat(spec, Mode.PATTERN, Pattern.compile(regex.append('$').toString()), groups);
}
/**
* A part of a date or time may be named once, a 12-hour clock needs its meridian, and a meridian needs an
* hour: anything else is a format whose value would be read ambiguously.
*/
private static boolean partsAreConsistent(List<Part> parts) {
Set<String> seen = new HashSet<>();
boolean twelveHour = false;
for (Part part : parts) {
if (!part.isToken()) {
continue;
}
if (!seen.add(category(part.token()))) {
return false;
}
twelveHour |= "HH12".equals(part.token());
}
boolean meridian = seen.contains("meridian");
return !seen.isEmpty() && (!twelveHour || meridian) && (!meridian || seen.contains("hour"));
}
private static String category(String token) {
return switch (token) {
case "YYYY", "YY" -> "year";
case "MM", "MON" -> "month";
case "DD" -> "day";
case "HH", "HH24", "HH12" -> "hour";
case "MI" -> "minute";
case "SS" -> "second";
default -> "meridian";
};
}
private static String tokenAt(String spec, int position) {
for (String token : TOKENS) {
if (spec.regionMatches(true, position, token, 0, token.length())) {
return token;
}
}
return null;
}
private static String regexFor(String token, boolean exactWidth) {
String twoDigits = exactWidth ? "(\\d{2})" : "(\\d{1,2})";
return switch (token) {
case "YYYY" -> "(\\d{4})";
case "YY" -> "(\\d{2})";
case "MON" -> "([A-Za-z]{3,9})";
case "SS" -> twoDigits + "(?:\\.(\\d{1,6}))?";
case "AM", "PM" -> "([AaPp][Mm])";
default -> twoDigits;
};
}
String spec() {
return spec;
}
/** False for {@code 'auto'}, which leaves every value to PostgreSQL. */
boolean converts() {
return mode != Mode.AUTO;
}
/** Text PostgreSQL reads as a date: the value converted to {@code YYYY-MM-DD}, any time of day dropped. */
String toDate(String value) {
if (mode == Mode.AUTO) {
return value;
}
return parseValue(value).toLocalDate().toString();
}
/** Text PostgreSQL reads as a timestamp; a format without a time of day gives midnight. */
String toTimestamp(String value) {
if (mode == Mode.AUTO) {
return value;
}
LocalDateTime parsed = parseValue(value);
String text = parsed.toLocalDate() + " " + parsed.toLocalTime();
return parsed.getSecond() == 0 && parsed.getNano() == 0 ? text + ":00" : text;
}
private LocalDateTime parseValue(String value) {
String text = value.trim();
return switch (mode) {
case EPOCH_SECONDS -> epoch(text, false);
case EPOCH_MILLISECONDS -> epoch(text, true);
case ISO -> parseIso(text);
default -> parsePattern(text);
};
}
private LocalDateTime epoch(String text, boolean milliseconds) {
if (!EPOCH.matcher(text).matches()) {
throw invalid(text);
}
try {
long amount = Long.parseLong(text);
Instant instant = milliseconds ? Instant.ofEpochMilli(amount) : Instant.ofEpochSecond(amount);
LocalDateTime parsed = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
if (parsed.getYear() < 1 || parsed.getYear() > MAX_YEAR) {
throw invalid(text);
}
return parsed;
} catch (NumberFormatException | DateTimeException e) {
throw invalid(text);
}
}
private LocalDateTime parseIso(String text) {
Matcher matcher = pattern.matcher(text);
if (!matcher.matches()) {
throw invalid(text);
}
try {
int year = Integer.parseInt(matcher.group(1));
if (year < 1 || year > MAX_YEAR) {
throw invalid(text);
}
LocalDate date = LocalDate.of(year, Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3)));
int hour = matcher.group(4) == null ? 0 : Integer.parseInt(matcher.group(4));
int minute = matcher.group(5) == null ? 0 : Integer.parseInt(matcher.group(5));
int second = matcher.group(6) == null ? 0 : Integer.parseInt(matcher.group(6));
int nanos = matcher.group(7) == null ? 0 : fractionToNanos(matcher.group(7));
return LocalDateTime.of(date, LocalTime.of(hour, minute, second, nanos));
} catch (DateTimeException e) {
throw invalid(text);
}
}
private LocalDateTime parsePattern(String text) {
Matcher matcher = pattern.matcher(text);
if (!matcher.matches()) {
throw invalid(text);
}
int year = 1970;
int month = 1;
int day = 1;
int hour = 0;
int minute = 0;
int second = 0;
int nanos = 0;
boolean twelveHour = false;
String meridian = null;
int group = 1;
try {
for (String token : groups) {
String captured = matcher.group(group++);
switch (token) {
case "YYYY" -> year = Integer.parseInt(captured);
case "YY" -> {
int shortYear = Integer.parseInt(captured);
year = shortYear < TWO_DIGIT_YEAR_PIVOT ? 2000 + shortYear : 1900 + shortYear;
}
case "MM" -> month = Integer.parseInt(captured);
case "MON" -> month = monthNumber(captured, text);
case "DD" -> day = Integer.parseInt(captured);
case "HH", "HH24" -> hour = Integer.parseInt(captured);
case "HH12" -> {
hour = Integer.parseInt(captured);
twelveHour = true;
}
case "MI" -> minute = Integer.parseInt(captured);
case "SS" -> second = Integer.parseInt(captured);
case "FRACTION" -> nanos = captured == null ? 0 : fractionToNanos(captured);
case "AM", "PM" -> meridian = captured.toUpperCase(Locale.ROOT);
default -> throw invalid(text);
}
}
if (year < 1 || year > MAX_YEAR) {
throw invalid(text);
}
hour = applyMeridian(hour, twelveHour, meridian, text);
return LocalDateTime.of(LocalDate.of(year, month, day), LocalTime.of(hour, minute, second, nanos));
} catch (DateTimeException e) {
throw invalid(text);
}
}
private int applyMeridian(int hour, boolean twelveHour, String meridian, String text) {
if (meridian == null && !twelveHour) {
return hour;
}
if (hour < 1 || hour > 12) {
throw invalid(text);
}
boolean pm = "PM".equals(meridian);
return (hour % 12) + (pm ? 12 : 0);
}
private int monthNumber(String name, String text) {
String lower = name.toLowerCase(Locale.ROOT);
for (Month month : Month.values()) {
String full = month.name().toLowerCase(Locale.ROOT);
if (full.equals(lower) || (lower.length() == 3 && full.startsWith(lower))) {
return month.getValue();
}
}
throw invalid(text);
}
private static int fractionToNanos(String digits) {
String padded = (digits + "000000000").substring(0, 9);
return Integer.parseInt(padded);
}
private IllegalArgumentException invalid(String text) {
return new IllegalArgumentException("'" + text + "' does not match the format '" + spec + "'");
}
}
@@ -20,6 +20,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
@@ -193,7 +194,13 @@ public final class S3CopySimulator {
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, OutputStream backendOut) throws IOException {
streamObjects(input.spec(), discoveredColumns, columnMaxBytes, input.s3(), input.iamService(),
streamCopyInput(input, discoveredColumns, columnMaxBytes, null, backendOut);
}
static void streamCopyInput(CopyInput input, List<String> discoveredColumns,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
OutputStream backendOut) throws IOException {
streamObjects(input.spec(), discoveredColumns, columnMaxBytes, columnKinds, input.s3(), input.iamService(),
input.roleSession(), input.keys(), backendOut);
}
@@ -325,9 +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();
List<String> discoveredColumns = null;
List<Integer> columnMaxBytes = null;
if (discoverForJson || truncate) {
List<CopyRecordTransformer.ColumnKind> columnKinds = null;
if (discoverForJson || truncate || temporal) {
List<ColumnInfo> catalog = discoverColumnInfo(client, backend, spec, txStatus, onStatusChange);
if (catalog == null) {
return true;
@@ -338,6 +347,9 @@ public final class S3CopySimulator {
if (truncate) {
columnMaxBytes = alignMaxBytes(spec, catalog);
}
if (temporal) {
columnKinds = alignKinds(spec, catalog);
}
}
OutputStream backendOut = backend.getOutputStream();
@@ -374,7 +386,7 @@ public final class S3CopySimulator {
// a CopyFail to the backend, whose ErrorResponse/ReadyForQuery is relayed to the client;
// or, if the backend is unreachable, one synthesized ErrorResponse/ReadyForQuery.
try {
streamCopyInput(input, discoveredColumns, columnMaxBytes, backendOut);
streamCopyInput(input, discoveredColumns, columnMaxBytes, columnKinds, backendOut);
writeCopyDone(backendOut);
drainToReadyForQuery(backendDecoder, client, onStatusChange);
} catch (RuntimeException | IOException e) {
@@ -469,7 +481,8 @@ public final class S3CopySimulator {
}
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns,
List<Integer> columnMaxBytes, S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
List<Integer> columnMaxBytes, List<CopyRecordTransformer.ColumnKind> columnKinds,
S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
List<String> keys, OutputStream backendOut) throws IOException {
if (spec.transforms().truncateColumns() && columnMaxBytes == null) {
// Extended Query fixes the statement at Parse time, so there is no catalog round trip to
@@ -478,6 +491,11 @@ 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) {
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);
}
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
if (roleSession != null) {
@@ -506,7 +524,7 @@ public final class S3CopySimulator {
}
InputStream source = in;
if (spec.transforms().any()) {
source = new ByteArrayInputStream(transformObject(spec, columnMaxBytes, in));
source = new ByteArrayInputStream(transformObject(spec, columnMaxBytes, columnKinds, in));
}
int read;
boolean endsWithNewline = false;
@@ -533,6 +551,7 @@ public final class S3CopySimulator {
* its 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;
try {
@@ -546,7 +565,8 @@ public final class S3CopySimulator {
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)", null);
+ "(EMPTYASNULL, BLANKSASNULL, REMOVEQUOTES, ACCEPTINVCHARS, TRUNCATECOLUMNS, "
+ "DATEFORMAT, TIMEFORMAT)", null);
}
int wantedMib = (int) ((total * COPY_TRANSFORM_HEAP_FACTOR) / (1024 * 1024)) + 1;
while (heldMib < wantedMib) {
@@ -558,25 +578,41 @@ public final class S3CopySimulator {
}
buffered.write(chunk, 0, read);
}
return new CopyRecordTransformer(spec, columnMaxBytes).apply(buffered.toByteArray());
return new CopyRecordTransformer(spec, columnMaxBytes, columnKinds).apply(buffered.toByteArray());
} finally {
COPY_TRANSFORM_HEAP_MIB.release(heldMib);
}
}
record ColumnInfo(String name, Integer maxBytes) {
record ColumnInfo(String name, Integer maxBytes, CopyRecordTransformer.ColumnKind kind) {
ColumnInfo(String name, Integer maxBytes) {
this(name, maxBytes, CopyRecordTransformer.ColumnKind.OTHER);
}
}
/** 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);
}
/** Positional kind per COPY column; a name the table does not have counts as an ordinary column. */
static List<CopyRecordTransformer.ColumnKind> alignKinds(CopyStatementParser.S3CopyFrom spec,
List<ColumnInfo> catalog) {
return align(spec, catalog, ColumnInfo::kind).stream()
.map(kind -> kind == null ? CopyRecordTransformer.ColumnKind.OTHER : kind)
.toList();
}
private static <T> List<T> align(CopyStatementParser.S3CopyFrom spec, List<ColumnInfo> catalog,
Function<ColumnInfo, T> attribute) {
if (spec.columns() == null || spec.columns().isEmpty()) {
return catalog.stream().map(ColumnInfo::maxBytes).toList();
return catalog.stream().map(attribute).toList();
}
Map<String, Integer> byName = new HashMap<>();
Map<String, T> byName = new HashMap<>();
for (ColumnInfo info : catalog) {
byName.put(info.name(), info.maxBytes());
byName.put(info.name(), attribute.apply(info));
}
List<Integer> aligned = new ArrayList<>();
List<T> aligned = new ArrayList<>();
for (String column : spec.columns()) {
String key = column.startsWith("\"") ? unquoteIdentifier(column) : column.toLowerCase(Locale.ROOT);
aligned.add(byName.get(key));
@@ -584,6 +620,17 @@ 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) {
if ("1082".equals(typeOid)) {
return CopyRecordTransformer.ColumnKind.DATE;
}
if ("1114".equals(typeOid)) {
return CopyRecordTransformer.ColumnKind.TIMESTAMP;
}
return CopyRecordTransformer.ColumnKind.OTHER;
}
private static List<String> parseDataRow(byte[] body) {
int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
List<String> values = new ArrayList<>(count);
@@ -607,7 +654,7 @@ public final class S3CopySimulator {
char txStatus, IntConsumer onStatusChange) throws IOException {
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
String query = "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
+ "THEN a.atttypmod - 4 END FROM pg_catalog.pg_attribute a "
+ "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 "
+ "ORDER BY a.attnum";
@@ -627,7 +674,8 @@ public final class S3CopySimulator {
Integer maxBytes = values.size() >= 2 && values.get(1) != null
? Integer.valueOf(values.get(1))
: null;
cols.add(new ColumnInfo(values.get(0), maxBytes));
String typeOid = values.size() >= 3 ? values.get(2) : null;
cols.add(new ColumnInfo(values.get(0), maxBytes, kindOf(typeOid)));
}
} else if (type == 'E') {
forward(client, msg);
@@ -8,6 +8,7 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CopyRecordTransformerTest {
@@ -26,6 +27,130 @@ class CopyRecordTransformerTest {
return new String(out, StandardCharsets.UTF_8);
}
private static final List<CopyRecordTransformer.ColumnKind> KINDS = List.of(
CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.DATE,
CopyRecordTransformer.ColumnKind.TIMESTAMP);
private static CopyStatementParser.CopyTransforms temporal(String dateFormat, String timeFormat, boolean any) {
CopyTemporalFormat date = dateFormat != null ? CopyTemporalFormat.parse(dateFormat, false)
: (any ? CopyTemporalFormat.defaultIso() : null);
CopyTemporalFormat time = timeFormat != null ? CopyTemporalFormat.parse(timeFormat, true)
: (any ? CopyTemporalFormat.defaultIso() : null);
return new CopyStatementParser.CopyTransforms(false, false, false, false, null, date, time, any);
}
private static String applyTemporal(boolean csv, CopyStatementParser.CopyTransforms transforms, String input) {
return applyTemporal(csv ? "," : "|", csv, transforms, input);
}
private static String applyTemporal(String delimiter, boolean csv,
CopyStatementParser.CopyTransforms transforms, String input) {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "k", delimiter, 0, false, csv, null, null, false, false, false, transforms);
return new String(new CopyRecordTransformer(spec, null, KINDS).apply(input.getBytes(StandardCharsets.UTF_8)),
StandardCharsets.UTF_8);
}
@Test
void dateAndTimestampColumnsAreRewrittenAndOthersLeftAlone() {
assertEquals("03/31/2003|2003-03-31|2003-03-31 18:45:05\n",
applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY HH:MI:SS", false),
"03/31/2003|03/31/2003|03/31/2003 18:45:05\n"));
}
@Test
void aFormatOnlyAppliesToItsOwnKindOfColumn() {
assertEquals("a|2003-03-31|03/31/2003 18:45:05\n",
applyTemporal(false, temporal("YYYY-MM-DD", null, false), "a|2003-03-31|03/31/2003 18:45:05\n"));
}
@Test
void nullMarkersAreNotConverted() {
assertEquals("1|\\N|\\N\n",
applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", false), "1|\\N|\\N\n"));
}
@Test
void emptyTemporalFieldsWithoutAcceptAnyDateFailTheCopy() {
assertThrows(S3CopySimulator.S3TransferException.class,
() -> applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", false), "1|03/31/2003|\n"));
assertThrows(S3CopySimulator.S3TransferException.class,
() -> applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", false), "1||03/31/2003 12:00:00\n"));
}
@Test
void acceptAnyDateLoadsEmptyDateAndTimestampAsNull() {
assertEquals("1|\\N|\\N\n",
applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", true), "1||\n"));
assertEquals("1,,\n",
applyTemporal(true, temporal("MM/DD/YYYY", "MM/DD/YYYY", true), "1,\"\",\n"));
}
@Test
void convertedDatesContainingTheDelimiterAreEscapedInTextMode() {
assertEquals("a-2020\\-01\\-02-c\n",
applyTemporal("-", false, temporal("YYYYMMDD", null, false), "a-20200102-c\n"));
assertEquals("a:b:2020-01-02 12\\:30\\:00\n",
applyTemporal(":", false, temporal(null, "YYYYMMDD HHMISS", false), "a:b:20200102 123000\n"));
assertEquals("a 2003-03-31 2023-11-14\\ 22:13:20\n",
applyTemporal(" ", false, temporal("YYYY-MM-DD", "epochsecs", false), "a 2003-03-31 1700000000\n"));
}
@Test
void convertedDatesContainingTheDelimiterAreQuotedInCsvMode() {
assertEquals("a-\"2020-01-02\"-c\n",
applyTemporal("-", true, temporal("YYYYMMDD", null, false), "a-20200102-c\n"));
assertEquals("a:b:\"2020-01-02 12:30:00\"\n",
applyTemporal(":", true, temporal(null, "YYYYMMDD HHMISS", false), "a:b:20200102 123000\n"));
assertEquals("a 2003-03-31 \"2023-11-14 22:13:20\"\n",
applyTemporal(" ", true, temporal("YYYY-MM-DD", "epochsecs", false), "a 2003-03-31 1700000000\n"));
}
@Test
void yearZeroIsRejectedOrLoadedAsNullWithAcceptAnyDate() {
assertThrows(S3CopySimulator.S3TransferException.class,
() -> applyTemporal(false, temporal("YYYY-MM-DD", null, false), "a|0000-01-01|x\n"));
assertEquals("a|\\N|\\N\n",
applyTemporal(false, temporal("YYYY-MM-DD", "YYYY-MM-DD HH:MI:SS", true),
"a|0000-01-01|0000-01-01 00:00:00\n"));
assertEquals("a|\\N|\\N\n",
applyTemporal(false, temporal(null, null, true),
"a|0000-01-01|0000-01-01 00:00:00\n"));
}
@Test
void aQuotedCsvFieldIsConvertedAndKeepsItsQuotes() {
assertEquals("a,\"2003-03-31\",2003-03-31 00:00:00\n",
applyTemporal(true, temporal("MM/DD/YYYY", "MM/DD/YYYY", false), "a,\"03/31/2003\",03/31/2003\n"));
}
@Test
void aValueThatDoesNotMatchFailsTheCopy() {
S3CopySimulator.S3TransferException failure = assertThrows(S3CopySimulator.S3TransferException.class,
() -> applyTemporal(false, temporal("MM/DD/YYYY", null, false), "a|2003-03-31|x\n"));
assertTrue(failure.getMessage().contains("date"), failure.getMessage());
assertTrue(failure.getMessage().contains("column 2"), failure.getMessage());
}
@Test
void acceptAnyDateLoadsAValueThatDoesNotMatchAsNull() {
assertEquals("a|\\N|\\N\n",
applyTemporal(false, temporal("MM/DD/YYYY", "MM/DD/YYYY", true), "a|00/00/00|2003-03-31 18:45:05\n"));
}
@Test
void acceptAnyDateWithoutAFormatLoadsIsoValuesAndNullsTheRest() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null,
CopyTemporalFormat.defaultIso(), CopyTemporalFormat.defaultIso(), true);
assertEquals("a|2020-01-01|2020-01-01 00:00:00\n",
applyTemporal(false, transforms, "a|2020-01-01|2020-01-01\n"));
assertEquals("a|\\N|\\N\n", applyTemporal(false, transforms, "a|00/00/00|00/00/00 00:00:00\n"));
}
@Test
void emptyAsNullReplacesEmptyTextFields() {
assertEquals("1|\\N|x\n2|b|\\N\n",
@@ -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' DATEFORMAT 'YYYY-MM-DD'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FILLRECORD"));
}
@@ -490,6 +490,46 @@ class CopyStatementParserTest {
"COPY t FROM 's3://b/k' FORMAT AS JSON 'auto' TRUNCATECOLUMNS"));
}
@Test
void copyParsesDateAndTimeFormats() {
CopyStatementParser.CopyTransforms transforms = copyFrom(
"COPY t FROM 's3://b/k' DATEFORMAT AS 'MM/DD/YYYY' TIMEFORMAT 'epochsecs'").transforms();
assertEquals("MM/DD/YYYY", transforms.dateFormat().spec());
assertEquals("epochsecs", transforms.timeFormat().spec());
assertTrue(transforms.temporal());
assertFalse(transforms.acceptAnyDate());
}
@Test
void autoDateFormatsAreAcceptedButConvertNothing() {
CopyStatementParser.CopyTransforms transforms =
copyFrom("COPY t FROM 's3://b/k' DATEFORMAT 'auto' TIMEFORMAT 'auto'").transforms();
assertFalse(transforms.temporal());
assertFalse(transforms.fieldLevel());
}
@Test
void acceptAnyDateFallsBackToTheIsoForm() {
CopyStatementParser.CopyTransforms transforms =
copyFrom("COPY t FROM 's3://b/k' ACCEPTANYDATE").transforms();
assertTrue(transforms.acceptAnyDate());
assertEquals("YYYY-MM-DD[ HH:MI:SS]", transforms.dateFormat().spec());
assertEquals("YYYY-MM-DD[ HH:MI:SS]", transforms.timeFormat().spec());
}
@Test
void copyRejectsInvalidDateFormatOptions() {
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'nonsense'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' TIMEFORMAT 'YYYY-MM-DD HH:MI:SS TZ'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'epochsecs'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'MM/DD/YYYY' DATEFORMAT 'auto'"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' ACCEPTANYDATE ACCEPTANYDATE"));
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'MM/DD/YYYY' FORMAT AS JSON 'auto'"));
}
@Test
void acceptInvCharsDefaultsToQuestionMark() {
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' ACCEPTINVCHARS");
@@ -0,0 +1,155 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CopyTemporalFormatTest {
private static CopyTemporalFormat date(String spec) {
return CopyTemporalFormat.parse(spec, false);
}
private static CopyTemporalFormat time(String spec) {
return CopyTemporalFormat.parse(spec, true);
}
@Test
void theDocumentedDateExamplesConvertToIso() {
assertEquals("2003-03-31", date("MM/DD/YYYY").toDate("03/31/2003"));
assertEquals("2003-03-31", date("MON DD, YYYY").toDate("March 31, 2003"));
assertEquals("1999-01-01", date("MON-DD-YYYY").toDate("Jan-01-1999"));
assertEquals("1999-01-01", date("YYYY-MM-DD").toDate("1999-01-01"));
}
@Test
void theDocumentedTimeExamplesConvertToIso() {
assertEquals("2003-03-31 18:45:05", time("MM.DD.YYYY HH:MI:SS").toTimestamp("03.31.2003 18:45:05"));
assertEquals("2003-03-31 18:45:05.123456",
time("MM.DD.YYYY HH:MI:SS").toTimestamp("03.31.2003 18:45:05.123456"));
}
@Test
void aTwelveHourClockUsesTheMeridian() {
CopyTemporalFormat format = time("YYYY-MM-DD HH12:MI AM");
assertEquals("2003-03-31 18:45:00", format.toTimestamp("2003-03-31 06:45 PM"));
assertEquals("2003-03-31 00:05:00", format.toTimestamp("2003-03-31 12:05 AM"));
assertEquals("2003-03-31 12:05:00", format.toTimestamp("2003-03-31 12:05 PM"));
assertThrows(IllegalArgumentException.class, () -> format.toTimestamp("2003-03-31 13:05 PM"));
}
@Test
void aTimeFormatWithoutATimeOfDayGivesMidnightAndADateFormatDropsTheTime() {
assertEquals("2003-03-31 00:00:00", time("MM/DD/YYYY").toTimestamp("03/31/2003"));
assertEquals("2003-03-31", date("MM/DD/YYYY HH:MI:SS").toDate("03/31/2003 18:45:05"));
}
@Test
void aTwoDigitYearPivotsAtSeventy() {
assertEquals("2069-01-02", date("YY-MM-DD").toDate("69-01-02"));
assertEquals("1970-01-02", date("YY-MM-DD").toDate("70-01-02"));
}
@Test
void tokensAreReadWhateverTheirCase() {
assertEquals("2003-03-31", date("mm/dd/yyyy").toDate("03/31/2003"));
}
@Test
void epochKeywordsConvertInUtc() {
assertEquals("2023-11-14 22:13:20", time("epochsecs").toTimestamp("1700000000"));
assertEquals("2023-11-14 22:13:20.123", time("epochmillisecs").toTimestamp("1700000000123"));
assertThrows(IllegalArgumentException.class, () -> time("epochsecs").toTimestamp("soon"));
}
@Test
void aValueThatDoesNotMatchTheFormatIsRejectedAndNamesTheFormat() {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> date("MM/DD/YYYY").toDate("2003-03-31"));
assertTrue(failure.getMessage().contains("MM/DD/YYYY"), failure.getMessage());
assertThrows(IllegalArgumentException.class, () -> date("YYYY-MM-DD").toDate("2003-02-30"));
assertThrows(IllegalArgumentException.class, () -> date("MON DD, YYYY").toDate("Smarch 31, 2003"));
}
@Test
void autoLeavesEveryValueToPostgres() {
CopyTemporalFormat auto = date("auto");
assertFalse(auto.converts());
assertEquals("J2451187", auto.toDate("J2451187"));
assertEquals("2019-02-11T05:09:12.195Z", time("auto").toTimestamp("2019-02-11T05:09:12.195Z"));
}
@Test
void numericTokensWithNothingBetweenThemNeedExactWidths() {
CopyTemporalFormat compact = date("YYYYMMDD");
assertEquals("2020-01-01", compact.toDate("20200101"));
assertThrows(IllegalArgumentException.class, () -> compact.toDate("2020011"));
assertEquals("2020-01-01 04:08:09", time("YYYYMMDD HHMISS").toTimestamp("20200101 040809"));
}
@Test
void separatedTokensMayBeOneDigit() {
assertEquals("2020-01-02", date("YYYY-MM-DD").toDate("2020-1-2"));
}
@Test
void aRepeatedPartOrAnUnpairedMeridianIsNotParsed() {
assertNull(date("YYYY-YYYY"));
assertNull(date("YYYY-MM-MM"));
assertNull(date("YYYY-MON-MM"));
assertNull(time("YYYY-MM-DD HH:HH24"));
assertNull(time("YYYY-MM-DD HH12:MI"));
assertNull(time("YYYY-MM-DD MI AM"));
assertNotNull(time("YYYY-MM-DD HH:MI AM"));
}
@Test
void anEpochOutsideTheSupportedYearsIsRejected() {
assertThrows(IllegalArgumentException.class, () -> time("epochsecs").toTimestamp("999999999999999"));
assertThrows(IllegalArgumentException.class, () -> time("epochsecs").toTimestamp("-99999999999"));
}
@Test
void yearZeroIsRejectedInIsoAndPattern() {
assertThrows(IllegalArgumentException.class, () -> date("YYYY-MM-DD").toDate("0000-01-01"));
assertThrows(IllegalArgumentException.class, () -> date("YYYYMMDD").toDate("00000101"));
assertThrows(IllegalArgumentException.class, () -> CopyTemporalFormat.defaultIso().toDate("0000-01-01"));
assertThrows(IllegalArgumentException.class,
() -> CopyTemporalFormat.defaultIso().toTimestamp("0000-01-01 00:00:00"));
assertThrows(IllegalArgumentException.class,
() -> time("YYYY-MM-DD HH:MI:SS").toTimestamp("0000-01-01 12:00:00"));
}
@Test
void theIsoFallbackReadsADateWithOrWithoutATimeOfDay() {
CopyTemporalFormat iso = CopyTemporalFormat.defaultIso();
assertEquals("2020-01-01 00:00:00", iso.toTimestamp("2020-01-01"));
assertEquals("2020-01-01 10:00:00", iso.toTimestamp("2020-01-01T10:00"));
assertEquals("2020-01-01 10:00:05.500", iso.toTimestamp("2020-01-01 10:00:05.5"));
assertEquals("2020-01-01", iso.toDate("2020-01-01 10:00:05"));
assertThrows(IllegalArgumentException.class, () -> iso.toDate("00/00/00"));
assertThrows(IllegalArgumentException.class, () -> iso.toDate("2020-02-30"));
}
@Test
void formatsRedshiftRefusesAreNotParsed() {
assertNull(date(""));
assertNull(date("foo"));
assertNull(date("AUTO"));
assertNull(date("epochsecs"));
assertNull(time("YYYY-MM-DD HH:MI:SS TZ"));
assertNull(time("YYYY-MM-DD HH:MI:SSOF"));
assertNull(date("YYYY2MM"));
assertNotNull(time("epochmillisecs"));
assertNotNull(date("YYYY-MM-DD"));
}
}
@@ -1631,6 +1631,51 @@ class S3CopySimulatorTest {
assertEquals(Arrays.asList(null, 3, 5), S3CopySimulator.alignMaxBytes(all, catalog));
}
@Test
void alignKinds_followsExplicitColumnListAndTreatsUnknownNamesAsOrdinary() {
List<S3CopySimulator.ColumnInfo> catalog = List.of(
new S3CopySimulator.ColumnInfo("id", null, CopyRecordTransformer.ColumnKind.OTHER),
new S3CopySimulator.ColumnInfo("born", null, CopyRecordTransformer.ColumnKind.DATE),
new S3CopySimulator.ColumnInfo("Seen", null, CopyRecordTransformer.ColumnKind.TIMESTAMP));
CopyStatementParser.S3CopyFrom explicit = new CopyStatementParser.S3CopyFrom(
"t", List.of("SEEN", "missing", "\"Seen\"", "born"), "wh", "k", "|", 0, false, false, null, null);
assertEquals(List.of(CopyRecordTransformer.ColumnKind.OTHER, CopyRecordTransformer.ColumnKind.OTHER,
CopyRecordTransformer.ColumnKind.TIMESTAMP, CopyRecordTransformer.ColumnKind.DATE),
S3CopySimulator.alignKinds(explicit, catalog));
}
@Test
void streamCopyInput_rewritesDatesWithTheColumnKindsOfTheCatalog() throws Exception {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, CopyTemporalFormat.parse("MM/DD/YYYY", false), null, false);
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|03/31/2003\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.DATE), out);
assertEquals("1|2003-03-31\n", copyDataPayload(out.toByteArray()));
}
@Test
void streamCopyInput_withDateFormatsAndNoCatalogFailsAndNamesSimpleQueryMode() {
CopyStatementParser.CopyTransforms transforms = new CopyStatementParser.CopyTransforms(
false, false, false, false, null, CopyTemporalFormat.parse("MM/DD/YYYY", false), null, false);
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_withTruncateColumnsAndNoCatalogFailsAndNamesSimpleQueryMode() {
CopyStatementParser.CopyTransforms transforms =