feat(redshift): add the SUPER and VARBYTE types and their functions (#8571)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-16 08:52:44 -04:00
1 parent f0ee5d44a0
commit 4f623d7b50
7 files changed
+526

No files matched your search

@@ -156,6 +156,25 @@ class RedshiftDataOperationsTest {
assertThat(result.records().get(0).get(1).stringValue()).isEqualTo("a");
}
@Test
@DisplayName("SUPER and VARBYTE columns round trip through JSON_PARSE, TO_VARBYTE and their readers")
void superAndVarbyteRoundTrip() throws Exception {
run("CREATE TABLE compat_super (id int, doc SUPER, raw VARBYTE(16))");
run("INSERT INTO compat_super VALUES (1, JSON_PARSE('[10001,10002,\"abc\"]'), TO_VARBYTE('6162', 'hex'))");
String selectId = run("SELECT JSON_SERIALIZE(doc), JSON_TYPEOF(doc), FROM_VARBYTE(raw, 'utf8'), "
+ "CAN_JSON_PARSE('This is a string.') FROM compat_super");
GetStatementResultResponse result = data.getStatementResult(GetStatementResultRequest.builder()
.id(selectId)
.build());
assertThat(result.records()).hasSize(1);
assertThat(result.records().get(0).get(0).stringValue()).isEqualTo("[10001,10002,\"abc\"]");
assertThat(result.records().get(0).get(1).stringValue()).isEqualTo("array");
assertThat(result.records().get(0).get(2).stringValue()).isEqualTo("ab");
assertThat(result.records().get(0).get(3).booleanValue()).isFalse();
}
@Test
@DisplayName("named SQL parameters are bound through the SDK model")
void parameterizedStatementBindsSqlParameters() throws Exception {
+33
View File
@@ -375,6 +375,39 @@ See AWS's [COPY JOB](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-JOB.h
`CreateTags`/`DeleteTags`/`DescribeTags` do not list that fault at all and return
`ResourceNotFoundFault` (HTTP 404) for any missing resource, grants included.
## SUPER and VARBYTE
A cluster's database has the `SUPER` and `VARBYTE` types and the functions that make and read them. `VARBYTE(n)`, `VARBINARY(n)`
and `BINARY VARYING(n)` in `CREATE TABLE` and `ALTER TABLE` are the same type.
| Function | Result |
|---|---|
| `JSON_PARSE(varchar or varbyte)` | The `SUPER` value of a JSON document; an error when it is not JSON. NULL for NULL. |
| `CAN_JSON_PARSE(varchar or varbyte)` | `true` when `JSON_PARSE` takes it, `false` otherwise and for an empty string, NULL for NULL. |
| `JSON_SERIALIZE(super)` | The JSON text of a `SUPER` value, the string `null` for NULL. |
| `JSON_TYPEOF(super)` | `object`, `array`, `string`, `number`, `boolean` or `null`. |
| `FROM_VARBYTE(varbyte, format)` | The string of a binary value in `hex`, `binary`, `utf8` (also `utf-8` and `utf_8`) or `base64`. |
| `TO_VARBYTE(string, format)` | The binary value of a string in one of those formats; an odd number of hexadecimal digits gets a leading `0`. |
```sql
CREATE TABLE events (id INT, doc SUPER, raw VARBYTE(64));
INSERT INTO events VALUES (1, JSON_PARSE('{"a":[1,2]}'), TO_VARBYTE('6162', 'hex'));
SELECT JSON_SERIALIZE(doc), FROM_VARBYTE(raw, 'utf8') FROM events;
```
Floci keeps both as PostgreSQL domains, `varbyte` over `bytea` and `super` over `jsonb`, so some things differ from Amazon Redshift:
- The length of `VARBYTE(n)` is not enforced.
- A `SUPER` object's keys are in `jsonb` order, shorter keys first and then by bytes, not in the order the JSON gave them.
- A `VARBYTE` column read as it is comes back in PostgreSQL's `bytea` form (`\x6162`), not as `6162`. Read it with `FROM_VARBYTE(value, 'hex')`.
- A `VARCHAR` or an integer does not cast to `VARBYTE`: use `TO_VARBYTE`.
- PartiQL navigation into a `SUPER` value (`doc.a[0]`), `JSON_SIZE`, `IS_OBJECT`, `IS_ARRAY` and the other `SUPER` functions are not supported.
- `JSON_TYPEOF` of an untyped literal is ambiguous with PostgreSQL's own `json_typeof`: give it a `JSON_PARSE` result or a `::super` cast.
See AWS's [SUPER type](https://docs.aws.amazon.com/redshift/latest/dg/r_SUPER_type.html),
[VARBYTE type](https://docs.aws.amazon.com/redshift/latest/dg/r_VARBYTE_type.html) and
[JSON_PARSE](https://docs.aws.amazon.com/redshift/latest/dg/JSON_PARSE.html).
## Cross-region snapshot copy
`EnableSnapshotCopy` makes a background sweep (`FLOCI_SERVICES_REDSHIFT_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS`, 60 by default) copy the cluster's snapshots to the destination Region.
@@ -68,6 +68,21 @@ public final class RedshiftSqlInterceptor {
/** {@code ENCODE <codec>} where {@code <codec>} is an actual Redshift column encoding or {@code AUTO}. */
private static final Pattern ENCODE_PATTERN = Pattern.compile(
"(?i)\\bENCODE\\s+(RAW|AZ64|BYTEDICT|DELTA32K|DELTA|LZO|MOSTLY8|MOSTLY16|MOSTLY32|RUNLENGTH|TEXT255|TEXT32K|ZSTD|AUTO)\\b");
/** Whitespace and SQL comments, which may sit between the parts of a column definition. */
private static final String GAP = "(?:\\s|/\\*.*?\\*/|--[^\\n]*(?:\\n|$))";
/**
* {@code VARBYTE(n)}, {@code VARBINARY(n)} and {@code BINARY VARYING(n)}, and the two aliases without a length, as
* the type of a column: the {@code varbyte} domain takes no length, and PostgreSQL has no type of the other names.
* A type is only the word after a column's name, and a column's definition only starts after the {@code (} or
* {@code ,} of a column list or after {@code ADD [COLUMN] [IF NOT EXISTS]}. A column called {@code varbinary}, a
* {@code RENAME COLUMN a TO varbinary} and the like are never in that position. Group 1 is what leads up to the
* type, kept as it is.
*/
private static final Pattern VARBYTE_TYPE_PATTERN = Pattern.compile(
"(?is)((?:[(,]|\\bADD\\s+(?:COLUMN\\s+)?+(?:IF\\s+NOT\\s+EXISTS\\s+)?+)" + GAP + "*(?:\"[^\"]+\"|\\w+)" + GAP + "+)"
+ "(?:VARBYTE|VARBINARY|BINARY\\s+VARYING)(?:\\s*\\(\\s*\\d+\\s*\\))?(?=[\\s,)]|/\\*|--|$)");
/** A table made from a query has no column types to rewrite, only select lists whose aliases could look like one. */
private static final Pattern TABLE_FROM_QUERY_PATTERN = Pattern.compile("(?is)\\bAS\\s*\\(?\\s*(?:SELECT|WITH)\\b");
private static final Pattern DOUBLE_COMMA_PATTERN = Pattern.compile(",(?:\\s*,)+");
private static final Pattern COMMA_CLOSE_PAREN_PATTERN = Pattern.compile(",\\s*\\)");
@@ -113,6 +128,9 @@ public final class RedshiftSqlInterceptor {
s = KEY_COLUMN_CONSTRAINT_PATTERN.matcher(s).replaceAll("");
s = TABLE_LEVEL_KEY_IDENT_PATTERN.matcher(s).replaceAll("");
s = ENCODE_PATTERN.matcher(s).replaceAll("");
if (!TABLE_FROM_QUERY_PATTERN.matcher(s).find()) {
s = VARBYTE_TYPE_PATTERN.matcher(s).replaceAll("$1varbyte");
}
s = DOUBLE_COMMA_PATTERN.matcher(s).replaceAll(",");
s = COMMA_CLOSE_PAREN_PATTERN.matcher(s).replaceAll(")");
return s;
@@ -633,3 +633,127 @@ GRANT USAGE ON SCHEMA floci_internal TO PUBLIC;
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 SELECT ON ALL TABLES IN SCHEMA pg_catalog TO PUBLIC;
-- 18. VARBYTE and SUPER: Redshift's binary and semi-structured types, as domains over bytea and jsonb,
-- with the functions that read and write them. A SUPER value keeps the jsonb order of an object's keys,
-- not the order they were written in.
DO $floci$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'pg_catalog' AND t.typname = 'varbyte') THEN
CREATE DOMAIN pg_catalog.varbyte AS bytea;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'pg_catalog' AND t.typname = 'super') THEN
CREATE DOMAIN pg_catalog.super AS jsonb;
END IF;
END
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.from_varbyte(value pg_catalog.varbyte, format text)
RETURNS text LANGUAGE plpgsql IMMUTABLE STRICT AS $floci$
BEGIN
CASE lower(format)
WHEN 'hex' THEN
RETURN encode(value, 'hex');
WHEN 'binary' THEN
RETURN COALESCE((SELECT string_agg((('x' || lpad(to_hex(get_byte(value, i)), 2, '0'))::bit(8))::text, '' ORDER BY i)
FROM generate_series(0, length(value) - 1) AS i), '');
WHEN 'utf8', 'utf-8', 'utf_8' THEN
RETURN convert_from(value, 'UTF8');
WHEN 'base64' THEN
RETURN replace(encode(value, 'base64'), E'\n', '');
ELSE
RAISE EXCEPTION 'invalid format "%" for FROM_VARBYTE', format USING ERRCODE = '22023';
END CASE;
END
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.to_varbyte(value text, format text)
RETURNS pg_catalog.varbyte LANGUAGE plpgsql IMMUTABLE STRICT AS $floci$
DECLARE
padded text;
result bytea := ''::bytea;
i integer;
BEGIN
CASE lower(format)
WHEN 'hex' THEN
-- An odd number of digits gets a leading 0.
RETURN decode(CASE WHEN length(value) % 2 = 1 THEN '0' || value ELSE value END, 'hex');
WHEN 'binary' THEN
IF value !~ '^[01]*$' THEN
RAISE EXCEPTION 'invalid binary digit in "%"', value USING ERRCODE = '22023';
END IF;
padded := lpad(value, ((length(value) + 7) / 8) * 8, '0');
FOR i IN 0 .. length(padded) / 8 - 1 LOOP
result := result || set_byte('\x00'::bytea, 0, (('b' || substr(padded, i * 8 + 1, 8))::bit(8))::integer);
END LOOP;
RETURN result;
WHEN 'utf8', 'utf-8', 'utf_8' THEN
RETURN convert_to(value, 'UTF8');
WHEN 'base64' THEN
RETURN decode(value, 'base64');
ELSE
RAISE EXCEPTION 'invalid format "%" for TO_VARBYTE', format USING ERRCODE = '22023';
END CASE;
END
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.json_parse(value text)
RETURNS pg_catalog.super LANGUAGE sql IMMUTABLE STRICT AS $floci$
SELECT value::jsonb::pg_catalog.super
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.json_parse(value pg_catalog.varbyte)
RETURNS pg_catalog.super LANGUAGE sql IMMUTABLE STRICT AS $floci$
SELECT convert_from(value, 'UTF8')::jsonb::pg_catalog.super
$floci$;
-- False, not an error, for what JSON_PARSE would refuse, an empty string among it.
CREATE OR REPLACE FUNCTION pg_catalog.can_json_parse(value text)
RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT AS $floci$
BEGIN
PERFORM value::jsonb;
RETURN true;
EXCEPTION WHEN OTHERS THEN
RETURN false;
END
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.can_json_parse(value pg_catalog.varbyte)
RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT AS $floci$
BEGIN
PERFORM convert_from(value, 'UTF8')::jsonb;
RETURN true;
EXCEPTION WHEN OTHERS THEN
RETURN false;
END
$floci$;
-- Compact text, as RFC 8259 allows and Redshift writes it; a null is the JSON string 'null'.
CREATE OR REPLACE FUNCTION pg_catalog.json_serialize(value pg_catalog.super)
RETURNS text LANGUAGE plpgsql IMMUTABLE AS $floci$
DECLARE
doc jsonb := value;
BEGIN
IF doc IS NULL THEN
RETURN 'null';
END IF;
CASE jsonb_typeof(doc)
WHEN 'object' THEN
RETURN '{' || COALESCE((SELECT string_agg(to_jsonb(e.key)::text || ':'
|| pg_catalog.json_serialize(e.value::pg_catalog.super), ',')
FROM jsonb_each(doc) AS e), '') || '}';
WHEN 'array' THEN
RETURN '[' || COALESCE((SELECT string_agg(pg_catalog.json_serialize(e.value::pg_catalog.super), ',' ORDER BY e.ord)
FROM jsonb_array_elements(doc) WITH ORDINALITY AS e(value, ord)), '') || ']';
ELSE
RETURN doc::text;
END CASE;
END
$floci$;
CREATE OR REPLACE FUNCTION pg_catalog.json_typeof(value pg_catalog.super)
RETURNS text LANGUAGE sql IMMUTABLE STRICT AS $floci$
SELECT jsonb_typeof(value)
$floci$;
@@ -0,0 +1,73 @@
package io.floci.aws.services.redshift;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** What the bootstrap script defines, checked without a database; the Docker tests run it. */
class RedshiftBootstrapSqlTest {
private static String bootstrap() throws IOException {
try (InputStream in = RedshiftBootstrapSqlTest.class.getResourceAsStream("/redshift/bootstrap-catalog.sql")) {
assertNotNull(in);
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
@Test
void definesTheVarbyteAndSuperDomainsOnceEach() throws IOException {
String sql = bootstrap();
assertEquals(1, count(sql, "CREATE DOMAIN pg_catalog.varbyte AS bytea;"));
assertEquals(1, count(sql, "CREATE DOMAIN pg_catalog.super AS jsonb;"));
// Run again on a database that has them, so each is created only when absent.
assertTrue(sql.contains("t.typname = 'varbyte') THEN"));
assertTrue(sql.contains("t.typname = 'super') THEN"));
}
@Test
void definesEachVarbyteAndSuperFunctionWithItsArgumentTypes() throws IOException {
String sql = bootstrap();
for (String signature : List.of(
"pg_catalog.from_varbyte(value pg_catalog.varbyte, format text)",
"pg_catalog.to_varbyte(value text, format text)",
"pg_catalog.json_parse(value text)",
"pg_catalog.json_parse(value pg_catalog.varbyte)",
"pg_catalog.can_json_parse(value text)",
"pg_catalog.can_json_parse(value pg_catalog.varbyte)",
"pg_catalog.json_serialize(value pg_catalog.super)",
"pg_catalog.json_typeof(value pg_catalog.super)")) {
assertEquals(1, count(sql, "CREATE OR REPLACE FUNCTION " + signature), signature);
}
}
@Test
void closesEveryDollarQuotedBodyItOpens() throws IOException {
assertEquals(0, count(bootstrap(), "$floci$") % 2);
}
@Test
void putsTheVarbyteAndSuperSectionAfterTheGrantsAndRevokesSoAFailureInItNeverSkipsThem() throws IOException {
String sql = bootstrap();
int section = sql.indexOf("-- 18. VARBYTE and SUPER");
assertTrue(section > sql.lastIndexOf("REVOKE EXECUTE ON FUNCTION"));
assertTrue(section > sql.lastIndexOf("GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO PUBLIC;"));
}
private static int count(String text, String part) {
int count = 0;
for (int at = text.indexOf(part); at >= 0; at = text.indexOf(part, at + part.length())) {
count++;
}
return count;
}
}
@@ -0,0 +1,171 @@
package io.floci.aws.services.redshift;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.testing.DockerAvailability;
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.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import static io.floci.aws.services.redshift.RedshiftConnections.waitForConnection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The VARBYTE and SUPER types and their functions, with the examples of the Amazon Redshift documentation. */
@QuarkusTest
class RedshiftVarbyteSuperIntegrationTest {
@Inject
RedshiftService service;
private String clusterId;
@BeforeAll
static void requireDocker() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(),
"Docker daemon must be available for Redshift integration tests");
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
service.deleteCluster(clusterId);
}
}
private Connection connect() throws Exception {
clusterId = "varbyte-" + UUID.randomUUID().toString().substring(0, 8);
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
return waitForConnection(cluster, "admin", "Secret123");
}
private static boolean bool(Statement statement, String sql) throws SQLException {
try (ResultSet rows = statement.executeQuery(sql)) {
assertTrue(rows.next(), sql);
return rows.getBoolean(1);
}
}
private static String string(Statement statement, String sql) throws SQLException {
try (ResultSet rows = statement.executeQuery(sql)) {
assertTrue(rows.next(), sql);
return rows.getString(1);
}
}
@Test
void fromVarbyteWritesABinaryValueInEachFormat() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertEquals("6162", string(statement, "SELECT FROM_VARBYTE('ab', 'hex')"));
assertEquals("01001101", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('4d', 'hex'), 'binary')"));
assertEquals("a", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('61', 'hex'), 'UTF-8')"));
assertEquals("a", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('61', 'hex'), 'utf8')"));
assertEquals("a", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('61', 'hex'), 'utf_8')"));
assertEquals("YWJj", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('abc', 'utf8'), 'base64')"));
}
}
@Test
void toVarbyteReadsAStringInEachFormat() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertEquals("6162", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('6162', 'hex'), 'hex')"));
assertEquals("4d", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('01001101', 'binary'), 'hex')"));
assertEquals("61", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('a', 'utf8'), 'hex')"));
// An odd number of hexadecimal digits gets a leading 0.
assertEquals("04", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('4', 'hex'), 'hex')"));
assertEquals("abc", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('YWJj', 'base64'), 'utf8')"));
// Fewer than eight bits are the low bits of one byte.
assertEquals("05", string(statement, "SELECT FROM_VARBYTE(TO_VARBYTE('101', 'binary'), 'hex')"));
}
}
@Test
void anUnknownFormatOrADigitThatIsNotBinaryIsRefused() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
SQLException format = assertThrows(SQLException.class,
() -> statement.executeQuery("SELECT TO_VARBYTE('61', 'octal')"));
assertEquals("22023", format.getSQLState());
SQLException digit = assertThrows(SQLException.class,
() -> statement.executeQuery("SELECT TO_VARBYTE('012', 'binary')"));
assertEquals("22023", digit.getSQLState());
}
}
@Test
void jsonParseMakesASuperValueThatJsonSerializeAndJsonTypeofRead() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertEquals("[10001,10002,\"abc\"]",
string(statement, "SELECT JSON_SERIALIZE(JSON_PARSE('[10001,10002,\"abc\"]'))"));
assertEquals("array", string(statement, "SELECT JSON_TYPEOF(JSON_PARSE('[10001,10002,\"abc\"]'))"));
assertEquals("object", string(statement, "SELECT JSON_TYPEOF(JSON_PARSE('{\"a\":1}'))"));
assertEquals("{\"k\":\"a\\\"b\",\"n\":null,\"o\":{\"x\":[1,2.5,true]}}", string(statement,
"SELECT JSON_SERIALIZE(JSON_PARSE('{ \"k\" : \"a\\\"b\", \"n\" : null, \"o\" : {\"x\" : [1, 2.5, true]} }'))"));
assertEquals("{\"a\":1}",
string(statement, "SELECT JSON_SERIALIZE(JSON_PARSE(TO_VARBYTE('{\"a\":1}', 'utf8')))"));
}
}
@Test
void aNullSuperValueSerializesAsTheJsonStringNull() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertEquals("null", string(statement, "SELECT JSON_SERIALIZE(NULL::super)"));
assertNull(string(statement, "SELECT JSON_PARSE(NULL::varchar)"));
}
}
@Test
void jsonParseRefusesWhatIsNotJson() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertThrows(SQLException.class, () -> statement.executeQuery("SELECT JSON_PARSE('This is a string.')"));
}
}
@Test
void canJsonParseTellsWhatJsonParseWouldTake() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
assertTrue(bool(statement, "SELECT CAN_JSON_PARSE('[10001,10002,\"abc\"]')"));
assertFalse(bool(statement, "SELECT CAN_JSON_PARSE('This is a string.')"));
assertFalse(bool(statement, "SELECT CAN_JSON_PARSE('')"));
assertNull(string(statement, "SELECT CAN_JSON_PARSE(NULL::varchar)"));
assertTrue(bool(statement, "SELECT CAN_JSON_PARSE(TO_VARBYTE('{\"a\":1}', 'utf8'))"));
assertFalse(bool(statement, "SELECT CAN_JSON_PARSE(TO_VARBYTE('ff', 'hex'))"));
// The documented use: parse only what can be parsed.
assertEquals("\"This is not JSON.\"", string(statement, "SELECT JSON_SERIALIZE(CASE "
+ "WHEN CAN_JSON_PARSE('This is a string.') THEN JSON_PARSE('This is a string.') "
+ "ELSE JSON_PARSE('\"This is not JSON.\"') END)"));
}
}
@Test
void aTableKeepsSuperAndSizedVarbyteColumns() throws Exception {
try (Connection connection = connect(); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE events (id INT, doc SUPER, raw VARBYTE(16), blob VARBINARY(8)) DISTSTYLE EVEN");
statement.execute("INSERT INTO events VALUES (1, JSON_PARSE('{\"a\":1}'), TO_VARBYTE('ff00', 'hex'), "
+ "TO_VARBYTE('0a', 'hex'))");
statement.execute("INSERT INTO events VALUES (2, JSON_PARSE('[1,2]'), NULL, NULL)");
try (ResultSet rows = statement.executeQuery("SELECT id, JSON_SERIALIZE(doc), FROM_VARBYTE(raw, 'hex'), "
+ "FROM_VARBYTE(blob, 'hex') FROM events ORDER BY id")) {
assertTrue(rows.next());
assertEquals("{\"a\":1}", rows.getString(2));
assertEquals("ff00", rows.getString(3));
assertEquals("0a", rows.getString(4));
assertTrue(rows.next());
assertEquals("[1,2]", rows.getString(2));
assertNull(rows.getString(3));
assertFalse(rows.next());
}
}
}
}
@@ -271,4 +271,92 @@ class RedshiftSqlInterceptorTest {
assertTrue(!rewritten.contains("INTERLEAVED"), "Should not contain INTERLEAVED: " + rewritten);
assertTrue(!rewritten.contains(",\n)"), "Should not contain trailing comma before parenthesis: " + rewritten);
}
@ParameterizedTest
@ValueSource(strings = {"VARBYTE(64)", "varbyte (1024)", "VARBINARY(10)", "BINARY VARYING(16)", "binary varying (16)"})
void shouldTurnASizedBinaryTypeIntoTheVarbyteDomain(String type) {
String rewritten = RedshiftSqlInterceptor.rewrite("CREATE TABLE t (id INT, payload " + type + " NOT NULL);");
assertEquals("CREATE TABLE t (id INT, payload varbyte NOT NULL);", rewritten);
}
@ParameterizedTest
@ValueSource(strings = {"VARBYTE(10)", "VARBYTE", "VARBINARY(10)", "BINARY VARYING(10)"})
void shouldTurnABinaryTypeThatEndsTheStatementIntoTheVarbyteDomain(String type) {
assertEquals("ALTER TABLE t ADD COLUMN x varbyte;",
RedshiftSqlInterceptor.rewrite("ALTER TABLE t ADD COLUMN x " + type + ";"));
assertEquals("ALTER TABLE t ADD COLUMN x varbyte",
RedshiftSqlInterceptor.rewrite("ALTER TABLE t ADD COLUMN x " + type));
}
@Test
void shouldTurnABinaryTypeAfterWideAlignmentIntoTheVarbyteDomain() {
String padding = " ".repeat(40);
assertEquals("CREATE TABLE t (\n payload" + padding + "varbyte\n);",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (\n payload" + padding + "VARBYTE(64)\n);"));
}
@ParameterizedTest
@ValueSource(strings = {
"ALTER TABLE events ADD COLUMN varbinary INT",
"ALTER TABLE events ADD varbinary INT",
"ALTER TABLE events ADD COLUMN IF NOT EXISTS varbinary INT",
"ALTER TABLE events RENAME COLUMN payload TO varbinary",
"ALTER TABLE events RENAME TO varbinary",
"CREATE TABLE t AS SELECT 1 AS varbinary",
"CREATE TABLE t AS SELECT a, b varbinary FROM s",
"CREATE TABLE t AS (SELECT a, b varbinary FROM s)",
"CREATE TABLE t (varbinary INT, a INT)"})
void shouldNotRenameAColumnOrAliasThatIsCalledLikeABinaryType(String sql) {
assertSame(sql, RedshiftSqlInterceptor.rewrite(sql));
}
@Test
void shouldTurnTheTypeOfAColumnCalledLikeABinaryTypeAndKeepItsName() {
assertEquals("ALTER TABLE events ADD COLUMN varbinary varbyte",
RedshiftSqlInterceptor.rewrite("ALTER TABLE events ADD COLUMN varbinary VARBYTE(8)"));
assertEquals("CREATE TABLE t (varbinary varbyte, a INT)",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (varbinary VARBINARY(8), a INT)"));
assertEquals("ALTER TABLE events ADD COLUMN IF NOT EXISTS x varbyte",
RedshiftSqlInterceptor.rewrite("ALTER TABLE events ADD COLUMN IF NOT EXISTS x VARBYTE(8)"));
}
@Test
void shouldTurnABinaryTypeAfterACommentOrALongGapIntoTheVarbyteDomain() {
assertEquals("CREATE TABLE t (payload /* note */ varbyte, id INT)",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (payload /* note */ VARBYTE(16), id INT)"));
assertEquals("CREATE TABLE t (payload -- note\n varbyte, id INT)",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (payload -- note\n VARBYTE(16), id INT)"));
String gap = " ".repeat(300);
assertEquals("CREATE TABLE t (payload" + gap + "varbyte)",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (payload" + gap + "VARBYTE(16))"));
}
@Test
void shouldTurnAnUnsizedBinaryAliasIntoTheVarbyteDomain() {
assertEquals("CREATE TABLE t (a varbyte, b varbyte);",
RedshiftSqlInterceptor.rewrite("CREATE TABLE t (a VARBINARY, b BINARY VARYING);"));
}
@Test
void shouldLeaveAColumnNamedLikeABinaryTypeAlone() {
String sql = "CREATE TABLE t (id INT, varbinary INT, binary_data INT);";
assertSame(sql, RedshiftSqlInterceptor.rewrite(sql));
}
@Test
void shouldLeaveASuperColumnAndABinaryTypeInAStringLiteralAlone() {
String sql = "CREATE TABLE t (doc SUPER, note VARCHAR(20) DEFAULT 'a VARBYTE(5) b');";
assertSame(sql, RedshiftSqlInterceptor.rewrite(sql));
}
@Test
void shouldNotTouchABinaryTypeOutsideTableDdl() {
String sql = "SELECT CAST(x AS VARBYTE(10)) FROM t";
assertSame(sql, RedshiftSqlInterceptor.rewrite(sql));
}
}