mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
A prepared statement with a predicate on a bound value (WHERE day = $1) loaded every Glue partition, because the pruner read only literals. The Bind message now carries its text-format values, and the pruner reads each $n as the value bound to it. A statement that is only being parsed has no values yet, so it loads no partition, enough for PostgreSQL to plan it; each Bind loads the partitions its values select. A NULL, binary-format or unreadable value leaves its predicate out and the query loads every partition. A malformed Bind parameter section leaves the values unknown instead of failing the connection. Parse of a parameterized Spectrum statement no longer deletes partitions by cast key, which could remove rows of overlapping partitions that stay recorded as loaded; the Bind reconciles the table. Bind parameters are decoded only when a Spectrum statement needs them, and binary values are skipped instead of copied.
This commit is contained in:
1 parent
9dae9f8036
commit
2964140717
12 files changed
+491
-41
No files matched your search
@@ -799,9 +799,11 @@ Pruning applies to the simple query protocol, the extended query protocol (the d
|
||||
driver, unless `preferQueryMode=simple`), statements inside a transaction block, and the Data API outside a
|
||||
transaction block. A Data API statement inside a transaction block, which includes a batch, loads every
|
||||
partition, because that backend cannot report where its transaction ends.
|
||||
Only predicates written as literals are used. A predicate on a bind parameter (`$1`, `$2`) is left out, so a
|
||||
statement whose partition predicates all use bind parameters loads every partition, while a literal predicate
|
||||
in the same statement still prunes.
|
||||
A bind parameter (`$1`, `$2`) in a predicate is read as the value the client binds, so a prepared statement
|
||||
prunes like the same query written with literals. When the statement is parsed its values are not yet known, so
|
||||
it loads no partition at that point, only enough for PostgreSQL to plan it, and each Bind loads the partitions
|
||||
its values select. A parameter that is NULL, sent in binary format, or compared in a form Floci does not read
|
||||
(for example `$1::int`) leaves its predicate out, and the query loads every partition.
|
||||
The partitions loaded inside a transaction block, or by an extended query cycle, are staged for their connection
|
||||
and recorded as loaded only when the transaction (or the cycle) commits. A rollback, an error or a
|
||||
`ROLLBACK TO SAVEPOINT` discards them, so nothing is left behind that a later query would trust. Staged
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.IntPredicate;
|
||||
@@ -146,9 +147,54 @@ public class PostgresWireDecoder {
|
||||
/** Decode the leading names of a Bind ({@code 'B'}) message body. */
|
||||
public BindMessage decodeBind(FrontendMessage message) throws IOException {
|
||||
BodyCursor cursor = cursorFor(message, 'B');
|
||||
String portalName = cursor.readCString();
|
||||
String statementName = cursor.readCString();
|
||||
return new BindMessage(portalName, statementName);
|
||||
return new BindMessage(cursor.readCString(), cursor.readCString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Text-format values of a Bind's parameters, by position. A NULL or a binary-format value is null: the
|
||||
* caller cannot read it as a literal. Only a statement that prunes needs them, so they are read apart from
|
||||
* {@link #decodeBind}. A malformed section gives an empty list: the backend still gets the original frame
|
||||
* and reports a malformed Bind itself, so it must not fail here.
|
||||
*/
|
||||
public List<String> decodeBindParameters(FrontendMessage message) throws IOException {
|
||||
BodyCursor cursor = cursorFor(message, 'B');
|
||||
cursor.readCString();
|
||||
cursor.readCString();
|
||||
try {
|
||||
return readBindParameters(cursor);
|
||||
} catch (IOException expected) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> readBindParameters(BodyCursor cursor) throws IOException {
|
||||
int formatCount = cursor.readInt16();
|
||||
int[] formats = new int[formatCount];
|
||||
for (int i = 0; i < formatCount; i++) {
|
||||
formats[i] = cursor.readInt16();
|
||||
}
|
||||
int parameterCount = cursor.readInt16();
|
||||
if (formatCount > 1 && formatCount != parameterCount) {
|
||||
throw new IOException("Bind has " + formatCount + " parameter format codes for " + parameterCount
|
||||
+ " parameters");
|
||||
}
|
||||
List<String> values = new ArrayList<>(parameterCount);
|
||||
for (int i = 0; i < parameterCount; i++) {
|
||||
int length = cursor.readInt32();
|
||||
if (length < 0) {
|
||||
values.add(null);
|
||||
continue;
|
||||
}
|
||||
// zero format codes mean every parameter is text, one applies to all, otherwise one per parameter
|
||||
int format = formatCount == 0 ? 0 : formatCount == 1 ? formats[0] : formats[i];
|
||||
if (format == 0) {
|
||||
values.add(new String(cursor.readBytes(length), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
cursor.skip(length);
|
||||
values.add(null);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** Decode an Execute ({@code 'E'}) message body. */
|
||||
@@ -262,6 +308,18 @@ public class PostgresWireDecoder {
|
||||
return value;
|
||||
}
|
||||
|
||||
private void skip(int count) throws IOException {
|
||||
requireRemaining(count);
|
||||
offset += count;
|
||||
}
|
||||
|
||||
private byte[] readBytes(int count) throws IOException {
|
||||
requireRemaining(count);
|
||||
byte[] value = Arrays.copyOfRange(body, offset, offset + count);
|
||||
offset += count;
|
||||
return value;
|
||||
}
|
||||
|
||||
private int readInt32() throws IOException {
|
||||
requireRemaining(4);
|
||||
int value = ((body[offset] & 0xFF) << 24)
|
||||
|
||||
@@ -374,7 +374,8 @@ public class RedshiftInterceptingBridge {
|
||||
try {
|
||||
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
|
||||
boolean prepared = runWithBackendOwned(() -> {
|
||||
spectrumInterceptor.preparation().prepare(parse.sql(), spectrumSession(), relationalBackend);
|
||||
// no values yet: a parameterized statement is only planned here, the Bind loads its partitions
|
||||
spectrumInterceptor.preparation().prepare(parse.sql(), spectrumSession(), relationalBackend, null);
|
||||
return true;
|
||||
});
|
||||
if (!prepared) {
|
||||
@@ -415,10 +416,12 @@ public class RedshiftInterceptingBridge {
|
||||
PostgresWireDecoder.ParseMessage relational = relationalStatements.get(bind.statementName());
|
||||
if (relational != null && !coordinator.isDiscardingUntilSync()) {
|
||||
try {
|
||||
List<String> parameterValues = decoder.decodeBindParameters(message);
|
||||
// Parse/Describe responses may be buffered until Flush or Sync; drain them before taking ownership.
|
||||
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
|
||||
boolean prepared = runWithBackendOwned(() -> {
|
||||
spectrumInterceptor.preparation().prepare(relational.sql(), spectrumSession(), relationalBackend);
|
||||
spectrumInterceptor.preparation().prepare(relational.sql(), spectrumSession(), relationalBackend,
|
||||
parameterValues);
|
||||
return true;
|
||||
});
|
||||
if (!prepared) {
|
||||
|
||||
+28
-7
@@ -213,14 +213,26 @@ public class ExternalTableMaterializer {
|
||||
*/
|
||||
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
String tableName, String sql) {
|
||||
return ensureCurrent(backend, session, binding, tableName, sql, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #ensureCurrent(BackendSql, SpectrumSession, ExternalSchemaBinding, String, String)} for a query
|
||||
* with bind parameters: {@code parameters} holds the text of each bound value, a null where it is unusable.
|
||||
* Null {@code parameters} means the statement is only being parsed and its values are not known yet; a
|
||||
* partitioned table then loads no partition, enough for PostgreSQL to plan it, and the Bind loads the ones
|
||||
* its values select.
|
||||
*/
|
||||
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
String tableName, String sql, List<String> parameters) {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
|
||||
session.inTransaction() || !backend.permitsCachePublication())) {
|
||||
return ensureCurrentLocked(backend, session, binding, tableName, sql);
|
||||
return ensureCurrentLocked(backend, session, binding, tableName, sql, parameters);
|
||||
}
|
||||
}
|
||||
|
||||
private Outcome ensureCurrentLocked(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
String tableName, String sql) {
|
||||
String tableName, String sql, List<String> parameters) {
|
||||
Table table;
|
||||
try {
|
||||
table = RequestScopes.callAs(session.accountId(), () -> glueService.getTable(binding.glueDatabase(), tableName));
|
||||
@@ -240,7 +252,8 @@ public class ExternalTableMaterializer {
|
||||
authorizeIcebergManifests(session.accountId(), binding, roleSession, table, location);
|
||||
List<Partition> partitions = partitions(session.accountId(), binding, table);
|
||||
if (holdsPartitions(table, session, backend, partitions)) {
|
||||
return ensurePartitions(backend, session, binding, roleSession, table, location, partitions, sql);
|
||||
return ensurePartitions(backend, session, binding, roleSession, table, location, partitions, sql,
|
||||
parameters);
|
||||
}
|
||||
List<ReadSource> sources = readSources(session.accountId(), binding, roleSession, table, location, partitions);
|
||||
List<S3Object> objects = sources.stream().flatMap(source -> source.objects().stream()).toList();
|
||||
@@ -339,13 +352,16 @@ public class ExternalTableMaterializer {
|
||||
*/
|
||||
private Outcome ensurePartitions(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
RedshiftRoleAccess.RoleSession roleSession, Table table, Location location,
|
||||
List<Partition> partitions, String sql) {
|
||||
List<Partition> partitions, String sql, List<String> parameters) {
|
||||
String accountId = session.accountId();
|
||||
Optional<PartitionPruner.Filter> filter = PartitionPruner.filterFor(sql, binding.schemaName(),
|
||||
table.getName(), table.getPartitionKeys());
|
||||
table.getName(), table.getPartitionKeys(), parameters);
|
||||
// partitions that PostgreSQL's casts make equal cannot be told apart by key value, so they are all read
|
||||
boolean overlapping = hasOverlappingPartitions(table, partitions);
|
||||
List<Partition> qualified = filter.isEmpty() || overlapping ? partitions
|
||||
// a statement still being parsed has no values to select with, and its Bind loads what it needs
|
||||
boolean awaitingValues = parameters == null && PartitionPruner.hasParameters(sql);
|
||||
List<Partition> qualified = awaitingValues ? List.of()
|
||||
: filter.isEmpty() || overlapping ? partitions
|
||||
: partitions.stream().filter(partition -> filter.get().matches(partition.getValues())).toList();
|
||||
List<ReadSource> sources = readSources(accountId, binding, roleSession, table, location, qualified);
|
||||
authorizeObjects(accountId, binding, roleSession, sources);
|
||||
@@ -372,6 +388,11 @@ public class ExternalTableMaterializer {
|
||||
previousSignature = schemaSignatures.get(cacheKey);
|
||||
}
|
||||
boolean reset = state == null || !state.identity().equals(identity) || !definitions.equals(previousSignature);
|
||||
if (awaitingValues && !reset) {
|
||||
// a statement still being parsed loads nothing; its Bind reconciles the table, because a delete by
|
||||
// key value here could remove rows of partitions that stay recorded as loaded
|
||||
return Outcome.CURRENT;
|
||||
}
|
||||
Map<List<String>, String> held = reset ? Map.of() : state.partitions();
|
||||
Set<List<String>> existing = partitions.stream().map(Partition::getValues).collect(Collectors.toSet());
|
||||
List<List<String>> deletions = new ArrayList<>(held.keySet().stream()
|
||||
@@ -390,7 +411,7 @@ public class ExternalTableMaterializer {
|
||||
loaded.put(values, fingerprint);
|
||||
}
|
||||
}
|
||||
if (overlapping && !reset && (!deletions.isEmpty() || !toLoad.isEmpty())) {
|
||||
if (overlapping && !reset &&(!deletions.isEmpty() || !toLoad.isEmpty())) {
|
||||
// a delete by key value cannot tell overlapping partitions apart, so the whole table is replaced
|
||||
reset = true;
|
||||
toLoad.clear();
|
||||
|
||||
@@ -77,10 +77,20 @@ final class PartitionPruner {
|
||||
* table has no usable predicate in some place it is named, or the text is not understood.
|
||||
*/
|
||||
static Optional<Filter> filterFor(String sql, String schema, String table, List<Column> partitionKeys) {
|
||||
return filterFor(sql, schema, table, partitionKeys, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #filterFor(String, String, String, List)}, reading each {@code $n} as the text of
|
||||
* {@code parameters.get(n - 1)}. A parameter with no value, or a null one, stays unknown, so a predicate on
|
||||
* it is not used.
|
||||
*/
|
||||
static Optional<Filter> filterFor(String sql, String schema, String table, List<Column> partitionKeys,
|
||||
List<String> parameters) {
|
||||
if (sql == null || partitionKeys == null || partitionKeys.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Tokens tokens = tokenize(sql);
|
||||
Tokens tokens = bindParameters(tokenize(sql), parameters);
|
||||
if (tokens.unsafe || !tokens.balanced()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@@ -723,6 +733,51 @@ final class PartitionPruner {
|
||||
return words.size() == 3 && words.get(1).text.equals(schema) && words.get(2).text.equals(table);
|
||||
}
|
||||
|
||||
/** Whether the text names a bind parameter such as {@code $1} outside strings, comments and quoted names. */
|
||||
static boolean hasParameters(String sql) {
|
||||
if (sql == null || sql.indexOf('$') < 0) {
|
||||
return false;
|
||||
}
|
||||
return tokenize(sql).list.stream().anyMatch(token -> parameterIndex(token) >= 0);
|
||||
}
|
||||
|
||||
/** Zero-based position of a {@code $n} token, or -1 when the token is not a bind parameter. */
|
||||
private static int parameterIndex(Token token) {
|
||||
String text = token.text;
|
||||
if (token.kind != Kind.OTHER || text.length() < 2 || text.charAt(0) != '$') {
|
||||
return -1;
|
||||
}
|
||||
for (int i = 1; i < text.length(); i++) {
|
||||
if (!Character.isDigit(text.charAt(i))) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(text.substring(1)) - 1;
|
||||
} catch (NumberFormatException expected) {
|
||||
// a number too long for an int is no parameter the client could have bound
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces each {@code $n} that has a text value with a string literal of it, which the predicate parser
|
||||
* reads like the same literal written in the query. Quotes in the value cannot end the literal: a token
|
||||
* holds the text itself, not SQL.
|
||||
*/
|
||||
private static Tokens bindParameters(Tokens tokens, List<String> parameters) {
|
||||
if (parameters == null || parameters.isEmpty()) {
|
||||
return tokens;
|
||||
}
|
||||
List<Token> list = new ArrayList<>(tokens.list.size());
|
||||
for (Token token : tokens.list) {
|
||||
int index = parameterIndex(token);
|
||||
String value = index >= 0 && index < parameters.size() ? parameters.get(index) : null;
|
||||
list.add(value == null ? token : new Token(Kind.STRING, value, true));
|
||||
}
|
||||
return new Tokens(list, tokens.unsafe);
|
||||
}
|
||||
|
||||
private static Tokens tokenize(String sql) {
|
||||
SpectrumSqlLexer.Result result = SpectrumSqlLexer.tokenize(sql);
|
||||
List<Token> list = new ArrayList<>(result.tokens().size());
|
||||
|
||||
+11
-3
@@ -50,8 +50,16 @@ public class SpectrumQueryPreparation {
|
||||
}
|
||||
|
||||
public boolean prepare(String sql, SpectrumSession session, BackendSql backend) {
|
||||
return prepare(sql, session, backend, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a statement that has bind parameters. {@code parameters} is the text of each bound value, a null
|
||||
* where it is unusable; null {@code parameters} means the statement is only being parsed, with no values yet.
|
||||
*/
|
||||
public boolean prepare(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
|
||||
try {
|
||||
return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend));
|
||||
return RequestScopes.callAs(session.accountId(), () -> prepareInScope(sql, session, backend, parameters));
|
||||
} catch (AwsException exception) {
|
||||
String state = switch (exception.getErrorCode()) {
|
||||
case "AlreadyExistsException" -> "42P07";
|
||||
@@ -91,7 +99,7 @@ public class SpectrumQueryPreparation {
|
||||
};
|
||||
}
|
||||
|
||||
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend) {
|
||||
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend, List<String> parameters) {
|
||||
Optional<ExternalStatement> statement = parser.parse(sql);
|
||||
if (statement.orElse(null) instanceof ExternalStatement.CreateSchema schema) {
|
||||
return createSchema(schema, session, backend);
|
||||
@@ -139,7 +147,7 @@ public class SpectrumQueryPreparation {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
|
||||
session.inTransaction() || !backend.permitsCachePublication())) {
|
||||
requireCurrentBinding(session, binding);
|
||||
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table(), sql);
|
||||
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table(), sql, parameters);
|
||||
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
|
||||
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
|
||||
+ "." + reference.table() + "\" does not exist");
|
||||
|
||||
@@ -679,9 +679,10 @@ class RedshiftSpectrumIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
@Timeout(120)
|
||||
void readsOnlyThePartitionsTheWhereSelectsOnTheExtendedProtocolAndInATransaction() throws Exception {
|
||||
void readsOnlyThePartitionsTheWhereSelectsOnTheExtendedProtocolAndInATransaction(boolean bindParameters) throws Exception {
|
||||
bucket = "spectrum-pruning-ext-" + System.nanoTime();
|
||||
s3Service.createBucket(bucket, "us-east-1");
|
||||
s3Service.putObject(bucket, "events/day=1/part-1.csv", "1,10\n2,20\n".getBytes(StandardCharsets.UTF_8),
|
||||
@@ -713,29 +714,51 @@ class RedshiftSpectrumIntegrationTest {
|
||||
+ "PARTITION (day='1') LOCATION 's3://" + bucket + "/events/day=1/' "
|
||||
+ "PARTITION (day='2') LOCATION 's3://" + bucket + "/events/day=2/'");
|
||||
|
||||
// the cache is cold here, so the simple protocol transaction itself loads and stages the partition
|
||||
try (Connection simple = DriverManager.getConnection(baseUrl + "&preferQueryMode=simple",
|
||||
"admin", "Secret123");
|
||||
Statement query = simple.createStatement()) {
|
||||
simple.setAutoCommit(false);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
simple.commit();
|
||||
simple.setAutoCommit(true);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
SQLException unreadable = assertThrows(SQLException.class,
|
||||
() -> query.executeQuery("SELECT SUM(amount) FROM " + schemaName + ".events"));
|
||||
assertEquals("22P02", unreadable.getSQLState());
|
||||
if (!bindParameters) {
|
||||
// The literal case also covers loading the cold cache in a Simple Query transaction.
|
||||
try (Connection simple = DriverManager.getConnection(baseUrl + "&preferQueryMode=simple",
|
||||
"admin", "Secret123");
|
||||
Statement query = simple.createStatement()) {
|
||||
simple.setAutoCommit(false);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
simple.commit();
|
||||
simple.setAutoCommit(true);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
SQLException unreadable = assertThrows(SQLException.class,
|
||||
() -> query.executeQuery("SELECT SUM(amount) FROM " + schemaName + ".events"));
|
||||
assertEquals("22P02", unreadable.getSQLState());
|
||||
}
|
||||
}
|
||||
try (Connection extended = DriverManager.getConnection(baseUrl + "&preferQueryMode=extended",
|
||||
String select = bindParameters ? "SELECT SUM(amount) FROM " + schemaName + ".events WHERE day = ?" : selectDayOne;
|
||||
try (Connection extended = DriverManager.getConnection(baseUrl + "&preferQueryMode=extended&binaryTransfer=false",
|
||||
"admin", "Secret123");
|
||||
Statement query = extended.createStatement()) {
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
PreparedStatement query = extended.prepareStatement(select)) {
|
||||
query.unwrap(PGStatement.class).setPrepareThreshold(1);
|
||||
// Describe forces Parse before any Bind, while the parameterized case still has a cold cache.
|
||||
assertEquals(bindParameters ? 1 : 0, query.getParameterMetaData().getParameterCount());
|
||||
if (bindParameters) {
|
||||
query.setInt(1, 1);
|
||||
}
|
||||
assertPreparedSum(query, 30);
|
||||
extended.setAutoCommit(false);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
assertPreparedSum(query, 30);
|
||||
extended.rollback();
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
assertPreparedSum(query, 30);
|
||||
extended.commit();
|
||||
extended.setAutoCommit(true);
|
||||
if (bindParameters) {
|
||||
query.setInt(1, 2);
|
||||
SQLException unreadable = assertThrows(SQLException.class, query::executeQuery);
|
||||
assertEquals("22P02", unreadable.getSQLState());
|
||||
query.setInt(1, 1);
|
||||
assertPreparedSum(query, 30);
|
||||
s3Service.putObject(bucket, "events/day=2/part-1.csv", "3,40\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
query.setInt(1, 2);
|
||||
assertPreparedSum(query, 40);
|
||||
query.setInt(1, 1);
|
||||
assertPreparedSum(query, 30);
|
||||
}
|
||||
}
|
||||
statement.execute("DROP SCHEMA IF EXISTS " + schemaName + " CASCADE");
|
||||
} finally {
|
||||
@@ -751,6 +774,14 @@ class RedshiftSpectrumIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertPreparedSum(PreparedStatement statement, long expected) throws SQLException {
|
||||
try (ResultSet rows = statement.executeQuery()) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(expected, rows.getLong(1));
|
||||
assertFalse(rows.next());
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertTotal(Statement statement, long total) throws SQLException {
|
||||
try (ResultSet rows = statement.executeQuery("SELECT COALESCE(SUM(amount),0) FROM lake.events")) {
|
||||
assertTrue(rows.next());
|
||||
|
||||
@@ -9,6 +9,8 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
@@ -48,6 +50,68 @@ class PostgresWireDecoderTest {
|
||||
assertEquals("stmt-1", bind.statementName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesTextBindParametersAndMarksNullAndBinaryAsUnknown() throws IOException {
|
||||
byte[] body = concat(cString("p"), cString("s"),
|
||||
int16(3), int16(0), int16(1), int16(0),
|
||||
int16(3),
|
||||
int32(3), "abc".getBytes(StandardCharsets.UTF_8),
|
||||
int32(2), new byte[]{0, 7},
|
||||
int32(-1),
|
||||
int16(0));
|
||||
|
||||
assertEquals(Arrays.asList("abc", null, null), parameters(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesASingleBindFormatCodeToEveryParameter() throws IOException {
|
||||
byte[] binary = concat(cString("p"), cString("s"), int16(1), int16(1), int16(1),
|
||||
int32(1), new byte[]{5}, int16(0));
|
||||
byte[] text = concat(cString("p"), cString("s"), int16(1), int16(0), int16(2),
|
||||
int32(1), "a".getBytes(StandardCharsets.UTF_8),
|
||||
int32(1), "b".getBytes(StandardCharsets.UTF_8), int16(0));
|
||||
|
||||
assertEquals(Collections.singletonList((String) null), parameters(binary));
|
||||
assertEquals(List.of("a", "b"), parameters(text));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedBindParameterSectionLeavesTheValuesUnknownWithoutFailing() throws IOException {
|
||||
byte[] body = concat(cString("p"), cString("s"), int16(0), int16(1), int32(9), new byte[]{1});
|
||||
|
||||
assertEquals(List.of(), parameters(body));
|
||||
assertEquals("s", decodeBind(body).statementName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBindWithFewerFormatCodesThanParametersLeavesTheValuesUnknownWithoutFailing() throws IOException {
|
||||
byte[] body = concat(cString("p"), cString("s"), int16(2), int16(0), int16(0), int16(3),
|
||||
int32(1), "a".getBytes(StandardCharsets.UTF_8),
|
||||
int32(1), "b".getBytes(StandardCharsets.UTF_8),
|
||||
int32(1), "c".getBytes(StandardCharsets.UTF_8), int16(0));
|
||||
|
||||
assertEquals(List.of(), parameters(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsMixedPerParameterFormatCodes() throws IOException {
|
||||
byte[] body = concat(cString("p"), cString("s"), int16(2), int16(0), int16(1), int16(2),
|
||||
int32(1), "a".getBytes(StandardCharsets.UTF_8),
|
||||
int32(1), new byte[]{9}, int16(0));
|
||||
|
||||
assertEquals(Arrays.asList("a", null), parameters(body));
|
||||
}
|
||||
|
||||
private static List<String> parameters(byte[] body) throws IOException {
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(frame('B', body)));
|
||||
return decoder.decodeBindParameters(decoder.nextMessage());
|
||||
}
|
||||
|
||||
private static PostgresWireDecoder.BindMessage decodeBind(byte[] body) throws IOException {
|
||||
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(frame('B', body)));
|
||||
return decoder.decodeBind(decoder.nextMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesExecuteDescribeAndClose() throws IOException {
|
||||
PostgresWireDecoder.ExecuteMessage execute = decodeExecute(frame('E', concat(cString("p"), int32(0))));
|
||||
|
||||
+42
@@ -550,6 +550,46 @@ class RedshiftInterceptingBridgeTest {
|
||||
assertEquals('T', fromBridge.read());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(20)
|
||||
void preparesExternalQueriesWithoutValuesAtParseAndWithEachBindBeforeForwarding() throws Exception {
|
||||
String sql = "SELECT SUM(amount) FROM lake.events WHERE day = $1";
|
||||
SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class);
|
||||
SpectrumQueryPreparation preparation = mock(SpectrumQueryPreparation.class);
|
||||
when(interceptor.preparation()).thenReturn(preparation);
|
||||
when(preparation.referencesExternal(eq(sql), any())).thenReturn(true);
|
||||
startBridge(interceptor);
|
||||
testClientEnd.setSoTimeout(5000);
|
||||
testBackendEnd.setSoTimeout(5000);
|
||||
InputStream response = testClientEnd.getInputStream();
|
||||
byte[] parse = PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage("s", sql, List.of(23)), sql);
|
||||
|
||||
testClientEnd.getOutputStream().write(parse);
|
||||
testClientEnd.getOutputStream().flush();
|
||||
assertEquals('H', nextForwarded().type());
|
||||
assertArrayEquals(parse, nextForwarded().toPacketBytes());
|
||||
verify(preparation).prepare(eq(sql), any(), any(), isNull());
|
||||
writeBackendFrame('1', new byte[0]);
|
||||
assertEquals('1', response.read());
|
||||
skipFrameBody(response);
|
||||
|
||||
for (String day : List.of("1", "2")) {
|
||||
byte[] value = day.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] bind = frame('B', concat(cString(""), cString("s"), new byte[]{0, 0, 0, 1},
|
||||
ByteBuffer.allocate(4).putInt(value.length).array(), value, new byte[]{0, 0}));
|
||||
testClientEnd.getOutputStream().write(bind);
|
||||
testClientEnd.getOutputStream().flush();
|
||||
assertEquals('H', nextForwarded().type());
|
||||
assertArrayEquals(bind, nextForwarded().toPacketBytes());
|
||||
verify(preparation).prepare(eq(sql), any(), any(), eq(List.of(day)));
|
||||
writeBackendFrame('2', new byte[0]);
|
||||
assertEquals('2', response.read());
|
||||
skipFrameBody(response);
|
||||
}
|
||||
verify(preparation, never()).prepare(anyString(), any(), any());
|
||||
verify(preparation, times(3)).prepare(eq(sql), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(20)
|
||||
void parsingAndDescribingExternalDdlDoesNotExecuteCatalogChanges() throws Exception {
|
||||
@@ -573,6 +613,8 @@ class RedshiftInterceptingBridgeTest {
|
||||
assertEquals('n', response.read());
|
||||
skipFrameBody(response);
|
||||
Mockito.verify(preparation, Mockito.never()).prepare(Mockito.anyString(), Mockito.any(), Mockito.any());
|
||||
Mockito.verify(preparation, Mockito.never()).prepare(Mockito.anyString(), Mockito.any(), Mockito.any(),
|
||||
Mockito.any());
|
||||
Mockito.verify(interceptor, Mockito.never()).execute(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any());
|
||||
}
|
||||
|
||||
|
||||
+107
@@ -23,6 +23,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -52,6 +53,7 @@ import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.ArgumentMatchers.notNull;
|
||||
import static org.mockito.ArgumentMatchers.startsWith;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -1288,6 +1290,111 @@ class ExternalTableMaterializerTest {
|
||||
&& !sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
private static final String DAY_PARAMETER_SQL = "SELECT * FROM analytics.events WHERE day = $1";
|
||||
|
||||
@Test
|
||||
void loadsNoPartitionWhileAParameterizedStatementIsOnlyBeingParsed() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_PARAMETER_SQL, null);
|
||||
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
|
||||
assertThat(extended.statements.stream().anyMatch(sql -> sql.contains("CREATE TABLE \"analytics\".\"events\"")),
|
||||
equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsOnlyThePartitionTheBoundValueSelectsAfterTheStatementWasParsed() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_PARAMETER_SQL, null);
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_PARAMETER_SQL,
|
||||
List.of("2026-01-02"));
|
||||
|
||||
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/two/part-1.csv")
|
||||
&& !sql.contains("s3://bucket/one/")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsEveryPartitionWhenTheBoundValueIsUnusable() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_PARAMETER_SQL,
|
||||
Collections.singletonList(null));
|
||||
|
||||
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
|
||||
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsingAParameterizedStatementDoesNotEmptyATableOfOverlappingPartitions() {
|
||||
Table table = dayPartitionedTable();
|
||||
table.setPartitionKeys(List.of(new Column("n", "int")));
|
||||
Partition one = dayPartition(table, "1", "one/", "e1");
|
||||
Partition paddedOne = dayPartition(table, "01", "padded/", "e2");
|
||||
Partition two = dayPartition(table, "2", "two/", "e3");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, paddedOne, two));
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events",
|
||||
"SELECT * FROM analytics.events WHERE n = 1");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, paddedOne));
|
||||
int loaded = extended.statements.size();
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events",
|
||||
"SELECT * FROM analytics.events WHERE n = $1", null);
|
||||
|
||||
assertThat(extended.statements.size(), equalTo(loaded));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBindAfterAParseThatSawAGluePartitionRemovedStillReadsTheRetainedOverlappingPartitions() {
|
||||
Table table = dayPartitionedTable();
|
||||
table.setPartitionKeys(List.of(new Column("n", "int")));
|
||||
Partition one = dayPartition(table, "1", "one/", "e1");
|
||||
Partition paddedOne = dayPartition(table, "01", "padded/", "e2");
|
||||
Partition zeroPaddedOne = dayPartition(table, "001", "zero-padded/", "e3");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, paddedOne, zeroPaddedOne));
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events",
|
||||
"SELECT * FROM analytics.events WHERE n = 1");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, paddedOne));
|
||||
String sql = "SELECT * FROM analytics.events WHERE n = $1";
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", sql, null);
|
||||
clearInvocations(duck);
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", sql, List.of("1"));
|
||||
|
||||
verify(duck).execute(argThat(load -> load.contains("s3://bucket/one/part-1.csv")
|
||||
&& load.contains("s3://bucket/padded/part-1.csv")
|
||||
&& !load.contains("s3://bucket/zero-padded/")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStatementWithoutParametersLoadsItsPartitionsEvenWhileBeingParsed() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_ONE_SQL, null);
|
||||
|
||||
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
|
||||
&& !sql.contains("s3://bucket/two/")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsEveryPartitionOnABackendThatDoesNotReportTheEndOfTheTransactionEvenWhileBeingParsed() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend unreported = new RecordingBackend();
|
||||
unreported.publicationAllowed = false;
|
||||
|
||||
materializer.ensureCurrent(unreported, session(false), BINDING, "events", DAY_PARAMETER_SQL, null);
|
||||
|
||||
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/one/part-1.csv")
|
||||
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsOnlyTheSelectedPartitionInsideATransaction() {
|
||||
twoDayPartitions();
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.redshift.spectrum;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -258,6 +259,64 @@ class PartitionPrunerTest {
|
||||
assertThat(keeps(filter, "b"), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsABoundParameterLikeTheSameLiteral() {
|
||||
Optional<PartitionPruner.Filter> string = PartitionPruner.filterFor(
|
||||
"SELECT * FROM lake.events WHERE day = $1", "lake", "events", DAY, List.of("2026-01-02"));
|
||||
Optional<PartitionPruner.Filter> integer = PartitionPruner.filterFor(
|
||||
"SELECT * FROM lake.events WHERE year >= $1 AND month = $2", "lake", "events", YEAR_MONTH,
|
||||
List.of("2021", "7"));
|
||||
Optional<PartitionPruner.Filter> date = PartitionPruner.filterFor(
|
||||
"SELECT * FROM lake.events WHERE dt BETWEEN $1 AND $2", "lake", "events", DATE_KEY,
|
||||
List.of("2026-01-01", "2026-01-31"));
|
||||
|
||||
assertThat(keeps(string, "2026-01-02"), is(true));
|
||||
assertThat(keeps(string, "2026-01-03"), is(false));
|
||||
assertThat(keeps(integer, "2022", "7"), is(true));
|
||||
assertThat(keeps(integer, "2020", "7"), is(false));
|
||||
assertThat(keeps(date, "2026-01-15"), is(true));
|
||||
assertThat(keeps(date, "2026-02-01"), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBoundValueCannotChangeTheShapeOfThePredicate() {
|
||||
Optional<PartitionPruner.Filter> filter = PartitionPruner.filterFor(
|
||||
"SELECT * FROM lake.events WHERE day = $1", "lake", "events", DAY, List.of("a' OR '1'='1"));
|
||||
|
||||
assertThat(keeps(filter, "a' OR '1'='1"), is(true));
|
||||
assertThat(keeps(filter, "a"), is(false));
|
||||
assertThat(keeps(filter, "b"), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aParameterWithoutAUsableValueLeavesThePredicateOut() {
|
||||
String sql = "SELECT * FROM lake.events WHERE day = $1";
|
||||
|
||||
assertThat(PartitionPruner.filterFor(sql, "lake", "events", DAY, List.of()).isPresent(), is(false));
|
||||
assertThat(PartitionPruner.filterFor(sql, "lake", "events", DAY, Collections.singletonList(null))
|
||||
.isPresent(), is(false));
|
||||
assertThat(PartitionPruner.filterFor(sql, "lake", "events", DAY, List.of("a", "extra")).isPresent(), is(true));
|
||||
assertThat(PartitionPruner.filterFor("SELECT * FROM lake.events WHERE day = $2", "lake", "events", DAY,
|
||||
List.of("a")).isPresent(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBoundValueTheKeyTypeCannotReadStaysOut() {
|
||||
Optional<PartitionPruner.Filter> filter = PartitionPruner.filterFor(
|
||||
"SELECT * FROM lake.events WHERE year = $1", "lake", "events", YEAR_MONTH, List.of("abc"));
|
||||
|
||||
assertThat(filter.isPresent(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findsBindParametersOnlyOutsideStringsAndQuotedNames() {
|
||||
assertThat(PartitionPruner.hasParameters("SELECT * FROM lake.events WHERE day = $1"), is(true));
|
||||
assertThat(PartitionPruner.hasParameters("SELECT * FROM lake.events WHERE day = '$1'"), is(false));
|
||||
assertThat(PartitionPruner.hasParameters("SELECT * FROM lake.events WHERE day = 'a'"), is(false));
|
||||
assertThat(PartitionPruner.hasParameters("SELECT $$1$$ FROM lake.events"), is(false));
|
||||
assertThat(PartitionPruner.hasParameters(null), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresAnotherSchemaOrTable() {
|
||||
assertThat(filter("SELECT * FROM other.events WHERE day = 'a'", DAY).isPresent(), is(false));
|
||||
|
||||
+3
-3
@@ -28,7 +28,7 @@ class SpectrumQueryPreparationTest {
|
||||
materializer = mock(ExternalTableMaterializer.class);
|
||||
backend = mock(BackendSql.class);
|
||||
when(registry.list(SESSION.accountId(), SESSION.clusterKey(), "dev")).thenReturn(List.of(BINDING));
|
||||
when(materializer.ensureCurrent(any(), any(), any(), anyString(), anyString()))
|
||||
when(materializer.ensureCurrent(any(), any(), any(), anyString(), anyString(), any()))
|
||||
.thenReturn(ExternalTableMaterializer.Outcome.CURRENT);
|
||||
glue = mock(GlueService.class);
|
||||
preparation = new SpectrumQueryPreparation(registry, materializer, new ExternalStatementParser(),
|
||||
@@ -62,7 +62,7 @@ class SpectrumQueryPreparationTest {
|
||||
String sql = "SELECT a.id, SUM(b.amount) FROM lake.sales a JOIN lake.sales b "
|
||||
+ "ON a.id=b.id JOIN public.customers c ON c.id=a.id GROUP BY a.id ORDER BY a.id";
|
||||
assertFalse(preparation.prepare(sql, SESSION, backend));
|
||||
verify(materializer).ensureCurrent(backend, SESSION, BINDING, "sales", sql);
|
||||
verify(materializer).ensureCurrent(backend, SESSION, BINDING, "sales", sql, List.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -81,7 +81,7 @@ class SpectrumQueryPreparationTest {
|
||||
|
||||
@Test
|
||||
void missingGlueTableDoesNotUseCachedRelation() {
|
||||
when(materializer.ensureCurrent(backend, SESSION, BINDING, "sales", "SELECT * FROM lake.sales"))
|
||||
when(materializer.ensureCurrent(backend, SESSION, BINDING, "sales", "SELECT * FROM lake.sales", List.of()))
|
||||
.thenReturn(ExternalTableMaterializer.Outcome.NOT_EXTERNAL);
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () ->
|
||||
preparation.prepare("SELECT * FROM lake.sales", SESSION, backend));
|
||||
|
||||
Reference in new issue
Block a user