feat(redshift): add COPY JOB create, list, show, alter and drop (#7465)

A job stores the parameters of a COPY from S3 in the cluster database, and sys_copy_job lists it with AWS's columns. The checks AWS documents are made when the job is created: an S3 source, an explicit IAM_ROLE, no manifest, access keys, MAXERROR or IGNOREALLERRORS, no hyphen in the name, no transaction block, at most 200 jobs. COPY JOB RUN is refused until files can be loaded automatically.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-05 15:11:51 -04:00
1 parent e9378bb71a
commit de71d91d8c
19 files changed
+1092 -35

No files matched your search

@@ -24,6 +24,14 @@ public final class PostgresWire {
private PostgresWire() {
}
/**
* An escape-string literal, so it reads the same whatever standard_conforming_strings says.
* Apostrophes are doubled rather than backslash-escaped, which backslash_quote can forbid.
*/
public static String quoteLiteral(String value) {
return "E'" + value.replace("\\", "\\\\").replace("'", "''") + "'";
}
/** A message after the startup: its type byte and its body, without the length. */
public record Message(byte type, byte[] body) {
}
@@ -1025,7 +1025,7 @@ public class PostgresProtocolHandler {
+ "FROM pg_catalog.pg_db_role_setting s "
+ "JOIN pg_catalog.pg_roles r ON r.oid = s.setrole "
+ "CROSS JOIN LATERAL pg_catalog.unnest(s.setconfig) WITH ORDINALITY AS c(cfg, n) "
+ "WHERE r.rolname = " + quoteLiteral(role) + " AND s.setdatabase IN (0, "
+ "WHERE r.rolname = " + PostgresWire.quoteLiteral(role) + " AND s.setdatabase IN (0, "
+ "(SELECT d.oid FROM pg_catalog.pg_database d WHERE d.datname = pg_catalog.current_database())) "
+ "ORDER BY s.setdatabase = 0 DESC, c.n";
}
@@ -1424,22 +1424,14 @@ public class PostgresProtocolHandler {
sql.append(", ");
}
sql.append("pg_catalog.set_config(")
.append(quoteLiteral(settings.get(i).name()))
.append(PostgresWire.quoteLiteral(settings.get(i).name()))
.append(", ")
.append(quoteLiteral(settings.get(i).value()))
.append(PostgresWire.quoteLiteral(settings.get(i).value()))
.append(", false)");
}
return sql.toString();
}
/**
* An escape-string literal, so it reads the same whatever standard_conforming_strings says.
* Apostrophes are doubled rather than backslash-escaped, which backslash_quote can forbid.
*/
static String quoteLiteral(String value) {
return "E'" + value.replace("\\", "\\\\").replace("'", "''") + "'";
}
/**
* Folds the ParameterStatus messages a statement produced into the buffered startup messages,
* so the client's view of parameters such as {@code session_authorization} and
@@ -79,14 +79,14 @@ public final class RedshiftAuditSql {
}
}
private enum Kind { WORD, IDENTIFIER, STRING, SYMBOL }
public enum Kind { WORD, IDENTIFIER, STRING, SYMBOL, INVALID }
private record Token(String text, int start, int end, Kind kind) {
boolean keyword(String keyword) {
public record Token(String text, int start, int end, Kind kind) {
public boolean keyword(String keyword) {
return kind == Kind.WORD && keyword.equalsIgnoreCase(text);
}
String identifier() {
public String identifier() {
return kind == Kind.IDENTIFIER
? text.substring(1, text.length() - 1).replace("\"\"", "\"") : text.toLowerCase(Locale.ROOT);
}
@@ -245,7 +245,7 @@ public final class RedshiftAuditSql {
return name < tokens.size() ? new Savepoint(operation, tokens.get(name).identifier()) : null;
}
private static List<Token> tokens(String sql) {
public static List<Token> tokens(String sql) {
return tokens(sql, false);
}
@@ -261,7 +261,12 @@ public final class RedshiftAuditSql {
i++;
}
} else if (sql.startsWith("/*", i)) {
i = skipComment(sql, i);
int end = skipComment(sql, i);
if (end < 0) {
tokens.add(new Token(sql.substring(i), i, sql.length(), Kind.INVALID));
break;
}
i = end;
} else {
int start = i;
Kind kind;
@@ -311,7 +316,7 @@ public final class RedshiftAuditSql {
i++;
}
}
return i;
return depth == 0 ? i : -1;
}
private static int skipQuoted(String sql, int start, char quote, boolean escapes) {
@@ -0,0 +1,231 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.Kind;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.Token;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/** Rewrites COPY JOB SQL to the cluster catalog, without executing or validating the stored COPY options. */
public final class CopyJobSql {
private static final String SYS_COPY_JOB = "SELECT * FROM pg_catalog.sys_copy_job";
private CopyJobSql() {
}
/** Identifies job clauses outside strings, quoted identifiers and comments. */
public static boolean matches(String sql) {
return sql != null && RedshiftAuditSql.statements(sql).stream()
.anyMatch(statement -> jobClause(RedshiftAuditSql.tokens(statement)) >= 0);
}
/** CREATE and DROP need a standalone, auto-committed execution, including on the Data API path. */
public static boolean requiresAutoCommit(String sql) {
if (sql == null) {
return false;
}
for (String statement : RedshiftAuditSql.statements(sql)) {
List<Token> tokens = RedshiftAuditSql.tokens(statement);
int job = jobClause(tokens);
if (job >= 0 && job + 1 < tokens.size()
&& (tokens.get(job + 1).keyword("CREATE") || tokens.get(job + 1).keyword("DROP"))) {
return true;
}
}
return false;
}
/** The backend also checks transaction restrictions at execution, since a prepared statement may be reused. */
public static String rewrite(String sql, boolean inTransaction) {
if (sql == null) {
return null;
}
List<String> statements = RedshiftAuditSql.statements(sql);
List<String> rewritten = new ArrayList<>();
boolean changed = false;
for (String statement : statements) {
List<Token> tokens = RedshiftAuditSql.tokens(statement);
int job = jobClause(tokens);
String replacement = job < 0 ? statement
: rewriteStatement(statement, tokens, job, inTransaction || statements.size() > 1);
rewritten.add(replacement);
changed |= !replacement.equals(statement);
}
return changed ? String.join("; ", rewritten.stream().map(String::stripLeading).toList()) : sql;
}
private static int jobClause(List<Token> tokens) {
if (tokens.size() < 3 || !tokens.getFirst().keyword("COPY")) {
return -1;
}
if (tokens.get(1).keyword("JOB") && (tokens.get(2).keyword("LIST") || tokens.get(2).keyword("SHOW")
|| tokens.get(2).keyword("DROP") || tokens.get(2).keyword("ALTER") || tokens.get(2).keyword("RUN"))) {
return 1;
}
for (int i = 2; i + 1 < tokens.size(); i++) {
if (tokens.get(i).keyword("JOB") && tokens.get(i + 1).keyword("CREATE")) {
return i;
}
}
return -1;
}
private static String rewriteStatement(String sql, List<Token> tokens, int job, boolean inTransaction) {
if (tokens.stream().anyMatch(token -> token.kind() == Kind.INVALID)) {
return reject("42601", "Unterminated comment in COPY JOB statement");
}
if (job > 1) {
return create(sql, tokens, job, inTransaction);
}
String verb = tokens.get(2).text().toUpperCase(Locale.ROOT);
List<Token> arguments = tokens.subList(3, tokens.size());
boolean hasName = !arguments.isEmpty() && isName(arguments.getFirst());
return switch (verb) {
case "LIST" -> arguments.isEmpty() ? SYS_COPY_JOB + " ORDER BY job_id"
: reject("42601", "COPY JOB LIST takes no arguments");
case "SHOW" -> hasName && arguments.size() == 1
? SYS_COPY_JOB + " WHERE job_name = " + PostgresWire.quoteLiteral(arguments.getFirst().identifier())
: reject("42601", "COPY JOB SHOW needs a job name");
case "DROP" -> {
if (!hasName || arguments.size() != 1) {
yield reject("42601", "COPY JOB DROP needs a job name");
}
yield inTransaction ? reject("25001", "COPY JOB DROP cannot run inside a transaction block")
: "CALL floci_internal.drop_copy_job("
+ PostgresWire.quoteLiteral(arguments.getFirst().identifier()) + ")";
}
case "ALTER" -> hasName && arguments.size() == 3 && arguments.get(1).keyword("AUTO")
&& isAutoValue(arguments.get(2))
? "CALL floci_internal.alter_copy_job(" + PostgresWire.quoteLiteral(arguments.getFirst().identifier())
+ ", " + arguments.get(2).keyword("ON") + ")"
: reject("42601", "COPY JOB ALTER needs a job name and AUTO ON or AUTO OFF");
case "RUN" -> reject("0A000", "COPY JOB RUN is not supported");
default -> reject("42601", "Unknown COPY JOB command");
};
}
private static String create(String sql, List<Token> tokens, int job, boolean inTransaction) {
if (inTransaction) {
return reject("25001", "COPY JOB CREATE cannot run inside a transaction block");
}
List<Token> arguments = tokens.subList(job + 2, tokens.size());
if (arguments.isEmpty() || !isName(arguments.getFirst())
|| !(arguments.size() == 1 || arguments.size() == 3 && arguments.get(1).keyword("AUTO")
&& isAutoValue(arguments.get(2)))) {
return reject("42601", "COPY JOB CREATE needs a job name and optional AUTO ON or AUTO OFF");
}
String name = arguments.getFirst().identifier();
if (name.indexOf('-') >= 0) {
return reject("42602", "A copy job name cannot contain a hyphen");
}
if (name.getBytes(StandardCharsets.UTF_8).length > 127) {
return reject("42602", "A copy job name cannot exceed 127 bytes");
}
int from = 2;
while (from < job && !tokens.get(from).keyword("FROM")) {
from++;
}
if (from + 1 >= job || tokens.get(from + 1).kind() != Kind.STRING) {
return reject("0A000", "A copy job needs a COPY from an Amazon S3 location");
}
String table = targetTable(sql, tokens, from);
if (table == null) {
return reject("42601", "Invalid COPY target table or column list");
}
String source = stringValue(tokens.get(from + 1));
if (source == null || !source.startsWith("s3://") || source.length() <= 5) {
return reject("0A000", "A copy job needs a COPY from an Amazon S3 location");
}
String role = null;
for (int i = from + 2; i < job; i++) {
Token token = tokens.get(i);
if (token.keyword("MAXERROR") || token.keyword("IGNOREALLERRORS")) {
return reject("0A000", "A copy job cannot use MAXERROR or IGNOREALLERRORS");
}
if (token.keyword("MANIFEST")) {
return reject("0A000", "A copy job cannot use a manifest");
}
if (token.keyword("CREDENTIALS") || token.keyword("ACCESS_KEY_ID")
|| token.keyword("SECRET_ACCESS_KEY") || token.keyword("SESSION_TOKEN")) {
return reject("0A000", "A copy job authorizes with IAM_ROLE, not access keys");
}
if (token.keyword("IAM_ROLE")) {
int value = i + 1;
if (value < job && tokens.get(value).keyword("AS")) {
value++;
}
role = value < job ? stringValue(tokens.get(value)) : null;
}
}
if (role == null || role.isBlank() || "default".equalsIgnoreCase(role)) {
return reject("0A000", "A copy job needs an IAM_ROLE in its COPY command");
}
int slash = source.indexOf('/', 5);
String bucket = slash < 0 ? source.substring(5) : source.substring(5, slash);
String prefix = slash < 0 ? "" : source.substring(slash + 1);
if (bucket.isEmpty()) {
return reject("0A000", "A copy job needs a COPY from an Amazon S3 location");
}
String copy = sql.substring(tokens.getFirst().start(), tokens.get(job).start()).trim();
boolean auto = arguments.size() == 1 || arguments.get(2).keyword("ON");
return "CALL floci_internal.create_copy_job(" + PostgresWire.quoteLiteral(name) + ", "
+ PostgresWire.quoteLiteral(role) + ", " + PostgresWire.quoteLiteral(copy) + ", " + auto + ", "
+ PostgresWire.quoteLiteral(table) + ", " + PostgresWire.quoteLiteral(bucket) + ", "
+ PostgresWire.quoteLiteral(prefix) + ")";
}
private static String targetTable(String sql, List<Token> tokens, int from) {
int index = 1;
if (!isName(tokens.get(index++))) {
return null;
}
while (index < from && ".".equals(tokens.get(index).text())) {
index++;
if (index >= from || !isName(tokens.get(index++))) {
return null;
}
}
int end = index;
if (index < from && "(".equals(tokens.get(index).text())) {
index++;
while (true) {
if (index >= from || !isName(tokens.get(index++))) {
return null;
}
if (index >= from || !",".equals(tokens.get(index).text())) {
break;
}
index++;
}
if (index >= from || !")".equals(tokens.get(index++).text())) {
return null;
}
}
return index == from ? sql.substring(tokens.get(1).start(), tokens.get(end - 1).end()) : null;
}
private static boolean isName(Token token) {
return token.kind() == Kind.IDENTIFIER && token.text().length() > 2
&& token.text().matches("\"(?:[^\"]|\"\")*+\"")
|| token.kind() == Kind.WORD && token.text().matches("[\\p{L}_][\\p{L}\\p{N}_$]*");
}
private static boolean isAutoValue(Token token) {
return token.keyword("ON") || token.keyword("OFF");
}
private static String stringValue(Token token) {
String text = token.text();
return token.kind() == Kind.STRING && text.length() >= 2 && text.startsWith("'") && text.endsWith("'")
? text.substring(1, text.length() - 1).replace("''", "'") : null;
}
private static String reject(String sqlState, String message) {
return "CALL floci_internal.reject_copy_job(" + PostgresWire.quoteLiteral(sqlState) + ", "
+ PostgresWire.quoteLiteral(message) + ")";
}
}
@@ -317,7 +317,7 @@ public class RedshiftInterceptingBridge {
byte[] packet = message.toPacketBytes();
try {
String rewritten = RedshiftSqlInterceptor.rewrite(sql);
String rewritten = rewriteSql(sql);
if (!rewritten.equals(sql)) {
packet = PostgresWireDecoder.encodeQuery(rewritten);
}
@@ -386,7 +386,7 @@ public class RedshiftInterceptingBridge {
rewritten = S3CopySimulator.unloadBackendSql(unload);
} else {
try {
rewritten = RedshiftSqlInterceptor.rewrite(parse.sql());
rewritten = rewriteSql(parse.sql());
} catch (RuntimeException e) {
LOG.warnv("RedshiftSqlInterceptor failed, forwarding original Parse: {0}", e.getMessage());
}
@@ -637,7 +637,16 @@ public class RedshiftInterceptingBridge {
}
}
/** A COPY JOB statement becomes a call on the cluster catalog, then Redshift DDL is made PostgreSQL's. */
private String rewriteSql(String sql) {
String statement = CopyJobSql.rewrite(sql, false);
return RedshiftSqlInterceptor.rewrite(statement);
}
private CopyStatementParser.S3Statement parseS3Statement(String sql) {
if (CopyJobSql.matches(sql)) {
return null;
}
try {
return CopyStatementParser.parse(sql, defaultIamRoleArn);
} catch (RuntimeException e) {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.spectrum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Column;
@@ -176,7 +177,7 @@ public class ExternalMetadataWriter {
}
private static String literal(String value) {
return "'" + (value == null ? "" : value.replace("'", "''")) + "'";
return PostgresWire.quoteLiteral(value == null ? "" : value);
}
private static Map<String, Object> row(Object... values) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Database;
@@ -275,13 +276,9 @@ public class SpectrumQueryPreparation {
private static void requireSchemaOwner(BackendSql backend, String schemaName) {
String body = "BEGIN IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = "
+ sqlLiteral(schemaName) + " AND pg_catalog.pg_has_role(current_user, n.nspowner, 'USAGE')) THEN "
+ PostgresWire.quoteLiteral(schemaName) + " AND pg_catalog.pg_has_role(current_user, n.nspowner, 'USAGE')) THEN "
+ "RAISE EXCEPTION 'Must be owner of external schema' USING ERRCODE = '42501'; END IF; END";
backend.execute("DO " + sqlLiteral(body));
}
private static String sqlLiteral(String value) {
return "'" + value.replace("'", "''") + "'";
backend.execute("DO " + PostgresWire.quoteLiteral(body));
}
private boolean createSchema(ExternalStatement.CreateSchema schema, SpectrumSession session, BackendSql backend) {
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import io.github.hectorvent.floci.services.redshift.proxy.CopyJobSql;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
@@ -519,7 +520,7 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
if (session != null && session.transactionFailed()) {
throw new SQLException("Current transaction is aborted; use COMMIT or ROLLBACK to end it", "25P02");
}
boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find()
boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find() || CopyJobSql.requiresAutoCommit(sql)
|| preparation != null && target.spectrum() != null
&& preparation.handlesDdl(sql, target.spectrum());
if (autoCommit) {
@@ -682,7 +683,7 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
throw new SQLException("External query preparation failed: " + exception.getMessage(), "58030", exception);
}
}
ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
ParsedSql parsed = RedshiftDataSqlParameters.parse(CopyJobSql.rewrite(sql, !autoCommit || !connection.getAutoCommit()));
execution.checkCancellation();
if (!autoCommit) {
connection.setAutoCommit(false);