feat(redshift-data): emulate the Amazon Redshift Data API (#3186)

* feat(redshift-data): resource resolver, connection factory, statement store, service registration

* feat(redshift-data): field mapper, column metadata, SQL parameter binding

* feat(redshift-data): execute, describe, and paged result retrieval

* feat(redshift-data): batch execution, list statements, cancel

* feat(redshift-data): schema introspection operations

* test(redshift-data): end-to-end Data API over a real cluster plus SDK compatibility test

* docs(redshift-data): document the Redshift Data API surface

* fix(redshift-data): address code review findings

- rejectMultiStatement now reuses the SQL tokenizer so a semicolon inside a
  comment, string literal, or dollar-quoted block no longer rejects a valid
  single statement
- GetStatementResultV2 gains unit coverage for the typed and CSV envelopes
- CSV output is RFC 4180 quoted (embedded comma, quote, CR, LF)
- batch rollback is asserted transactionally in the integration test
- RedshiftDataFieldMapper logs a swallowed blob-read SQLException
- RedshiftPid/RedshiftQueryId use a non-negative hash
- NextToken that decodes to a negative offset is rejected
- CancelStatement leaves a FAILED statement FAILED
- DescribeTable paginates ColumnList and emits NextToken
- DbUser is echoed on the SecretArn path
- the statement store no longer builds its sweeper executor in the test constructor

* fix(redshift-data): address PR #3186 review findings

- SQL scanner handles PostgreSQL escape strings (E'...'): a backslash-escaped
  quote no longer ends the literal and mis-detects a following :name as a bind
  marker; plain '...' literals still treat backslash as an ordinary character
- ListStatements clamps MaxResults to 1..100 so MaxResults=0 no longer emits the
  same NextToken forever
- DescribeTable matches Table / Schema exactly (=) instead of LIKE, so a name
  containing _ or % cannot merge other tables' columns into ColumnList
- register the service in the README category table
- drop a stray em dash from the neighbouring services.yaml comment

* fix(redshift-data): bind string parameters untyped so real PostgreSQL infers the column type

CI ran the integration test against a real Redshift (PostgreSQL 15) cluster and
parameterisedStatement failed: a string bound to an int column via setString
raised "operator does not exist: integer = character varying". H2 in PostgreSQL
mode coerces it, so the unit test missed it.

- RedshiftDataConnectionFactory adds stringtype=unspecified to the JDBC URL, so
  setString sends the value untyped and the server infers the target type,
  matching how AWS binds Redshift Data API parameters
- ListStatements now rejects MaxResults above 100 with ValidationException
  instead of silently clamping (PR #3186 re-review)
- RedshiftDataOperationsTest uses JBoss Logging, not java.util.logging (PR #3186 re-review)

* fix(redshift-data): back the statement store with StorageFactory

The store held a bare ConcurrentHashMap outside the configured storage and
lifecycle model. It now obtains an account-aware backend through StorageFactory
("redshift-data", statements.json), the same as Athena's query store, resolved to
the global storage mode via the catalog descriptor. Default mode stays memory, so
statements are still lost on restart as documented; the 24h TTL sweep now walks
every account partition and deletes per account since the sweep thread has no
request context. StoredStatement is annotated for reflection and field-visible
serialization so persistent modes round-trip it.

* test(redshift-data): cover StoredStatement serialization round-trip and values()

The StorageFactory-backed store serializes StoredStatement in persistent modes.
Adds a round-trip test through the exact mapper PersistentStorage builds,
covering the ArrayNode, enum, Instant, and nested sub-statement fields plus the
field-visibility annotation, and a values() test.

* fix(redshift-data): register the nested Status enum for reflection

PersistedModelReflectionTest walks every type reachable from a StorageFactory
persistence root; StoredStatement.status pointed at an unregistered enum, so
native-image deserialization of a persisted statement would fail on restart.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-07 20:18:22 -04:00
1 parent 618f52e758
commit b9039fef1d
30 files changed
+2805 -3

No files matched your search

@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.services.redshiftdata;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
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.time.Duration;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class RedshiftDataApiIntegrationTest {
@Inject
RedshiftService redshift;
private String clusterId;
@BeforeAll
static void configure() {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for Redshift Data API integration tests");
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static boolean dockerAvailable() {
try {
Process p = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true).start();
return p.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
redshift.deleteCluster(clusterId);
clusterId = null;
}
}
private static String quote(String s) {
return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
private String executeAndWait(String sql) {
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": %s, "ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev"}
""".formatted(quote(sql), clusterId))
.then().statusCode(200).extract().path("Id");
awaitFinished(id);
return id;
}
private void awaitFinished(String id) {
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(250)).until(() -> {
String status = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status");
assertTrue(!"FAILED".equals(status) && !"ABORTED".equals(status),
() -> "statement " + id + " ended " + status);
return "FINISHED".equals(status);
});
}
private static int asInt(Object value) {
return ((Number) value).intValue();
}
@Test
void executeDescribeGetResultRoundTrip() {
clusterId = "it-rsdata-roundtrip";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
executeAndWait("CREATE TABLE t (id int, name varchar(20))");
String insertId = executeAndWait("INSERT INTO t VALUES (1, 'a'), (2, 'b')");
Object insertRows = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + insertId + "\"}").then().statusCode(200).extract().path("ResultRows");
assertEquals(2, asInt(insertRows));
String selectId = executeAndWait("SELECT id, name FROM t ORDER BY id");
var result = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + selectId + "\"}").then().statusCode(200).extract();
assertEquals(2, asInt(result.path("TotalNumRows")));
assertEquals("id", result.path("ColumnMetadata[0].name"));
assertEquals(1, asInt(result.path("Records[0][0].longValue")));
assertEquals("a", result.path("Records[0][1].stringValue"));
}
@Test
void parameterisedStatement() {
clusterId = "it-rsdata-param";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
executeAndWait("CREATE TABLE p (id int)");
executeAndWait("INSERT INTO p VALUES (1), (2), (3)");
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT id FROM p WHERE id = :id",
"ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev",
"Parameters": [{"name": "id", "value": "2"}]}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(id);
Object rows = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("TotalNumRows");
assertEquals(1, asInt(rows));
}
@Test
void batchExecuteReportsSubStatements() {
clusterId = "it-rsdata-batch";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
executeAndWait("CREATE TABLE bt (id int)");
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "BatchExecuteStatement", """
{"Sqls": ["INSERT INTO bt VALUES (1)", "SELECT count(*) AS c FROM bt"],
"ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
awaitFinished(id);
List<?> subs = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("SubStatements");
assertEquals(2, subs.size());
Object first = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + id + "\"}").then().statusCode(200)
.extract().path("Records[0][0].longValue");
assertEquals(1, asInt(first));
}
@Test
void batchRollsBackEveryStatementWhenOneFails() {
clusterId = "it-rsdata-batch-rollback";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
executeAndWait("CREATE TABLE br (id int)");
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "BatchExecuteStatement", """
{"Sqls": ["INSERT INTO br VALUES (1)", "INSERT INTO br (nope) VALUES (2)"],
"ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(250)).until(() ->
"FAILED".equals(RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status")));
// The first INSERT must have been rolled back with the batch: br is empty.
String countId = executeAndWait("SELECT count(*) AS c FROM br");
Object count = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult",
"{\"Id\":\"" + countId + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue");
assertEquals(0, asInt(count));
}
@Test
void schemaIntrospection() {
clusterId = "it-rsdata-schema";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
executeAndWait("CREATE TABLE si (a int, b int)");
String target = "\"ClusterIdentifier\": \"" + clusterId + "\", \"DbUser\": \"admin\", \"Database\": \"dev\"";
RestAssuredJsonUtils.awsAction("RedshiftData", "ListDatabases", "{" + target + "}")
.then().statusCode(200).body("Databases", hasItem("dev"));
RestAssuredJsonUtils.awsAction("RedshiftData", "ListTables", "{" + target + ", \"TablePattern\": \"si\"}")
.then().statusCode(200).body("Tables.name", hasItem("si"));
List<?> columns = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeTable",
"{" + target + ", \"Table\": \"si\"}").then().statusCode(200).extract().path("ColumnList");
assertEquals(2, columns.size());
}
@Test
void workgroupNameIsRejected() {
RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement",
"{\"Sql\": \"SELECT 1\", \"WorkgroupName\": \"wg\", \"Database\": \"dev\"}")
.then().statusCode(400).body("__type", containsString("ValidationException"));
}
@Test
void executionErrorSurfacesThroughDescribeNotHttp() {
clusterId = "it-rsdata-err";
redshift.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
{"Sql": "SELECT * FROM nope", "ClusterIdentifier": "%s", "DbUser": "admin", "Database": "dev"}
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(250)).until(() ->
"FAILED".equals(RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status")));
}
}
@@ -0,0 +1,51 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.h2.Driver;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftDataColumnMetadataTest {
static {
Driver.load();
}
private final ObjectMapper om = new ObjectMapper();
@Test
void emitsEveryColumnMetadataFieldForEachColumn() throws Exception {
String url = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";
try (Connection c = DriverManager.getConnection(url, "sa", "");
Statement st = c.createStatement()) {
st.execute("create table t (id int not null, name varchar(50))");
try (ResultSet rs = st.executeQuery("select id as id, name as name from t")) {
ArrayNode columns = RedshiftDataColumnMetadata.toColumnMetadata(om, rs.getMetaData());
assertEquals(2, columns.size());
var id = columns.get(0);
assertEquals("ID", id.get("name").asText().toUpperCase());
assertTrue(id.has("label"));
assertTrue(id.has("typeName"));
assertTrue(id.has("nullable"));
assertTrue(id.has("length"));
assertTrue(id.has("precision"));
assertTrue(id.has("scale"));
assertTrue(id.has("isCaseSensitive"));
assertTrue(id.has("isCurrency"));
assertTrue(id.has("isSigned"));
assertTrue(id.has("schemaName"));
assertTrue(id.has("tableName"));
assertTrue(id.has("columnDefault"));
}
}
}
}
@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.sql.Types;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftDataFieldMapperTest {
private final ObjectMapper om = new ObjectMapper();
@Test
void mapsEachJdbcTypeToTheRightFieldVariant() {
assertEquals(7L, RedshiftDataFieldMapper.toField(om, 7, Types.INTEGER, false).get("longValue").asLong());
assertEquals(7L, RedshiftDataFieldMapper.toField(om, 7L, Types.BIGINT, false).get("longValue").asLong());
assertEquals(1.5, RedshiftDataFieldMapper.toField(om, 1.5d, Types.DOUBLE, false).get("doubleValue").asDouble());
assertTrue(RedshiftDataFieldMapper.toField(om, true, Types.BOOLEAN, false).get("booleanValue").asBoolean());
assertEquals("12.34",
RedshiftDataFieldMapper.toField(om, new java.math.BigDecimal("12.34"), Types.NUMERIC, false)
.get("stringValue").asText());
assertEquals("hello",
RedshiftDataFieldMapper.toField(om, "hello", Types.VARCHAR, false).get("stringValue").asText());
assertTrue(RedshiftDataFieldMapper.toField(om, null, Types.VARCHAR, true).get("isNull").asBoolean());
ObjectNode blob = RedshiftDataFieldMapper.toField(om, new byte[] {1, 2, 3}, Types.VARBINARY, false);
assertTrue(blob.has("blobValue"));
}
@Test
void serializedSizeIsMonotonic() {
ArrayNode oneRow = om.createArrayNode();
oneRow.add(om.createObjectNode().put("stringValue", "abc"));
long small = RedshiftDataFieldMapper.serializedSize(List.of(oneRow));
ArrayNode bigRow = om.createArrayNode();
bigRow.add(om.createObjectNode().put("stringValue", "abcdefghij"));
long big = RedshiftDataFieldMapper.serializedSize(List.of(oneRow, bigRow));
assertTrue(big > small);
assertEquals("abc".getBytes(StandardCharsets.UTF_8).length, small);
}
}
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.redshiftdata;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class RedshiftDataRegistrationIntegrationTest {
private static final String TARGET = "X-Amz-Target";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void redshiftDataTargetReachesTheHandler() {
// The stub service throws ValidationException("... not implemented yet");
// the point is that it is NOT an UnknownOperationException from the catalog.
given()
.contentType("application/x-amz-json-1.1")
.header(TARGET, "RedshiftData.ExecuteStatement")
.body("{\"Sql\":\"select 1\",\"ClusterIdentifier\":\"none\",\"DbUser\":\"admin\",\"Database\":\"dev\"}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("__type", not(containsString("UnknownOperation")));
}
@Test
void deprecatedExecuteSqlIsRejected() {
given()
.contentType("application/x-amz-json-1.1")
.header(TARGET, "RedshiftData.ExecuteSql")
.body("{}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"));
}
}
@@ -0,0 +1,143 @@
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.core.common.AwsException;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftDataResourceResolverTest {
private static final String REGION = "us-east-1";
private final ObjectMapper mapper = new ObjectMapper();
private static Cluster cluster() {
Cluster c = new Cluster();
c.setClusterIdentifier("wh");
c.setMasterUsername("admin");
c.setMasterPassword("Secret123");
c.setContainerHost("127.0.0.1");
c.setContainerPort(55432);
return c;
}
private RedshiftDataResourceResolver resolver(RedshiftService redshift, SecretsManagerService secrets) {
return new RedshiftDataResourceResolver(redshift, secrets, mapper);
}
@Test
void resolvesClusterIdentifierAndMasterDbUser() {
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(cluster()));
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "wh");
req.put("DbUser", "admin");
req.put("Database", "dev");
RedshiftDataResourceResolver.DatabaseTarget target =
resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION);
assertEquals("127.0.0.1", target.host());
assertEquals(55432, target.port());
assertEquals("dev", target.database());
assertEquals("admin", target.user());
assertEquals("Secret123", target.password());
}
@Test
void rejectsWorkgroupName() {
ObjectNode req = mapper.createObjectNode();
req.put("WorkgroupName", "wg-1");
req.put("Database", "dev");
AwsException e = assertThrows(AwsException.class,
() -> resolver(mock(RedshiftService.class), mock(SecretsManagerService.class)).resolve(req, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void rejectsUnknownCluster() {
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("missing"))
.thenThrow(new AwsException("ClusterNotFound", "Cluster missing not found", 404));
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "missing");
req.put("DbUser", "admin");
req.put("Database", "dev");
AwsException e = assertThrows(AwsException.class,
() -> resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void rejectsNonMasterDbUser() {
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(cluster()));
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "wh");
req.put("DbUser", "analyst");
req.put("Database", "dev");
AwsException e = assertThrows(AwsException.class,
() -> resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void resolvesSecretArn() {
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(cluster()));
SecretsManagerService secrets = mock(SecretsManagerService.class);
SecretVersion secret = new SecretVersion();
secret.setSecretString("{\"username\":\"svc\",\"password\":\"p4ss\"}");
when(secrets.getSecretValue(eq("arn:aws:secretsmanager:us-east-1:000000000000:secret:wh-creds"), any(), any(), eq(REGION)))
.thenReturn(secret);
ObjectNode req = mapper.createObjectNode();
req.put("SecretArn", "arn:aws:secretsmanager:us-east-1:000000000000:secret:wh-creds");
req.put("ClusterIdentifier", "wh");
req.put("Database", "dev");
RedshiftDataResourceResolver.DatabaseTarget target = resolver(redshift, secrets).resolve(req, REGION);
assertEquals("svc", target.user());
assertEquals("p4ss", target.password());
}
@Test
void rejectsCrossRegionSecretArn() {
ObjectNode req = mapper.createObjectNode();
req.put("SecretArn", "arn:aws:secretsmanager:eu-west-1:000000000000:secret:wh-creds");
req.put("ClusterIdentifier", "wh");
req.put("Database", "dev");
AwsException e = assertThrows(AwsException.class,
() -> resolver(mock(RedshiftService.class), mock(SecretsManagerService.class)).resolve(req, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void rejectsClusterWithNoContainerRuntime() {
Cluster c = cluster();
c.setContainerHost("");
c.setContainerPort(0);
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(c));
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "wh");
req.put("DbUser", "admin");
req.put("Database", "dev");
AwsException e = assertThrows(AwsException.class,
() -> resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION));
assertEquals("ValidationException", e.getErrorCode());
}
}
@@ -0,0 +1,312 @@
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.core.common.AwsException;
import org.h2.Driver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.sql.DriverManager;
import java.time.Clock;
import java.util.UUID;
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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftDataServiceTest {
static {
Driver.load();
}
private static final String REGION = "us-east-1";
private final ObjectMapper om = new ObjectMapper();
private String jdbcUrl;
private RedshiftDataService service;
@BeforeEach
void setUp() throws Exception {
jdbcUrl = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE";
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", "admin", "x"));
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
when(factory.open(any())).thenAnswer(inv -> DriverManager.getConnection(jdbcUrl, "sa", ""));
service = new RedshiftDataService(resolver, factory,
new RedshiftDataStatementStore(24, Clock.systemUTC()), om);
}
private ObjectNode req(String sql) {
ObjectNode r = om.createObjectNode();
r.put("Sql", sql);
r.put("ClusterIdentifier", "wh");
r.put("DbUser", "admin");
r.put("Database", "dev");
return r;
}
private ObjectNode idOf(String id) {
return om.createObjectNode().put("Id", id);
}
@Test
void executeStoresFinishedResultAndDescribeReportsIt() {
String createId = service.executeStatement(req("create table t (id int, name varchar(20))"), REGION)
.get("Id").asText();
ObjectNode createDescribe = service.describeStatement(idOf(createId));
assertEquals("FINISHED", createDescribe.get("Status").asText());
assertFalse(createDescribe.get("HasResultSet").asBoolean());
service.executeStatement(req("insert into t values (1, 'a'), (2, 'b')"), REGION);
String selectId = service.executeStatement(req("select id, name from t order by id"), REGION)
.get("Id").asText();
ObjectNode selectDescribe = service.describeStatement(idOf(selectId));
assertEquals("FINISHED", selectDescribe.get("Status").asText());
assertTrue(selectDescribe.get("HasResultSet").asBoolean());
assertEquals(2, selectDescribe.get("ResultRows").asInt());
ObjectNode result = service.getStatementResult(idOf(selectId));
assertEquals(2, result.get("Records").size());
assertEquals(1L, result.get("Records").get(0).get(0).get("longValue").asLong());
assertEquals("a", result.get("Records").get(0).get(1).get("stringValue").asText());
assertTrue(result.get("ColumnMetadata").get(0).get("name").asText().equalsIgnoreCase("id"));
}
@Test
void executionErrorIsStoredAsFailedButExecuteStillReturnsAnId() {
ObjectNode response = service.executeStatement(req("select * from does_not_exist"), REGION);
String id = response.get("Id").asText();
ObjectNode describe = service.describeStatement(idOf(id));
assertEquals("FAILED", describe.get("Status").asText());
assertFalse(describe.get("Error").asText().isBlank());
}
@Test
void getStatementResultOnUpdateStatementIsRejected() {
service.executeStatement(req("create table u (id int)"), REGION);
String id = service.executeStatement(req("insert into u values (1)"), REGION).get("Id").asText();
AwsException e = assertThrows(AwsException.class, () -> service.getStatementResult(idOf(id)));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void unknownIdIsResourceNotFound() {
AwsException e = assertThrows(AwsException.class, () -> service.describeStatement(idOf("nope")));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
@Test
void parameterisedSelectBindsValues() {
service.executeStatement(req("create table p (id int)"), REGION);
service.executeStatement(req("insert into p values (1), (2), (3)"), REGION);
ObjectNode r = req("select id from p where id = :id");
r.putArray("Parameters").addObject().put("name", "id").put("value", "2");
String id = service.executeStatement(r, REGION).get("Id").asText();
ObjectNode result = service.getStatementResult(idOf(id));
assertEquals(1, result.get("Records").size());
assertEquals(2L, result.get("Records").get(0).get(0).get("longValue").asLong());
}
@Test
void rejectsMultiStatementSql() {
AwsException e = assertThrows(AwsException.class,
() -> service.executeStatement(req("select 1; select 2"), REGION));
assertEquals("ValidationException", e.getErrorCode());
}
private ObjectNode batchReq(String... sqls) {
ObjectNode r = om.createObjectNode();
r.put("ClusterIdentifier", "wh");
r.put("DbUser", "admin");
r.put("Database", "dev");
var array = r.putArray("Sqls");
for (String sql : sqls) {
array.add(sql);
}
return r;
}
@Test
void batchExecutesInOneTransactionAndDescribeShowsSubStatements() {
String id = service.batchExecuteStatement(batchReq(
"create table b (id int)",
"insert into b values (1), (2)",
"select count(*) as c from b"), REGION).get("Id").asText();
ObjectNode describe = service.describeStatement(idOf(id));
assertEquals("FINISHED", describe.get("Status").asText());
assertEquals(3, describe.get("SubStatements").size());
ObjectNode result = service.getStatementResult(idOf(id));
assertEquals(1, result.get("Records").size());
assertEquals(2L, result.get("Records").get(0).get(0).get("longValue").asLong());
}
@Test
void batchRollsBackWhenASubStatementFails() {
String id = service.batchExecuteStatement(batchReq(
"create table r1 (id int)",
"insert into r1 values (1)",
"insert into r1 (nope) values (2)"), REGION).get("Id").asText();
ObjectNode describe = service.describeStatement(idOf(id));
assertEquals("FAILED", describe.get("Status").asText());
assertFalse(describe.get("Error").asText().isBlank());
}
@Test
void listStatementsIsNewestFirstAndFiltersByName() {
ObjectNode a = req("select 1");
a.put("StatementName", "alpha");
service.executeStatement(a, REGION);
ObjectNode b = req("select 2");
b.put("StatementName", "beta");
service.executeStatement(b, REGION);
ObjectNode all = service.listStatements(om.createObjectNode());
assertTrue(all.get("Statements").size() >= 2);
ObjectNode filtered = service.listStatements(om.createObjectNode().put("StatementName", "alpha"));
assertEquals(1, filtered.get("Statements").size());
assertEquals("alpha", filtered.get("Statements").get(0).get("StatementName").asText());
}
@Test
void cancelOnFinishedStatementReturnsTrueWithoutChangingIt() {
service.executeStatement(req("create table cf (id int)"), REGION);
String id = service.executeStatement(req("select id from cf"), REGION).get("Id").asText();
assertTrue(service.cancelStatement(idOf(id)).get("Status").asBoolean());
assertEquals("FINISHED", service.describeStatement(idOf(id)).get("Status").asText());
}
@Test
void cancelUnknownIdIsResourceNotFound() {
AwsException e = assertThrows(AwsException.class, () -> service.cancelStatement(idOf("missing")));
assertEquals("ResourceNotFoundException", e.getErrorCode());
}
private ObjectNode targetReq() {
ObjectNode r = om.createObjectNode();
r.put("ClusterIdentifier", "wh");
r.put("DbUser", "admin");
r.put("Database", "dev");
return r;
}
@Test
void listTablesAndDescribeTableReadInformationSchema() {
service.executeStatement(req("create table cat (id int not null, name varchar(30))"), REGION);
ObjectNode listReq = targetReq();
listReq.put("TablePattern", "cat");
ObjectNode tables = service.listTables(listReq, REGION);
assertTrue(tables.get("Tables").findValuesAsText("name").stream()
.anyMatch(n -> n.equalsIgnoreCase("cat")));
ObjectNode descReq = targetReq();
descReq.put("Table", "cat");
ObjectNode described = service.describeTable(descReq, REGION);
assertEquals("cat", described.get("TableName").asText());
assertEquals(2, described.get("ColumnList").size());
assertTrue(described.get("ColumnList").get(0).has("typeName"));
assertTrue(described.get("ColumnList").get(0).has("nullable"));
}
@Test
void listSchemasReturnsSchemata() {
ObjectNode schemas = service.listSchemas(targetReq(), REGION);
assertTrue(schemas.get("Schemas").size() >= 1);
}
@Test
void singleStatementWithATrailingCommentContainingASemicolonIsAllowed() {
String id = service.executeStatement(req("select 1 as one -- pick; the; first\n"), REGION)
.get("Id").asText();
assertEquals("FINISHED", service.describeStatement(idOf(id)).get("Status").asText());
}
@Test
void getStatementResultV2ReturnsTypedRecordsByDefault() {
service.executeStatement(req("create table v2 (id int, name varchar(20))"), REGION);
service.executeStatement(req("insert into v2 values (1, 'a')"), REGION);
String id = service.executeStatement(req("select id, name from v2 order by id"), REGION)
.get("Id").asText();
ObjectNode result = service.getStatementResultV2(idOf(id));
assertEquals("JSON", result.get("ResultFormat").asText());
assertEquals(1, result.get("Records").size());
assertEquals(1L, result.get("Records").get(0).get(0).get("longValue").asLong());
assertEquals("a", result.get("Records").get(0).get(1).get("stringValue").asText());
}
@Test
void getStatementResultV2CsvFormatQuotesEmbeddedDelimiters() {
service.executeStatement(req("create table v2csv (v varchar(20))"), REGION);
service.executeStatement(req("insert into v2csv values ('a,b')"), REGION);
ObjectNode r = req("select v from v2csv");
r.put("ResultFormat", "CSV");
String id = service.executeStatement(r, REGION).get("Id").asText();
ObjectNode result = service.getStatementResultV2(idOf(id));
assertEquals("CSV", result.get("ResultFormat").asText());
assertEquals("\"a,b\"", result.get("Records").get(0).get("CSVRecords").asText());
}
@Test
void malformedNextTokenIsRejected() {
service.executeStatement(req("create table tok (id int)"), REGION);
service.executeStatement(req("insert into tok values (1)"), REGION);
String id = service.executeStatement(req("select id from tok"), REGION).get("Id").asText();
ObjectNode r = idOf(id);
r.put("NextToken", "not-base64!!");
AwsException e = assertThrows(AwsException.class, () -> service.getStatementResult(r));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void cancelOnFailedStatementLeavesItFailed() {
String id = service.executeStatement(req("select * from missing_table"), REGION).get("Id").asText();
assertEquals("FAILED", service.describeStatement(idOf(id)).get("Status").asText());
assertTrue(service.cancelStatement(idOf(id)).get("Status").asBoolean());
assertEquals("FAILED", service.describeStatement(idOf(id)).get("Status").asText());
}
@Test
void listStatementsWithZeroMaxResultsDoesNotEmitANonTerminatingToken() {
service.executeStatement(req("select 1"), REGION);
service.executeStatement(req("select 2"), REGION);
ObjectNode result = service.listStatements(om.createObjectNode().put("MaxResults", 0));
assertEquals(2, result.get("Statements").size());
assertFalse(result.has("NextToken"));
}
@Test
void listStatementsRejectsMaxResultsAboveOneHundred() {
AwsException e = assertThrows(AwsException.class,
() -> service.listStatements(om.createObjectNode().put("MaxResults", 500)));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void describeTableMatchesTheExactNameNotAPattern() {
service.executeStatement(req("create table a_b (x int)"), REGION);
service.executeStatement(req("create table axb (y int, z int)"), REGION);
ObjectNode descReq = targetReq();
descReq.put("Table", "a_b");
ObjectNode described = service.describeTable(descReq, REGION);
assertEquals(1, described.get("ColumnList").size());
assertEquals("x", described.get("ColumnList").get(0).get("name").asText().toLowerCase());
}
}
@@ -0,0 +1,120 @@
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.core.common.AwsException;
import org.h2.Driver;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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;
class RedshiftDataSqlParametersTest {
static {
Driver.load();
}
private final ObjectMapper om = new ObjectMapper();
@Test
void rewritesNamedPlaceholdersInOrderAndSkipsLiteralsAndCasts() {
RedshiftDataSqlParameters.ParsedSql parsed = RedshiftDataSqlParameters.parse(
"select * from t where a = :a and b = ':b' and c = :a and d = 1::int");
assertEquals("select * from t where a = ? and b = ':b' and c = ? and d = 1::int", parsed.sql());
assertEquals(List.of("a", "a"), parsed.parameterOrder());
}
@Test
void bindsValuesAsStringsAndDatabaseCoerces() throws Exception {
String url = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1;MODE=PostgreSQL";
try (Connection c = DriverManager.getConnection(url, "sa", "")) {
c.createStatement().execute("create table t (id int, name varchar(20))");
c.createStatement().execute("insert into t values (2, 'bob')");
RedshiftDataSqlParameters.ParsedSql parsed =
RedshiftDataSqlParameters.parse("select name from t where id = :id");
try (PreparedStatement ps = c.prepareStatement(parsed.sql())) {
RedshiftDataSqlParameters.bind(ps, parsed.parameterOrder(), Map.of("id", "2"));
try (ResultSet rs = ps.executeQuery()) {
assertTrue(rs.next());
assertEquals("bob", rs.getString(1));
}
}
}
}
@Test
void missingParameterValueIsRejected() throws Exception {
String url = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";
try (Connection c = DriverManager.getConnection(url, "sa", "")) {
c.createStatement().execute("create table t (id int)");
RedshiftDataSqlParameters.ParsedSql parsed =
RedshiftDataSqlParameters.parse("select * from t where id = :id");
try (PreparedStatement ps = c.prepareStatement(parsed.sql())) {
AwsException e = assertThrows(AwsException.class,
() -> RedshiftDataSqlParameters.bind(ps, parsed.parameterOrder(), Map.of()));
assertEquals("ValidationException", e.getErrorCode());
}
}
}
@Test
void parseParametersReadsNameValueObjectsAndRejectsDuplicates() {
ObjectNode request = om.createObjectNode();
var params = request.putArray("Parameters");
params.addObject().put("name", "id").put("value", "1");
params.addObject().put("name", "id").put("value", "2");
AwsException e = assertThrows(AwsException.class,
() -> RedshiftDataSqlParameters.parseParameters(request, "Parameters"));
assertEquals("ValidationException", e.getErrorCode());
}
@Test
void isMultiStatementIgnoresSemicolonsInsideCommentsLiteralsAndDollarQuotes() {
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select 1 -- a; b\n"));
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select * from t /* x; y */ where a = 1"));
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select ';' as sep"));
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select $tag$a;b$tag$"));
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select 1;"));
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select 1 ; \n "));
}
@Test
void isMultiStatementDetectsARealSecondStatement() {
assertTrue(RedshiftDataSqlParameters.isMultiStatement("select 1; select 2"));
assertTrue(RedshiftDataSqlParameters.isMultiStatement("insert into t values (1); delete from t"));
}
@Test
void backslashEscapedQuoteInsideAnEscapeStringDoesNotEndTheLiteral() {
// E'it\'s :value' is one string literal; :value is literal text, not a bind marker.
RedshiftDataSqlParameters.ParsedSql parsed =
RedshiftDataSqlParameters.parse("select E'it\\'s :value' as v where id = :id");
assertEquals("select E'it\\'s :value' as v where id = ?", parsed.sql());
assertEquals(List.of("id"), parsed.parameterOrder());
}
@Test
void escapeStringWithAnEscapedQuoteIsNotSeenAsMultiStatement() {
assertFalse(RedshiftDataSqlParameters.isMultiStatement("select E'a\\';b' as v"));
}
@Test
void plainLiteralStillTreatsBackslashLiterally() {
// Not an E'' string: backslash is an ordinary character, '' still ends the literal.
RedshiftDataSqlParameters.ParsedSql parsed =
RedshiftDataSqlParameters.parse("select 'a\\' , :x");
assertEquals("select 'a\\' , ?", parsed.sql());
assertEquals(List.of("x"), parsed.parameterOrder());
}
}
@@ -0,0 +1,140 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftDataStatementStoreTest {
private static RedshiftDataStatementStore.StoredStatement statement(String id, Instant createdAt) {
RedshiftDataStatementStore.StoredStatement s = new RedshiftDataStatementStore.StoredStatement();
s.id = id;
s.createdAt = createdAt;
s.updatedAt = createdAt;
s.status = RedshiftDataStatementStore.Status.FINISHED;
return s;
}
@Test
void putThenGet() {
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
store.put(statement("a", Instant.now()));
assertNotNull(store.get("a"));
assertNull(store.get("missing"));
}
@Test
void sweepEvictsEntriesOlderThanTtl() {
Instant now = Instant.parse("2026-09-07T00:00:00Z");
Clock fixed = Clock.fixed(now, ZoneOffset.UTC);
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, fixed);
store.put(statement("old", now.minus(Duration.ofHours(25))));
store.put(statement("fresh", now.minus(Duration.ofHours(1))));
store.sweep();
assertNull(store.get("old"));
assertNotNull(store.get("fresh"));
}
@Test
void clearEmptiesStore() {
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
store.put(statement("a", Instant.now()));
store.clear();
assertNull(store.get("a"));
}
@Test
void valuesReturnsEveryStoredStatement() {
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
store.put(statement("a", Instant.now()));
store.put(statement("b", Instant.now()));
assertEquals(2, store.values().size());
}
/**
* The store is now backed by StorageFactory, so a persistent-mode backend serializes
* StoredStatement to JSON and reads it back through the same TypeReference the backend uses.
* This exercises the reflection / field-visibility annotations plus the ArrayNode, enum,
* Instant, and nested sub-statement fields with the exact mapper PersistentStorage builds.
*/
@Test
void storedStatementRoundTripsThroughThePersistentStorageMapper() throws Exception {
ObjectMapper mapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ArrayNode columnMetadata = mapper.createArrayNode();
columnMetadata.addObject().put("name", "id").put("typeName", "int4").put("nullable", 1);
ArrayNode row = mapper.createArrayNode();
row.addObject().put("longValue", 7L);
row.addObject().put("stringValue", "seven");
RedshiftDataStatementStore.StoredStatement sub = new RedshiftDataStatementStore.StoredStatement();
sub.id = "parent:1";
sub.sql = "insert into t values (7)";
sub.status = RedshiftDataStatementStore.Status.FINISHED;
sub.createdAt = Instant.parse("2026-09-08T10:00:00Z");
sub.updatedAt = sub.createdAt;
RedshiftDataStatementStore.StoredStatement original = new RedshiftDataStatementStore.StoredStatement();
original.id = "parent";
original.sql = "insert into t values (7); select * from t";
original.sqls = List.of("insert into t values (7)", "select * from t");
original.batch = true;
original.statementName = "load";
original.clusterIdentifier = "wh";
original.database = "dev";
original.dbUser = "admin";
original.resultFormat = "CSV";
original.status = RedshiftDataStatementStore.Status.FINISHED;
original.error = null;
original.createdAt = Instant.parse("2026-09-08T10:00:00Z");
original.updatedAt = Instant.parse("2026-09-08T10:00:01Z");
original.durationNanos = 123_456L;
original.hasResultSet = true;
original.resultRows = 1;
original.resultSize = 42;
original.columnMetadata = columnMetadata;
original.rows = List.of(row);
original.subStatements = List.of(sub);
String json = mapper.writeValueAsString(Map.of("parent", original));
Map<String, RedshiftDataStatementStore.StoredStatement> back =
mapper.readValue(json, new TypeReference<Map<String, RedshiftDataStatementStore.StoredStatement>>() {});
RedshiftDataStatementStore.StoredStatement restored = back.get("parent");
assertNotNull(restored);
assertEquals("parent", restored.id);
assertEquals(List.of("insert into t values (7)", "select * from t"), restored.sqls);
assertTrue(restored.batch);
assertEquals("CSV", restored.resultFormat);
assertEquals(RedshiftDataStatementStore.Status.FINISHED, restored.status);
assertEquals(Instant.parse("2026-09-08T10:00:01Z"), restored.updatedAt);
assertEquals(123_456L, restored.durationNanos);
assertTrue(restored.hasResultSet);
assertEquals("id", restored.columnMetadata.get(0).get("name").asText());
assertEquals(1, restored.rows.size());
assertEquals(7L, restored.rows.get(0).get(0).get("longValue").asLong());
assertEquals("seven", restored.rows.get(0).get(1).get("stringValue").asText());
assertEquals(1, restored.subStatements.size());
assertEquals("parent:1", restored.subStatements.get(0).id);
assertEquals(RedshiftDataStatementStore.Status.FINISHED, restored.subStatements.get(0).status);
}
}