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

@@ -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();
@@ -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());
}
}
}
@@ -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'"));
}
}
@@ -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");
}
@@ -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("\\\\", "\\"));
}
}
@@ -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());
}
}
@@ -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());
}
}