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

@@ -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);