diff --git a/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java index 28fa758ee9..db816e09e1 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftTest.java @@ -13,6 +13,16 @@ import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest; import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse; import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterResponse; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.Statement; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -59,6 +69,45 @@ public class RedshiftTest { @Test @Order(2) + public void testUnloadOverSimpleQueryWritesToS3() throws Exception { + RedshiftClient client = getClient(); + Cluster cluster = client.describeClusters(DescribeClustersRequest.builder() + .clusterIdentifier("test-cluster") + .build()).clusters().get(0); + String jdbcUrl = "jdbc:postgresql://" + cluster.endpoint().address() + ":" + + cluster.endpoint().port() + "/dev?preferQueryMode=simple"; + + S3Client s3 = TestFixtures.s3Client(); + String bucket = "redshift-unload-compat"; + s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build()); + + try (Connection conn = DriverManager.getConnection(jdbcUrl, "admin", "Password123"); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS unload_src"); + st.execute("CREATE TABLE unload_src (id int, name text)"); + st.execute("INSERT INTO unload_src VALUES (1, 'alice'), (2, 'bob')"); + st.execute("UNLOAD ('select id, name from unload_src order by id') " + + "TO 's3://redshift-unload-compat/out/'"); + } + + ListObjectsV2Response listing = s3.listObjectsV2(ListObjectsV2Request.builder() + .bucket(bucket) + .prefix("out/") + .build()); + assertTrue(listing.keyCount() >= 1, "UNLOAD must write at least one object"); + + StringBuilder all = new StringBuilder(); + listing.contents().stream() + .sorted((a, b) -> a.key().compareTo(b.key())) + .forEach(obj -> all.append(new String( + s3.getObjectAsBytes(GetObjectRequest.builder().bucket(bucket).key(obj.key()).build()) + .asByteArray(), + StandardCharsets.UTF_8))); + assertEquals("1|alice\n2|bob\n", all.toString()); + } + + @Test + @Order(3) public void testDeleteCluster() { RedshiftClient client = getClient(); DeleteClusterResponse res = client.deleteCluster(DeleteClusterRequest.builder() diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 8d632a0085..958877cff3 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -175,11 +175,45 @@ order) through its own S3 service and streams the rows into the backing PostgreS - The rewrite is textual (regex-based). It masks single-quoted string literals first, so `DEFAULT` / `CHECK` string values are safe, but it is **not** comment-aware and does not recognize escape strings (`E'...'`): an apostrophe inside a `--` or `/* */` comment can make the rewrite skip a Redshift clause. That fails safe: the statement then reaches PostgreSQL, which returns its own syntax error, but avoid apostrophes-in-comments in `CREATE TABLE` / `ALTER TABLE`. - A `rewrite` failure or any statement the interceptor does not recognize is forwarded unmodified (fail-open); PostgreSQL then rejects the Redshift-only syntax itself. - Simple Query ('Q') messages larger than 16 MiB bypass the interceptor and stream through verbatim without heap buffering; non-query traffic also streams through with no size limit. -- `UNLOAD (...) TO 's3://...'` is **not** yet emulated (planned). + +### UNLOAD to S3 + +`UNLOAD ('') TO 's3:///' [options]` sent over the +Simple Query protocol runs the select on the backing PostgreSQL container and writes +the result to S3 as one or more objects under ``. + +- Framing defaults to pipe-delimited text; `FORMAT CSV` (or `CSV`) switches to CSV + with a `,` default. `DELIMITER`, `HEADER`, `NULL AS`, and `ADDQUOTES` are honoured + (`ADDQUOTES` and `HEADER` force CSV framing on PostgreSQL 15). +- `PARALLEL ON` (default) names objects `0000_part_00`, + `0001_part_00`, and so on; `PARALLEL OFF` names them `000`, + `001`, and so on. The emulator has a single backend node, so more than one + object appears only when the result exceeds the per-file size. When `HEADER` is + set, the header row is repeated at the top of every object. +- `MAXFILESIZE [AS] [MB|GB]` sets the per-file size; a bare number is bytes. + Each file is buffered in memory, so the default is 6 MiB (real Redshift defaults + to 6.2 GB) and a whole UNLOAD result is capped at 256 MiB; a larger result fails + with a SQL error (54000). A `MAXFILESIZE` above that 256 MiB cap is not + intercepted at all: the statement is forwarded and PostgreSQL reports its own error. +- A zero-row result still writes one object (empty, or the header row alone when + `HEADER` is set). +- `GZIP` compresses each object and appends `.gz` to its key. +- `MANIFEST` writes `manifest` listing every object with its + `content_length`. +- Without `ALLOWOVERWRITE`, a non-empty target prefix fails with SQL error XX000 and the select + does not run. A failed UNLOAD then removes any objects it had already written. With + `ALLOWOVERWRITE` a failed UNLOAD leaves its objects in place (they may have replaced prior data, + so they are not deleted); a `MANIFEST` request that fails this way can leave data objects without + a manifest, and rerunning the same statement overwrites them. +- S3 access is authorized as an unsigned request, like COPY from S3. +- Any other option (`PARQUET`, `ENCRYPTED`, `REGION`, `IAM_ROLE` / `CREDENTIALS`, + `ZSTD`, `EXTENSION`, `CLEANPATH`, `PARTITION`, and so on) is not intercepted; the + statement is forwarded and PostgreSQL reports its own error. +- Extended Query protocol UNLOAD (a JDBC `PreparedStatement`) is not intercepted. ## Out of Scope -- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; UNLOAD to S3 and SUPER/SPECTRUM are not emulated. +- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; SUPER/SPECTRUM are not emulated. - Multi-node clusters: `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container. - Parameter groups apply no real engine settings; values are stored and echoed back only. - Subnet groups, VPC routing, and security groups are metadata only. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java index 215d927975..c051efd71c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/container/RedshiftContainerManager.java @@ -406,7 +406,7 @@ public class RedshiftContainerManager { lastOutput = e.getMessage(); } try { - java.util.concurrent.TimeUnit.SECONDS.sleep(1); + TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted initializing " + description + " in " + containerName, e); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/CopyStatementParser.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/CopyStatementParser.java index 3c990300f1..1fe4cb6eeb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/CopyStatementParser.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/CopyStatementParser.java @@ -6,12 +6,16 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Recognises a Simple Query statement that is an S3 {@code COPY FROM 's3://...'}. - * Any other statement, or a COPY that uses an option this simulator cannot honour, returns - * {@code null} so the bridge falls back to DDL rewriting and PostgreSQL reports its own error. + * Recognises a Simple Query statement that is an S3 {@code COPY
FROM 's3://...'} + * or {@code UNLOAD ('
FROM 's3://bucket/keyOrPrefix'} by reading the S3 object (or every - * object under the prefix, in key order) through {@link S3Service} and streaming it into the - * backing PostgreSQL container over a fabricated {@code COPY
FROM STDIN} exchange. + * Emulates {@code COPY
FROM 's3://bucket/keyOrPrefix'} and + * {@code UNLOAD ('