mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
e9378bb71a
commit
de71d91d8c
19 files changed
+1092
-35
No files matched your search
@@ -294,6 +294,38 @@ UNLOAD ('SELECT * FROM people') TO 's3://my-data/export/' IAM_ROLE default CSV;
|
||||
See AWS's [default IAM role guide](https://docs.aws.amazon.com/redshift/latest/mgmt/default-iam-role.html)
|
||||
and [COPY authorization parameters](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html).
|
||||
|
||||
### COPY JOB
|
||||
|
||||
A job stores the parameters of a COPY from Amazon S3 so that they can be reused:
|
||||
|
||||
```sql
|
||||
COPY public.target_table FROM 's3://my-bucket/staging/'
|
||||
IAM_ROLE 'arn:aws:iam::000000000000:role/Load'
|
||||
JOB CREATE my_copy_job AUTO ON;
|
||||
|
||||
COPY JOB LIST;
|
||||
COPY JOB SHOW my_copy_job;
|
||||
COPY JOB ALTER my_copy_job AUTO OFF;
|
||||
COPY JOB DROP my_copy_job;
|
||||
```
|
||||
|
||||
Jobs live in the cluster database and are listed in `sys_copy_job`, with AWS's columns. `JOB CREATE` and
|
||||
`COPY JOB DROP` are refused inside a transaction block. A job needs an S3 source and an explicit `IAM_ROLE`,
|
||||
and cannot use `MANIFEST`, access keys, `MAXERROR` or `IGNOREALLERRORS`. Names cannot contain a hyphen and
|
||||
must fit in 127 UTF-8 bytes. A database holds at most 200 jobs, including when jobs are created concurrently.
|
||||
Simple Query, Extended Query and the Redshift Data API are supported. Transaction restrictions are checked when a job
|
||||
command executes, including when a prepared statement is reused. Regular users can manage their own jobs
|
||||
and see their own rows in `sys_copy_job`; superusers can see all rows.
|
||||
|
||||
COPY options are stored for execution time, including formats the ordinary COPY simulator does not yet
|
||||
implement. The COPY JOB restrictions above are checked at creation time.
|
||||
|
||||
Jobs only record the COPY for now: nothing loads files automatically, and `COPY JOB RUN` is refused. The
|
||||
SQLSTATEs and messages of the refusals are Floci's own, not captured from AWS.
|
||||
|
||||
See AWS's [COPY JOB](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-JOB.html) and
|
||||
[auto-copy](https://docs.aws.amazon.com/redshift/latest/dg/loading-data-copy-job.html) references.
|
||||
|
||||
### Snapshot copy grants
|
||||
|
||||
- **`KmsKeyId` defaults to an alias ARN.** Floci has no per-account AWS-managed key, so
|
||||
|
||||
@@ -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) {
|
||||
}
|
||||
|
||||
+3
-11
@@ -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) + ")";
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -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
-1
@@ -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) {
|
||||
|
||||
+3
-6
@@ -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) {
|
||||
|
||||
+3
-2
@@ -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);
|
||||
|
||||
@@ -415,6 +415,98 @@ JOIN pg_catalog.pg_namespace n ON n.nspname = c.schema_name
|
||||
CROSS JOIN LATERAL jsonb_array_elements(c.payload->'partitions') t
|
||||
WHERE has_schema_privilege(n.oid, 'USAGE');
|
||||
|
||||
CREATE TABLE IF NOT EXISTS floci_internal.copy_job (
|
||||
job_id bigserial PRIMARY KEY,
|
||||
job_name text NOT NULL UNIQUE,
|
||||
owner name NOT NULL,
|
||||
iam_role text NOT NULL,
|
||||
job_text text NOT NULL,
|
||||
is_auto boolean NOT NULL,
|
||||
target_table text NOT NULL,
|
||||
bucket text NOT NULL,
|
||||
prefix text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.reject_copy_job(sqlstate text, message text)
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION '%', message USING ERRCODE = sqlstate;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.create_copy_job(
|
||||
name text, iam_role text, job_text text, is_auto boolean, target_table text, bucket text, prefix text)
|
||||
LANGUAGE plpgsql SECURITY INVOKER AS $$
|
||||
BEGIN
|
||||
-- PostgreSQL rejects COMMIT inside an explicit transaction, including a saved Parse executed later.
|
||||
-- Keep transaction control outside SECURITY DEFINER and SET clauses, which forbid it unconditionally.
|
||||
COMMIT;
|
||||
CALL floci_internal.insert_copy_job(name, iam_role, job_text, is_auto, target_table, bucket, prefix);
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.insert_copy_job(
|
||||
name text, iam_role text, job_text text, is_auto boolean, target_table text, bucket text, prefix text)
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
BEGIN
|
||||
LOCK TABLE floci_internal.copy_job IN SHARE ROW EXCLUSIVE MODE;
|
||||
IF (SELECT count(*) FROM floci_internal.copy_job) >= 200 THEN
|
||||
RAISE EXCEPTION 'A cluster or workgroup can have at most 200 copy jobs' USING ERRCODE = '54000';
|
||||
END IF;
|
||||
BEGIN
|
||||
INSERT INTO floci_internal.copy_job (job_name, owner, iam_role, job_text, is_auto, target_table, bucket, prefix)
|
||||
VALUES (name, session_user, iam_role, job_text, is_auto, target_table, bucket, prefix);
|
||||
EXCEPTION WHEN unique_violation THEN
|
||||
RAISE EXCEPTION 'Copy job "%" already exists', name USING ERRCODE = '42710';
|
||||
END;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.alter_copy_job(name text, is_auto boolean)
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
BEGIN
|
||||
UPDATE floci_internal.copy_job j SET is_auto = $2
|
||||
WHERE j.job_name = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user));
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'Copy job "%" does not exist', name USING ERRCODE = '42704';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.drop_copy_job(name text)
|
||||
LANGUAGE plpgsql SECURITY INVOKER AS $$
|
||||
BEGIN
|
||||
COMMIT;
|
||||
CALL floci_internal.delete_copy_job(name);
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE PROCEDURE floci_internal.delete_copy_job(name text)
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
||||
BEGIN
|
||||
DELETE FROM floci_internal.copy_job j
|
||||
WHERE j.job_name = $1 AND (j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user));
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'Copy job "%" does not exist', name USING ERRCODE = '42704';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE VIEW pg_catalog.sys_copy_job AS
|
||||
SELECT j.job_id::bigint AS job_id,
|
||||
j.job_name::character(128) AS job_name,
|
||||
j.iam_role::character(128) AS iam_role,
|
||||
left(j.job_text, 256)::character(256) AS job_text,
|
||||
CASE WHEN j.is_auto THEN 1 ELSE 0 END::integer AS is_auto,
|
||||
0::integer AS on_error_suspend
|
||||
FROM floci_internal.copy_job j
|
||||
WHERE j.owner = session_user OR (SELECT rolsuper FROM pg_roles WHERE rolname = session_user);
|
||||
|
||||
GRANT USAGE ON SCHEMA pg_catalog TO PUBLIC;
|
||||
GRANT USAGE ON SCHEMA floci_internal TO PUBLIC;
|
||||
-- Schema access for COPY JOB must not expose the unrelated privileged catalog writers.
|
||||
REVOKE EXECUTE ON FUNCTION floci_internal.refresh_external_catalog(text, jsonb) FROM PUBLIC;
|
||||
REVOKE EXECUTE ON FUNCTION floci_internal.purge_external_schema(text) FROM PUBLIC;
|
||||
GRANT ALL ON TABLE pg_catalog.stl_load_errors TO PUBLIC;
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO PUBLIC;
|
||||
@@ -16,6 +16,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class PostgresWireTest {
|
||||
|
||||
@Test
|
||||
void quoteLiteralUsesEscapeStringsAndPreservesText() {
|
||||
assertEquals("E''", PostgresWire.quoteLiteral(""));
|
||||
assertEquals("E'plain'", PostgresWire.quoteLiteral("plain"));
|
||||
assertEquals("E'it''s a \\\\ path'", PostgresWire.quoteLiteral("it's a \\ path"));
|
||||
assertEquals("E'\\\\n'", PostgresWire.quoteLiteral("\\n"));
|
||||
assertEquals("E'line\nnext'", PostgresWire.quoteLiteral("line\nnext"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMessageIsFramedWithALengthThatCountsItself() throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.testing.DockerAvailability;
|
||||
import io.github.hectorvent.floci.testing.RedshiftTestCluster;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftCopyJobIntegrationTest {
|
||||
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/LoadRole";
|
||||
private static final String COPY = "COPY public.events FROM 's3://copy-job-bucket/staging/' IAM_ROLE '" + ROLE + "'";
|
||||
|
||||
@Inject
|
||||
RedshiftService service;
|
||||
|
||||
private RedshiftTestCluster cluster;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift copy job tests");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
if (cluster != null) {
|
||||
cluster.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"simple", "extended"})
|
||||
void createListShowAlterAndDropACopyJob(String mode) throws Exception {
|
||||
cluster = RedshiftTestCluster.create(service, "copy-job");
|
||||
|
||||
try (Connection connection = cluster.connect(RedshiftTestCluster.MASTER_USER, mode);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE public.events (id integer)");
|
||||
statement.execute(COPY + " JOB CREATE my_copy_job AUTO ON");
|
||||
|
||||
try (ResultSet rows = statement.executeQuery("COPY JOB LIST")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("my_copy_job", rows.getString("job_name").trim());
|
||||
assertEquals(ROLE, rows.getString("iam_role").trim());
|
||||
assertEquals(1, rows.getInt("is_auto"));
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
|
||||
statement.execute("COPY JOB ALTER my_copy_job AUTO OFF");
|
||||
try (ResultSet rows = statement.executeQuery("COPY JOB SHOW my_copy_job")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(0, rows.getInt("is_auto"));
|
||||
}
|
||||
try (ResultSet rows = statement.executeQuery("SELECT job_name FROM sys_copy_job")) {
|
||||
assertTrue(rows.next());
|
||||
}
|
||||
|
||||
statement.execute("CREATE USER job_owner PASSWORD 'Secret123'");
|
||||
statement.execute("GRANT USAGE ON SCHEMA public TO job_owner");
|
||||
statement.execute("GRANT INSERT ON public.events TO job_owner");
|
||||
try (Connection user = cluster.connect("job_owner", mode);
|
||||
Statement userStatement = user.createStatement()) {
|
||||
userStatement.execute(COPY + " JOB CREATE user_job");
|
||||
try (ResultSet rows = userStatement.executeQuery("COPY JOB LIST")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("user_job", rows.getString("job_name").trim());
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
userStatement.execute("COPY JOB ALTER user_job AUTO OFF");
|
||||
userStatement.execute("COPY JOB DROP user_job");
|
||||
}
|
||||
|
||||
SQLException duplicate = assertThrows(SQLException.class,
|
||||
() -> statement.execute(COPY + " JOB CREATE my_copy_job"));
|
||||
assertEquals("42710", duplicate.getSQLState());
|
||||
SQLException tolerant = assertThrows(SQLException.class,
|
||||
() -> statement.execute(COPY + " MAXERROR 5 JOB CREATE other_job"));
|
||||
assertEquals("0A000", tolerant.getSQLState());
|
||||
|
||||
statement.execute("COPY JOB DROP my_copy_job");
|
||||
try (ResultSet rows = statement.executeQuery("COPY JOB LIST")) {
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
SQLException missing = assertThrows(SQLException.class,
|
||||
() -> statement.execute("COPY JOB DROP my_copy_job"));
|
||||
assertEquals("42704", missing.getSQLState());
|
||||
}
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.testing.DockerAvailability;
|
||||
import io.github.hectorvent.floci.testing.RedshiftTestCluster;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.postgresql.PGStatement;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Runs the real catalog on a cluster's PostgreSQL, so it needs a Docker daemon. */
|
||||
@QuarkusTest
|
||||
class CopyJobCatalogTest {
|
||||
private static final String COPY = "COPY public.events FROM 's3://bucket/prefix/' IAM_ROLE 'load-role'";
|
||||
private static final String READER = "copy_job_reader";
|
||||
private static RedshiftTestCluster cluster;
|
||||
|
||||
@Inject
|
||||
RedshiftService service;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift copy job tests");
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void startClusterAndReset() throws SQLException {
|
||||
if (cluster == null) {
|
||||
cluster = RedshiftTestCluster.create(service, "copy-job-catalog");
|
||||
try (Connection connection = open(RedshiftTestCluster.MASTER_USER);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE public.events (id integer)");
|
||||
statement.execute("CREATE USER " + READER + " PASSWORD '" + RedshiftTestCluster.PASSWORD + "'");
|
||||
statement.execute("GRANT USAGE ON SCHEMA public TO " + READER);
|
||||
statement.execute("GRANT INSERT ON public.events TO " + READER);
|
||||
}
|
||||
}
|
||||
truncateJobs();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopCluster() {
|
||||
if (cluster != null) {
|
||||
cluster.close();
|
||||
cluster = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection open() throws SQLException {
|
||||
return open(RedshiftTestCluster.MASTER_USER);
|
||||
}
|
||||
|
||||
private static Connection open(String user) throws SQLException {
|
||||
return cluster.connect(user);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void truncateJobs() throws SQLException {
|
||||
if (cluster != null) {
|
||||
try (Connection connection = open(); Statement statement = connection.createStatement()) {
|
||||
statement.execute("TRUNCATE floci_internal.copy_job");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryUserCanManageOwnJobsButCannotSeeAnotherUsersJobs() throws SQLException {
|
||||
try (Connection admin = open(); Statement adminStatement = admin.createStatement();
|
||||
Connection user = open(READER);
|
||||
Statement statement = user.createStatement()) {
|
||||
adminStatement.execute(CopyJobSql.rewrite(COPY + " JOB CREATE admin_job", false));
|
||||
statement.execute(CopyJobSql.rewrite(COPY + " JOB CREATE user_job", false));
|
||||
try (ResultSet rows = statement.executeQuery(CopyJobSql.rewrite("COPY JOB LIST", false))) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("user_job", rows.getString("job_name").trim());
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
statement.execute(CopyJobSql.rewrite("COPY JOB ALTER user_job AUTO OFF", false));
|
||||
statement.execute(CopyJobSql.rewrite("COPY JOB DROP user_job", false));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void grantingJobAccessDoesNotExposeExternalCatalogMutation() throws SQLException {
|
||||
try (Connection user = open(READER);
|
||||
Statement statement = user.createStatement()) {
|
||||
for (String sql : new String[]{"SELECT floci_internal.purge_external_schema('other_schema')",
|
||||
"SELECT floci_internal.refresh_external_catalog('other_schema', '{}'::jsonb)"}) {
|
||||
SQLException error = assertThrows(SQLException.class, () -> statement.execute(sql));
|
||||
assertEquals("42501", error.getSQLState());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobNamesAreSafeWhenStandardConformingStringsIsDisabled() throws SQLException {
|
||||
try (Connection connection = open(); Statement statement = connection.createStatement()) {
|
||||
statement.execute("SET standard_conforming_strings = off");
|
||||
statement.execute(CopyJobSql.rewrite(COPY + " JOB CREATE \"slash\\'job\"", false));
|
||||
try (ResultSet rows = statement.executeQuery(CopyJobSql.rewrite("COPY JOB SHOW \"slash\\'job\"", false))) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("slash\\'job", rows.getString("job_name").trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionRestrictionIsCheckedWhenPreparedStatementExecutes() throws SQLException {
|
||||
for (String sql : new String[]{COPY + " JOB CREATE saved_job", "COPY JOB DROP saved_job"}) {
|
||||
try (Connection connection = open();
|
||||
PreparedStatement statement = connection.prepareStatement(CopyJobSql.rewrite(sql, false))) {
|
||||
statement.unwrap(PGStatement.class).setPrepareThreshold(1);
|
||||
statement.execute();
|
||||
if (sql.contains("DROP")) {
|
||||
try (Statement seed = connection.createStatement()) {
|
||||
seed.execute(CopyJobSql.rewrite(COPY + " JOB CREATE saved_job", false));
|
||||
}
|
||||
}
|
||||
connection.setAutoCommit(false);
|
||||
SQLException error = assertThrows(SQLException.class, statement::execute);
|
||||
assertTrue(error.getSQLState().startsWith("2"), error.getMessage());
|
||||
connection.rollback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentCreatesCannotExceedTheJobLimit() throws Exception {
|
||||
try (Connection connection = open(); Statement statement = connection.createStatement()) {
|
||||
statement.execute("INSERT INTO floci_internal.copy_job "
|
||||
+ "(job_name, owner, iam_role, job_text, is_auto, target_table, bucket, prefix) "
|
||||
+ "SELECT 'job_' || i, session_user, 'role', 'COPY', true, 't', 'b', '' "
|
||||
+ "FROM generate_series(1, 199) i");
|
||||
}
|
||||
CountDownLatch created = new CountDownLatch(1);
|
||||
CompletableFuture<Void> second;
|
||||
try (Connection first = open(); Statement statement = first.createStatement()) {
|
||||
first.setAutoCommit(false);
|
||||
// Hold the first insert open so the other session must serialize before counting.
|
||||
statement.execute("LOCK TABLE floci_internal.copy_job IN SHARE ROW EXCLUSIVE MODE");
|
||||
second = CompletableFuture.runAsync(() -> {
|
||||
try (Connection connection = open(); Statement other = connection.createStatement()) {
|
||||
created.countDown();
|
||||
other.execute(CopyJobSql.rewrite(COPY + " JOB CREATE second_job", false));
|
||||
} catch (SQLException error) {
|
||||
assertEquals("54000", error.getSQLState(), error.getMessage());
|
||||
}
|
||||
});
|
||||
assertTrue(created.await(5, TimeUnit.SECONDS));
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).until(() -> {
|
||||
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM pg_stat_activity "
|
||||
+ "WHERE query LIKE '%second_job%' AND wait_event_type = 'Lock'")) {
|
||||
return rows.next() && rows.getInt(1) > 0;
|
||||
}
|
||||
});
|
||||
statement.execute("INSERT INTO floci_internal.copy_job "
|
||||
+ "(job_name, owner, iam_role, job_text, is_auto, target_table, bucket, prefix) "
|
||||
+ "VALUES ('first_job', session_user, 'role', 'COPY', true, 't', 'b', '')");
|
||||
first.commit();
|
||||
}
|
||||
second.get(10, TimeUnit.SECONDS);
|
||||
try (Connection connection = open(); Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery("SELECT count(*) FROM pg_catalog.sys_copy_job")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(200, rows.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
class CopyJobSqlTest {
|
||||
|
||||
private static final String ROLE = "arn:aws:iam::123456789012:role/Load";
|
||||
private static final String COPY = "COPY public.target_table FROM 's3://demo-bucket/staging-folder' IAM_ROLE '"
|
||||
+ ROLE + "'";
|
||||
|
||||
private static String create(String suffix) {
|
||||
return CopyJobSql.rewrite(COPY + " " + suffix, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRegistersTheJobWithTheCopyBucketPrefixAndRole() {
|
||||
String sql = create("JOB CREATE My_Job AUTO ON;");
|
||||
|
||||
assertThat(sql, startsWith("CALL floci_internal.create_copy_job(E'my_job', E'" + ROLE + "', "));
|
||||
assertThat(sql, containsString("E'public.target_table', E'demo-bucket', E'staging-folder')"));
|
||||
assertThat(sql, containsString("', true, E'public.target_table'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDefaultsToAutoOnAndKeepsAutoOff() {
|
||||
assertThat(create("JOB CREATE j"), containsString(", true, E'public.target_table'"));
|
||||
assertThat(create("JOB CREATE j AUTO OFF"), containsString(", false, E'public.target_table'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createKeepsAQuotedNameAsWrittenAndDoublesTheQuotesOfTheCopyText() {
|
||||
String sql = create("JOB CREATE \"Mixed\"");
|
||||
|
||||
assertThat(sql, containsString("create_copy_job(E'Mixed', "));
|
||||
assertThat(sql, containsString("IAM_ROLE ''" + ROLE + "''"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createIsRefusedInATransactionBlock() {
|
||||
assertThat(CopyJobSql.rewrite(COPY + " JOB CREATE j", true),
|
||||
containsString("reject_copy_job(E'25001'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRefusesWhatAWorkingJobCannotCarry() {
|
||||
assertThat(create("MAXERROR 5 JOB CREATE j"), containsString("MAXERROR or IGNOREALLERRORS"));
|
||||
assertThat(create("IGNOREALLERRORS JOB CREATE j"), containsString("MAXERROR or IGNOREALLERRORS"));
|
||||
assertThat(CopyJobSql.rewrite("COPY t FROM 's3://b/p' IAM_ROLE '" + ROLE + "' MANIFEST JOB CREATE j", false),
|
||||
containsString("manifest"));
|
||||
assertThat(CopyJobSql.rewrite("COPY t FROM 's3://b/p' CREDENTIALS 'aws_access_key_id=A;"
|
||||
+ "aws_secret_access_key=S' JOB CREATE j", false), containsString("IAM_ROLE"));
|
||||
assertThat(CopyJobSql.rewrite("COPY t FROM 's3://b/p' IAM_ROLE default JOB CREATE j", false),
|
||||
containsString("needs an IAM_ROLE"));
|
||||
assertThat(CopyJobSql.rewrite("COPY t FROM 's3://b/p' JOB CREATE j", false),
|
||||
containsString("needs an IAM_ROLE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRefusesAHyphenInAQuotedName() {
|
||||
assertThat(create("JOB CREATE \"my-job\""), containsString("cannot contain a hyphen"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOptionNamedLikeAToleranceInAPathDoesNotRefuseTheJob() {
|
||||
String sql = CopyJobSql.rewrite("COPY t FROM 's3://b/maxerror/' IAM_ROLE '" + ROLE + "' JOB CREATE j", false);
|
||||
|
||||
assertThat(sql, startsWith("CALL floci_internal.create_copy_job("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAndShowReadTheSystemView() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB LIST;", false),
|
||||
equalTo("SELECT * FROM pg_catalog.sys_copy_job ORDER BY job_id"));
|
||||
assertThat(CopyJobSql.rewrite("copy job show My_Job", false),
|
||||
equalTo("SELECT * FROM pg_catalog.sys_copy_job WHERE job_name = E'my_job'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void showEscapesApostrophesAndBackslashesInQuotedJobNames() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB SHOW \"o'brien\\new\"", false),
|
||||
equalTo("SELECT * FROM pg_catalog.sys_copy_job WHERE job_name = E'o''brien\\\\new'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void alterAndDropCallTheProcedures() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB ALTER j AUTO OFF", false),
|
||||
equalTo("CALL floci_internal.alter_copy_job(E'j', false)"));
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB DROP j", false),
|
||||
equalTo("CALL floci_internal.drop_copy_job(E'j')"));
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB DROP j", true), containsString("reject_copy_job(E'25001'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runIsRefusedUntilItIsSupported() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB RUN j", false), containsString("COPY JOB RUN is not supported"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void statementsThatAreNotJobStatementsAreLeftAlone() {
|
||||
assertThat(CopyJobSql.matches(COPY), equalTo(false));
|
||||
assertThat(CopyJobSql.matches("SELECT 1"), equalTo(false));
|
||||
assertThat(CopyJobSql.matches("COPY JOB LIST"), equalTo(true));
|
||||
assertThat(CopyJobSql.matches(COPY + " JOB CREATE j"), equalTo(true));
|
||||
assertThat(CopyJobSql.rewrite(COPY, false), not(containsString("floci_internal")));
|
||||
assertThat(CopyJobSql.rewrite("SELECT 1", false), equalTo("SELECT 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void targetAndColumnNamesAreNotOptions() {
|
||||
for (String target : new String[]{"public.manifest", "public.\"maxerror\"", "t (credentials)"}) {
|
||||
assertThat(CopyJobSql.rewrite("COPY " + target + " FROM 's3://b/p' IAM_ROLE '" + ROLE
|
||||
+ "' JOB CREATE j", false), startsWith("CALL floci_internal.create_copy_job("));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void storesOptionsThatAreOnlyValidatedWhenTheJobRuns() {
|
||||
assertThat(create("FORMAT AS PARQUET JOB CREATE j"), startsWith("CALL floci_internal.create_copy_job("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commentsAndEscapedIdentifiersAreSupported() {
|
||||
assertThat(CopyJobSql.rewrite("/* jobs */ COPY /* comment */ JOB SHOW \"a\"\"b\"; -- end", false),
|
||||
equalTo("SELECT * FROM pg_catalog.sys_copy_job WHERE job_name = E'a\"b'"));
|
||||
assertThat(CopyJobSql.rewrite(COPY + " /* MAXERROR */ JOB CREATE j -- end", false),
|
||||
startsWith("CALL floci_internal.create_copy_job("));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotedJobCreateTextDoesNotTurnAnOrdinaryCopyIntoAJob() {
|
||||
String sql = "COPY t FROM 's3://b/JOB CREATE j'";
|
||||
assertThat(CopyJobSql.matches(sql), equalTo(false));
|
||||
assertThat(CopyJobSql.rewrite(sql, false), equalTo(sql));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewritesEachStatementWithoutAbsorbingOtherStatementsIntoTheJob() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB LIST; SELECT 1", false),
|
||||
equalTo("SELECT * FROM pg_catalog.sys_copy_job ORDER BY job_id; SELECT 1"));
|
||||
assertThat(CopyJobSql.rewrite(COPY + "; SELECT 1 JOB CREATE j", false),
|
||||
equalTo(COPY + "; SELECT 1 JOB CREATE j"));
|
||||
assertThat(CopyJobSql.rewrite("BEGIN; " + COPY + " JOB CREATE j; COMMIT", false),
|
||||
containsString("reject_copy_job(E'25001'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unterminatedQuotedNamesCannotReferToAnExistingJob() {
|
||||
for (String name : new String[]{"\"jobx", "\"jobx\"\""}) {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB DROP " + name, false),
|
||||
containsString("reject_copy_job(E'42601'"));
|
||||
assertThat(create("JOB CREATE " + name), containsString("reject_copy_job(E'42601'"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unterminatedCommentsCannotExecuteAJobCommand() {
|
||||
assertThat(CopyJobSql.rewrite("COPY JOB DROP j /* unfinished", false),
|
||||
containsString("reject_copy_job(E'42601'"));
|
||||
assertThat(create("JOB CREATE j /* outer /* nested */"),
|
||||
containsString("reject_copy_job(E'42601'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidCopyTargetsAreRejectedBeforeRegisteringAJob() {
|
||||
for (String target : new String[]{"t bogus", "t (a b)", "t (a,)", "t."}) {
|
||||
assertThat(CopyJobSql.rewrite("COPY " + target + " FROM 's3://b/p' IAM_ROLE '" + ROLE
|
||||
+ "' JOB CREATE j", false), containsString("reject_copy_job("));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void jobNameLengthIsLimitedInUtf8Bytes() {
|
||||
assertThat(create("JOB CREATE " + "a".repeat(127)), startsWith("CALL floci_internal.create_copy_job("));
|
||||
assertThat(create("JOB CREATE " + "a".repeat(129)), containsString("reject_copy_job(E'42602'"));
|
||||
assertThat(create("JOB CREATE \"" + "é".repeat(64) + "\""), containsString("reject_copy_job(E'42602'"));
|
||||
assertThat(create("JOB CREATE \"" + "a".repeat(8192) + "\""), containsString("reject_copy_job(E'42602'"));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -145,7 +145,7 @@ class ExternalLifecycleTest {
|
||||
void cascadeUnregistersSchemaWithoutDeletingGlueDatabaseOrTables() {
|
||||
assertTrue(preparation.handlesDdl("DROP SCHEMA lake CASCADE", SESSION));
|
||||
assertTrue(preparation.prepare("DROP SCHEMA lake CASCADE", SESSION, backend));
|
||||
verify(backend).execute("DROP SCHEMA \"lake\" CASCADE; SELECT floci_internal.purge_external_schema('lake')");
|
||||
verify(backend).execute("DROP SCHEMA \"lake\" CASCADE; SELECT floci_internal.purge_external_schema(E'lake')");
|
||||
verify(registry).unbind(SESSION.accountId(), SESSION.clusterKey(), "dev", "lake");
|
||||
verify(materializer).forgetSchema(SESSION.clusterKey(), "dev", "lake");
|
||||
verify(glue, never()).deleteDatabase(anyString());
|
||||
@@ -246,7 +246,7 @@ class ExternalLifecycleTest {
|
||||
void dropsLocalSchemaWhenGlueDatabaseIsAlreadyGone() {
|
||||
when(glue.getTables("analytics")).thenThrow(new AwsException("EntityNotFoundException", "gone", 400));
|
||||
assertTrue(preparation.prepare("DROP SCHEMA IF EXISTS lake", SESSION, backend));
|
||||
verify(backend).execute("DROP SCHEMA IF EXISTS \"lake\" RESTRICT; SELECT floci_internal.purge_external_schema('lake')");
|
||||
verify(backend).execute("DROP SCHEMA IF EXISTS \"lake\" RESTRICT; SELECT floci_internal.purge_external_schema(E'lake')");
|
||||
verify(registry).unbind(SESSION.accountId(), SESSION.clusterKey(), "dev", "lake");
|
||||
verify(materializer).forgetSchema(SESSION.clusterKey(), "dev", "lake");
|
||||
}
|
||||
|
||||
+28
-4
@@ -47,7 +47,7 @@ class ExternalMetadataWriterTest {
|
||||
|
||||
String sql = writer.refreshSql(BINDING, List.of(table), Map.of("events", List.of(partition)));
|
||||
|
||||
assertThat(sql, containsString("SELECT floci_internal.refresh_external_catalog('analytics'"));
|
||||
assertThat(sql, containsString("SELECT floci_internal.refresh_external_catalog(E'analytics'"));
|
||||
assertThat(sql, containsString("IAM_ROLE"));
|
||||
assertThat(sql, containsString("\"location\":\"s3://bucket/o''brien/\""));
|
||||
assertThat(sql, containsString("\"columnname\":\"id\",\"external_type\":\"int\""));
|
||||
@@ -123,10 +123,34 @@ class ExternalMetadataWriterTest {
|
||||
assertEquals("{}", partitionRow.path("serde_parameters").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refreshPreservesBackslashesAndApostrophesInJsonPayload() throws Exception {
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setLocation("s3://bucket/o'brien\\new/");
|
||||
Table table = new Table();
|
||||
table.setName("events");
|
||||
table.setStorageDescriptor(descriptor);
|
||||
|
||||
String sql = writer.refreshSql(BINDING, List.of(table), Map.of());
|
||||
|
||||
assertEquals(descriptor.getLocation(), refreshPayload(sql).path("tables").get(0).path("location").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void purgeEscapesApostrophesAndBackslashes() {
|
||||
assertEquals("SELECT floci_internal.purge_external_schema(E'o''brien\\\\lake')",
|
||||
writer.purgeSql("o'brien\\lake"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void purgePreservesNullAsAnEmptySchemaName() {
|
||||
assertEquals("SELECT floci_internal.purge_external_schema(E'')", writer.purgeSql(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void purgeCallsPrivilegedWriterForOneSchema() {
|
||||
String sql = writer.purgeSql("analytics");
|
||||
assertThat(sql, containsString("SELECT floci_internal.purge_external_schema('analytics')"));
|
||||
assertThat(sql, containsString("SELECT floci_internal.purge_external_schema(E'analytics')"));
|
||||
assertThat(sql.contains("DELETE FROM floci_internal."), equalTo(false));
|
||||
}
|
||||
|
||||
@@ -174,9 +198,9 @@ class ExternalMetadataWriterTest {
|
||||
}
|
||||
|
||||
private JsonNode refreshPayload(String sql) throws Exception {
|
||||
String prefix = "SELECT floci_internal.refresh_external_catalog('analytics', '";
|
||||
String prefix = "SELECT floci_internal.refresh_external_catalog(E'analytics', E'";
|
||||
String payloadEnd = "'::jsonb)";
|
||||
String escapedJson = sql.substring(prefix.length(), sql.lastIndexOf(payloadEnd));
|
||||
return new ObjectMapper().readTree(escapedJson.replace("''", "'"));
|
||||
return new ObjectMapper().readTree(escapedJson.replace("''", "'").replace("\\\\", "\\"));
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
|
||||
import io.github.hectorvent.floci.testing.DockerAvailability;
|
||||
import io.github.hectorvent.floci.testing.RedshiftTestCluster;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.Statement;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Runs COPY JOB statements through the Data API against a cluster's PostgreSQL, so it needs a Docker daemon. */
|
||||
@QuarkusTest
|
||||
class RedshiftDataCopyJobIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
RedshiftService redshift;
|
||||
|
||||
private final ObjectMapper om = new ObjectMapper();
|
||||
private RedshiftTestCluster cluster;
|
||||
private RedshiftDataExecutor executor;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() throws InterruptedException {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift copy job tests");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
if (executor != null) {
|
||||
executor.close();
|
||||
}
|
||||
if (cluster != null) {
|
||||
cluster.close();
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode req(String sql) {
|
||||
ObjectNode request = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
request.put("Sql", sql);
|
||||
request.put("ClusterIdentifier", "wh");
|
||||
request.put("DbUser", RedshiftTestCluster.MASTER_USER);
|
||||
request.put("Database", "dev");
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode idOf(String id) {
|
||||
return om.createObjectNode().put("Id", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyJobLifecycleAndTransactionRestrictionsThroughTheDataApi() throws Exception {
|
||||
cluster = RedshiftTestCluster.create(redshift, "data-api-job");
|
||||
try (Connection connection = cluster.connect(RedshiftTestCluster.MASTER_USER);
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE public.events (id integer)");
|
||||
}
|
||||
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "127.0.0.1", 5439, "dev",
|
||||
RedshiftTestCluster.MASTER_USER, "x",
|
||||
new SpectrumSession("000000000000", "000000000000:wh", "dev", List.of(), false)));
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenAnswer(inv -> cluster.connect(RedshiftTestCluster.MASTER_USER));
|
||||
executor = new RedshiftDataExecutor(2, 100, 1);
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, factory,
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), om, mock(SpectrumQueryPreparation.class),
|
||||
executor, null);
|
||||
|
||||
String copy = "COPY public.events FROM 's3://bucket/prefix' IAM_ROLE 'load-role' JOB CREATE data_api_job";
|
||||
for (String sql : List.of(copy, "COPY JOB SHOW data_api_job", "COPY JOB ALTER data_api_job AUTO OFF")) {
|
||||
String id = service.executeStatement(req(sql), REGION).path("Id").asText();
|
||||
ObjectNode description = service.describeStatement(idOf(id));
|
||||
assertEquals("FINISHED", description.path("Status").asText(), description.toString());
|
||||
}
|
||||
ObjectNode request = req("unused");
|
||||
request.putArray("Sqls").add("COPY JOB DROP data_api_job");
|
||||
String batchId = service.batchExecuteStatement(request, REGION).path("Id").asText();
|
||||
ObjectNode batch = service.describeStatement(idOf(batchId));
|
||||
assertEquals("FAILED", batch.path("Status").asText());
|
||||
assertTrue(batch.path("Error").asText().contains("transaction block"), batch.toString());
|
||||
|
||||
ObjectNode begin = req("BEGIN").put("SessionKeepAliveSeconds", 60);
|
||||
String sessionId = service.executeStatement(begin, REGION).path("SessionId").asText();
|
||||
String dropId = service.executeStatement(req("COPY JOB DROP data_api_job").put("SessionId", sessionId), REGION)
|
||||
.path("Id").asText();
|
||||
ObjectNode drop = service.describeStatement(idOf(dropId));
|
||||
assertEquals("FAILED", drop.path("Status").asText());
|
||||
assertTrue(drop.path("Error").asText().contains("transaction block"), drop.toString());
|
||||
service.executeStatement(req("ROLLBACK").put("SessionId", sessionId), REGION);
|
||||
String id = service.executeStatement(req("COPY JOB DROP data_api_job"), REGION).path("Id").asText();
|
||||
assertEquals("FINISHED", service.describeStatement(idOf(id)).path("Status").asText());
|
||||
}
|
||||
}
|
||||
+17
@@ -16,9 +16,11 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -91,6 +93,21 @@ class RedshiftDataServiceTest {
|
||||
return om.createObjectNode().put("Id", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyJobListAndShowReadTheCatalogThroughTheDataApi() throws SQLException {
|
||||
try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", "");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TABLE pg_catalog.sys_copy_job (job_id bigint, job_name varchar(128))");
|
||||
statement.execute("INSERT INTO pg_catalog.sys_copy_job VALUES (1, 'saved_job')");
|
||||
}
|
||||
for (String sql : List.of("COPY JOB LIST", "COPY JOB SHOW saved_job")) {
|
||||
String id = service.executeStatement(req(sql), REGION).path("Id").asText();
|
||||
assertEquals("FINISHED", service.describeStatement(idOf(id)).path("Status").asText());
|
||||
ObjectNode result = service.getStatementResult(idOf(id));
|
||||
assertEquals("saved_job", result.path("Records").get(0).get(1).path("stringValue").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rolledBackBatchDoesNotExposeChildResults() {
|
||||
ObjectNode request = req("unused");
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftConnections;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
/** A Docker-backed Redshift cluster for tests that need the cluster's own PostgreSQL. */
|
||||
public final class RedshiftTestCluster implements AutoCloseable {
|
||||
|
||||
public static final String MASTER_USER = "admin";
|
||||
public static final String PASSWORD = "Secret123";
|
||||
|
||||
private final RedshiftService service;
|
||||
private final Cluster cluster;
|
||||
|
||||
private RedshiftTestCluster(RedshiftService service, Cluster cluster) {
|
||||
this.service = service;
|
||||
this.cluster = cluster;
|
||||
}
|
||||
|
||||
public static RedshiftTestCluster create(RedshiftService service, String prefix) {
|
||||
String id = prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
return new RedshiftTestCluster(service, service.createCluster(id, "dc2.large", MASTER_USER, PASSWORD));
|
||||
}
|
||||
|
||||
public String jdbcUrl() {
|
||||
return RedshiftConnections.jdbcUrl(cluster);
|
||||
}
|
||||
|
||||
/** Opens a connection as {@code user}, waiting for the cluster to accept connections first. */
|
||||
public Connection connect(String user) throws SQLException {
|
||||
return connect(user, null);
|
||||
}
|
||||
|
||||
/** Opens a connection with the requested query mode, or the driver's default when it is null. */
|
||||
public Connection connect(String user, String queryMode) throws SQLException {
|
||||
String url = jdbcUrl() + (queryMode == null ? "" : "?preferQueryMode=" + queryMode);
|
||||
return RedshiftConnections.waitForConnection(url, user, PASSWORD);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
service.deleteCluster(cluster.getClusterIdentifier());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user