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

@@ -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));
}
}