mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
Stage partitions loaded by a load that may roll back per client connection and publish them when the transaction commits, guarded by a per-table generation, instead of loading every partition. ensurePartitions waited on the per-table Java lock without a timeout even when the session held PostgreSQL locks. A transaction holding a table lock while another connection held the Java lock to load that table formed a cycle PostgreSQL cannot detect. It now uses the same transaction-aware acquisition as the full-load path. Pruning also applies to the Data API outside a transaction block, a predicate on a bind parameter is left out while literal predicates in the same statement still prune, and a session in a transaction block now waits at most 30 seconds for another load of the same table.
This commit is contained in:
1 parent
a5b3fab110
commit
d1205c34a2
7 files changed
+388
-18
No files matched your search
@@ -795,9 +795,20 @@ needs, reloads the ones whose objects or Glue entry changed and drops the ones G
|
||||
When two partitions hold key values that PostgreSQL casts to the same value, such as integer `1` and `01`,
|
||||
rows can no longer be told apart by partition, so a query on that table loads every partition and replaces
|
||||
the whole table when any of them changes.
|
||||
Pruning applies to the simple query protocol and the Data API. A session in a transaction block, and a client
|
||||
on the extended query protocol (the default of the PostgreSQL JDBC driver, unless `preferQueryMode=simple`),
|
||||
load every partition.
|
||||
Pruning applies to the simple query protocol, the extended query protocol (the default of the PostgreSQL JDBC
|
||||
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.
|
||||
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
|
||||
partitions also stop being trusted when another load changes the table in the meantime, and the next query then
|
||||
reloads it. While a connection holds staged partitions, other connections reload the table on their next query.
|
||||
A session inside a transaction block waits at most 30 seconds for another connection that is loading the same
|
||||
table, then fails with SQLSTATE `58030`; a session outside a transaction block waits for the load to finish.
|
||||
|
||||
Materialized relations are cached in the cluster database. Each new query checks the associated
|
||||
role, trust policy and S3 access before using cached data, following the existing S3 enforcement
|
||||
|
||||
@@ -7,6 +7,14 @@ public interface BackendSql {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifies the client connection whose transaction this backend runs in, so state staged for that
|
||||
* transaction can be published or dropped when it ends. Null when the end of the transaction is not reported.
|
||||
*/
|
||||
default Object connectionKey() {
|
||||
return null;
|
||||
}
|
||||
|
||||
void execute(String sql);
|
||||
long copyIn(String copySql, InputStream data);
|
||||
}
|
||||
+104
-14
@@ -95,16 +95,76 @@ public class ExternalTableMaterializer {
|
||||
/** The partitions each partitioned table holds in PostgreSQL, so a query loads only the ones it reads. */
|
||||
private final ConcurrentHashMap<String, LoadedPartitions> loadedPartitions = new ConcurrentHashMap<>();
|
||||
|
||||
/** Bumped whenever what a table holds changes, so state staged against an older content is recognized as stale. */
|
||||
private final ConcurrentHashMap<String, Long> generations = new ConcurrentHashMap<>();
|
||||
/** Partitions loaded inside a transaction, per client connection, until that transaction commits or rolls back. */
|
||||
private final Map<Object, Map<String, PendingPartitions>> pendingPartitions = new ConcurrentHashMap<>();
|
||||
|
||||
private record PendingLoad(String fingerprint, String definitions) { }
|
||||
|
||||
/** What a partitioned table holds: the table it was loaded for, and a fingerprint per loaded partition. */
|
||||
private record LoadedPartitions(String identity, Map<List<String>, String> partitions) { }
|
||||
|
||||
/** Partitions an uncommitted transaction loaded, valid only while the table's generation is unchanged. */
|
||||
private record PendingPartitions(LoadedPartitions state, String definitions, long generation) { }
|
||||
|
||||
public void finishCycle(BackendSql backend) {
|
||||
pendingLoads.remove(backend);
|
||||
discardPendingPartitions(backend);
|
||||
}
|
||||
|
||||
private void discardPendingPartitions(BackendSql backend) {
|
||||
Object connection = backend.connectionKey();
|
||||
if (connection != null) {
|
||||
pendingPartitions.remove(connection);
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets what the table holds: its content is about to change or can no longer be vouched for. */
|
||||
private void dropHeld(String cacheKey) {
|
||||
loadedPartitions.remove(cacheKey);
|
||||
generations.merge(cacheKey, 1L, Long::sum);
|
||||
}
|
||||
|
||||
private void dropStaged(BackendSql backend, String cacheKey) {
|
||||
Object connection = backend.connectionKey();
|
||||
Map<String, PendingPartitions> staged = connection == null ? null : pendingPartitions.get(connection);
|
||||
if (staged != null) {
|
||||
staged.remove(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
private long generation(String cacheKey) {
|
||||
return generations.getOrDefault(cacheKey, 0L);
|
||||
}
|
||||
|
||||
private void publishPendingPartitions(BackendSql backend) {
|
||||
Object connection = backend.connectionKey();
|
||||
Map<String, PendingPartitions> completed = connection == null ? null : pendingPartitions.remove(connection);
|
||||
if (completed == null) {
|
||||
return;
|
||||
}
|
||||
completed.forEach((key, pending) -> {
|
||||
ReentrantLock lock = locks.computeIfAbsent(key, ignored -> new ReentrantLock());
|
||||
lock.lock();
|
||||
try {
|
||||
// another load changed the table since this transaction did, so what it staged no longer describes it
|
||||
if (generation(key) == pending.generation()) {
|
||||
schemaSignatures.put(key, pending.definitions());
|
||||
loadedPartitions.put(key, pending.state());
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void finishCycle(BackendSql backend, boolean committed) {
|
||||
if (committed) {
|
||||
publishPendingPartitions(backend);
|
||||
} else {
|
||||
discardPendingPartitions(backend);
|
||||
}
|
||||
Map<String, PendingLoad> completed = pendingLoads.remove(backend);
|
||||
if (committed && completed != null) {
|
||||
completed.forEach((key, loaded) -> {
|
||||
@@ -209,7 +269,8 @@ public class ExternalTableMaterializer {
|
||||
String previousSignature = local == null ? schemaSignatures.get(cacheKey) : local.definitions();
|
||||
latestLoads.remove(cacheKey);
|
||||
// a load of every partition replaces what the table held, so the partitions it holds are no longer known
|
||||
loadedPartitions.remove(cacheKey);
|
||||
dropHeld(cacheKey);
|
||||
dropStaged(backend, cacheKey);
|
||||
String definitions = load(backend, session, binding, roleSession, table, sources, previousSignature, null);
|
||||
if (!backend.permitsCachePublication()) {
|
||||
fingerprints.remove(cacheKey);
|
||||
@@ -254,15 +315,20 @@ public class ExternalTableMaterializer {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether what a load puts in PostgreSQL may be undone, so it is only known to be there once the transaction commits. */
|
||||
private static boolean loadsMayRollBack(SpectrumSession session, BackendSql backend) {
|
||||
return session.inTransaction() || !backend.permitsCachePublication();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the table is loaded partition by partition: a partitioned table that has partitions, for a session
|
||||
* whose loads are published at once. A transaction may roll its load back and an Extended Query load is
|
||||
* published only when its cycle commits, so those keep loading every partition.
|
||||
* Whether the table is loaded partition by partition: a partitioned table that has partitions. A load that may
|
||||
* roll back is staged for its connection and published when the transaction commits, which needs a backend that
|
||||
* reports where the transaction ends; without one the table is loaded whole.
|
||||
*/
|
||||
private static boolean holdsPartitions(Table table, SpectrumSession session, BackendSql backend,
|
||||
List<Partition> partitions) {
|
||||
return hasPartitionKeys(table) && !partitions.isEmpty() && !session.inTransaction()
|
||||
&& backend.permitsCachePublication();
|
||||
return hasPartitionKeys(table) && !partitions.isEmpty()
|
||||
&& (!loadsMayRollBack(session, backend) || backend.connectionKey() != null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -288,10 +354,23 @@ public class ExternalTableMaterializer {
|
||||
String cacheKey = cacheKey(session, binding, table.getName());
|
||||
String label = binding.schemaName() + "." + table.getName();
|
||||
ReentrantLock lock = locks.computeIfAbsent(cacheKey, ignored -> new ReentrantLock());
|
||||
acquire(lock, label, false);
|
||||
acquire(lock, label, session.inTransaction());
|
||||
try {
|
||||
LoadedPartitions state = loadedPartitions.get(cacheKey);
|
||||
String previousSignature = schemaSignatures.get(cacheKey);
|
||||
boolean mayRollBack = loadsMayRollBack(session, backend);
|
||||
Object connection = backend.connectionKey();
|
||||
PendingPartitions staged = !mayRollBack || connection == null ? null
|
||||
: pendingPartitions.getOrDefault(connection, Map.of()).get(cacheKey);
|
||||
LoadedPartitions state;
|
||||
String previousSignature;
|
||||
if (staged != null) {
|
||||
// this transaction's own loads are in the table it reads; they hold only while nothing else changed it
|
||||
boolean current = staged.generation() == generation(cacheKey);
|
||||
state = current ? staged.state() : null;
|
||||
previousSignature = current ? staged.definitions() : null;
|
||||
} else {
|
||||
state = loadedPartitions.get(cacheKey);
|
||||
previousSignature = schemaSignatures.get(cacheKey);
|
||||
}
|
||||
boolean reset = state == null || !state.identity().equals(identity) || !definitions.equals(previousSignature);
|
||||
Map<List<String>, String> held = reset ? Map.of() : state.partitions();
|
||||
Set<List<String>> existing = partitions.stream().map(Partition::getValues).collect(Collectors.toSet());
|
||||
@@ -328,10 +407,21 @@ public class ExternalTableMaterializer {
|
||||
fingerprints.remove(cacheKey);
|
||||
latestLoads.remove(cacheKey);
|
||||
pendingLoads.values().forEach(loads -> loads.remove(cacheKey));
|
||||
loadedPartitions.remove(cacheKey);
|
||||
dropHeld(cacheKey);
|
||||
dropStaged(backend, cacheKey);
|
||||
load(backend, session, binding, roleSession, table, toLoad, previousSignature, reset ? null : deletions);
|
||||
schemaSignatures.put(cacheKey, definitions);
|
||||
loadedPartitions.put(cacheKey, new LoadedPartitions(identity, Map.copyOf(loaded)));
|
||||
LoadedPartitions loadedState = new LoadedPartitions(identity, Map.copyOf(loaded));
|
||||
if (mayRollBack) {
|
||||
// a rollback restores the committed columns, so a changed signature cannot be trusted afterwards
|
||||
if (!definitions.equals(schemaSignatures.get(cacheKey))) {
|
||||
schemaSignatures.remove(cacheKey);
|
||||
}
|
||||
pendingPartitions.computeIfAbsent(connection, ignored -> new ConcurrentHashMap<>())
|
||||
.put(cacheKey, new PendingPartitions(loadedState, definitions, generation(cacheKey)));
|
||||
} else {
|
||||
schemaSignatures.put(cacheKey, definitions);
|
||||
loadedPartitions.put(cacheKey, loadedState);
|
||||
}
|
||||
return Outcome.LOADED;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
@@ -378,7 +468,7 @@ public class ExternalTableMaterializer {
|
||||
lock.lock();
|
||||
try {
|
||||
fingerprints.remove(key);
|
||||
loadedPartitions.remove(key);
|
||||
dropHeld(key);
|
||||
latestLoads.remove(key);
|
||||
pendingLoads.values().forEach(loads -> loads.remove(key));
|
||||
} finally {
|
||||
@@ -398,7 +488,7 @@ public class ExternalTableMaterializer {
|
||||
lock.lock();
|
||||
try {
|
||||
fingerprints.remove(key);
|
||||
loadedPartitions.remove(key);
|
||||
dropHeld(key);
|
||||
schemaSignatures.remove(key);
|
||||
latestLoads.remove(key);
|
||||
pendingLoads.values().forEach(loads -> loads.remove(key));
|
||||
|
||||
@@ -16,6 +16,11 @@ public final class PostgresBackendSession implements BackendSql {
|
||||
this.backend = backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object connectionKey() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
try {
|
||||
|
||||
+5
@@ -24,6 +24,11 @@ public final class PostgresExtendedBackendSession implements BackendSql {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object connectionKey() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
/** The client's own pipelined statement failed; the backend discards everything until Sync. */
|
||||
public void onBackendError() {
|
||||
failedUntilSync = true;
|
||||
|
||||
@@ -679,6 +679,78 @@ class RedshiftSpectrumIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(120)
|
||||
void readsOnlyThePartitionsTheWhereSelectsOnTheExtendedProtocolAndInATransaction() 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),
|
||||
"text/csv", null);
|
||||
// this partition cannot be read, so a query that reads it fails and shows which partitions were read
|
||||
s3Service.putObject(bucket, "events/day=2/part-1.csv", "not-a-number,30\n".getBytes(StandardCharsets.UTF_8),
|
||||
"text/csv", null);
|
||||
glueDatabase = "spectrum_pruning_ext_" + System.nanoTime();
|
||||
Database database = new Database();
|
||||
database.setName(glueDatabase);
|
||||
glueService.createDatabase(database);
|
||||
clusterId = "it-pruning-ext-" + System.nanoTime();
|
||||
Cluster cluster = createClusterWithRole(clusterId);
|
||||
String baseUrl = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev?socketTimeout=30";
|
||||
String schemaName = "pruning_ext_lake";
|
||||
String selectDayOne = "SELECT SUM(amount) FROM " + schemaName + ".events WHERE day = 1";
|
||||
|
||||
try (Connection setup = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection(baseUrl + "&preferQueryMode=simple", "admin", "Secret123"),
|
||||
Objects::nonNull);
|
||||
Statement statement = setup.createStatement()) {
|
||||
statement.execute("CREATE EXTERNAL SCHEMA " + schemaName + " FROM DATA CATALOG DATABASE '" + glueDatabase
|
||||
+ "' IAM_ROLE '" + ROLE_ARN + "'");
|
||||
statement.execute("CREATE EXTERNAL TABLE " + schemaName + ".events (id INTEGER, amount INTEGER) "
|
||||
+ "PARTITIONED BY (day INTEGER) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' "
|
||||
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/'");
|
||||
statement.execute("ALTER TABLE " + schemaName + ".events ADD "
|
||||
+ "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());
|
||||
}
|
||||
try (Connection extended = DriverManager.getConnection(baseUrl + "&preferQueryMode=extended",
|
||||
"admin", "Secret123");
|
||||
Statement query = extended.createStatement()) {
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
extended.setAutoCommit(false);
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
extended.rollback();
|
||||
assertDayOneSum(query, selectDayOne);
|
||||
extended.commit();
|
||||
extended.setAutoCommit(true);
|
||||
}
|
||||
statement.execute("DROP SCHEMA IF EXISTS " + schemaName + " CASCADE");
|
||||
} finally {
|
||||
s3Service.deleteObject(bucket, "events/day=1/part-1.csv");
|
||||
s3Service.deleteObject(bucket, "events/day=2/part-1.csv");
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertDayOneSum(Statement statement, String sql) throws SQLException {
|
||||
try (ResultSet rows = statement.executeQuery(sql)) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals(30, rows.getLong(1));
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
|
||||
+180
-1
@@ -79,12 +79,18 @@ class ExternalTableMaterializerTest {
|
||||
private static final class RecordingBackend implements BackendSql {
|
||||
private final List<String> statements = new ArrayList<>();
|
||||
private boolean publicationAllowed = true;
|
||||
private Object connection;
|
||||
|
||||
@Override
|
||||
public boolean permitsCachePublication() {
|
||||
return publicationAllowed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object connectionKey() {
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
statements.add(sql);
|
||||
@@ -1257,7 +1263,7 @@ class ExternalTableMaterializerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsEveryPartitionInATransactionAndOnAnExtendedQueryBackend() {
|
||||
void loadsEveryPartitionWhenTheBackendDoesNotReportTheEndOfTheTransaction() {
|
||||
Table table = dayPartitionedTable();
|
||||
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
|
||||
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
|
||||
@@ -1271,6 +1277,179 @@ class ExternalTableMaterializerTest {
|
||||
&& sql.contains("s3://bucket/two/part-1.csv")), any(), anyString(), eq(ACCOUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsOnlyTheSelectedPartitionOnAnExtendedQueryBackend() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend extended = extendedBackend("connection-1");
|
||||
|
||||
materializer.ensureCurrent(extended, session(false), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
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();
|
||||
RecordingBackend inTransaction = extendedBackend("connection-1");
|
||||
inTransaction.publicationAllowed = true;
|
||||
|
||||
materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
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 aTransactionKeepsThePartitionsItLoadedForItsNextQuery() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend inTransaction = extendedBackend("connection-1");
|
||||
|
||||
materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_ONE_SQL);
|
||||
assertThat(materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
|
||||
int loaded = inTransaction.statements.size();
|
||||
materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_TWO_SQL);
|
||||
|
||||
verify(duck, times(2)).execute(anyString(), any(), anyString(), eq(ACCOUNT));
|
||||
assertThat(inTransaction.statements.subList(loaded, inTransaction.statements.size()).stream()
|
||||
.noneMatch(sql -> sql.contains("TRUNCATE")), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommitPublishesThePartitionsALaterConnectionReuses() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend first = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(first, session(false), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
materializer.finishCycle(first, true);
|
||||
|
||||
RecordingBackend second = extendedBackend("connection-2");
|
||||
assertThat(materializer.ensureCurrent(second, session(false), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackDropsThePartitionsItStagedSoTheNextQueryReloadsThem() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend first = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(first, session(false), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
materializer.finishCycle(first);
|
||||
|
||||
RecordingBackend second = extendedBackend("connection-2");
|
||||
assertThat(materializer.ensureCurrent(second, session(false), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackOfLaterPartitionsKeepsOnlyTheCommittedBaselineUsable() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend connection = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(connection, session(false), BINDING, "events", DAY_ONE_SQL);
|
||||
materializer.finishCycle(connection, true);
|
||||
materializer.ensureCurrent(connection, session(true), BINDING, "events", DAY_TWO_SQL);
|
||||
|
||||
materializer.finishCycle(connection);
|
||||
|
||||
// the rolled back load of day two is not trusted, and neither is the baseline it was added to
|
||||
assertThat(materializer.ensureCurrent(connection, session(false), BINDING, "events", DAY_TWO_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRollbackToASavepointMakesTheNextQueryInTheTransactionReload() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend connection = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(connection, session(true), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
materializer.finishCycle(connection);
|
||||
|
||||
assertThat(materializer.ensureCurrent(connection, session(true), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommitWithNothingStagedChangesNothing() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend connection = extendedBackend("connection-1");
|
||||
|
||||
materializer.finishCycle(connection, true);
|
||||
|
||||
assertThat(materializer.ensureCurrent(connection, session(false), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropsTheRowsOfAPartitionGlueNoLongerHasInsideATransaction() {
|
||||
Table table = dayPartitionedTable();
|
||||
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
|
||||
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
|
||||
RecordingBackend connection = extendedBackend("connection-1");
|
||||
connection.publicationAllowed = true;
|
||||
materializer.ensureCurrent(connection, session(true), BINDING, "events", null);
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one));
|
||||
int loaded = connection.statements.size();
|
||||
|
||||
assertThat(materializer.ensureCurrent(connection, session(true), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
|
||||
assertThat(connection.statements.subList(loaded, connection.statements.size()).stream().anyMatch(sql -> sql.contains(
|
||||
"DELETE FROM \"analytics\".\"events\" WHERE (\"day\" = CAST('2026-01-02' AS text))")), equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStagedLoadOfOneConnectionDoesNotAffectAnotherTablesOrConnectionsStagedState() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend first = extendedBackend("connection-1");
|
||||
RecordingBackend second = extendedBackend("connection-2");
|
||||
materializer.ensureCurrent(first, session(true), BINDING, "events", DAY_ONE_SQL);
|
||||
|
||||
materializer.finishCycle(second, true);
|
||||
|
||||
assertThat(materializer.ensureCurrent(first, session(true), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCommitDoesNotPublishPartitionsThatAnotherLoadHasSupersededSince() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend staged = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(staged, session(false), BINDING, "events", DAY_ONE_SQL);
|
||||
materializer.invalidateTable(BINDING.clusterKey(), "dev", "analytics", "events");
|
||||
|
||||
materializer.finishCycle(staged, true);
|
||||
|
||||
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTransactionDoesNotTrustPartitionsItLoadedOnceAnotherLoadChangedTheTable() {
|
||||
twoDayPartitions();
|
||||
RecordingBackend inTransaction = extendedBackend("connection-1");
|
||||
materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_ONE_SQL);
|
||||
materializer.invalidateTable(BINDING.clusterKey(), "dev", "analytics", "events");
|
||||
|
||||
assertThat(materializer.ensureCurrent(inTransaction, session(true), BINDING, "events", DAY_ONE_SQL),
|
||||
equalTo(ExternalTableMaterializer.Outcome.LOADED));
|
||||
}
|
||||
|
||||
private void twoDayPartitions() {
|
||||
Table table = dayPartitionedTable();
|
||||
Partition one = dayPartition(table, "2026-01-01", "one/", "e1");
|
||||
Partition two = dayPartition(table, "2026-01-02", "two/", "e2");
|
||||
when(glue.getPartitions("lake", "events")).thenReturn(List.of(one, two));
|
||||
}
|
||||
|
||||
private static RecordingBackend extendedBackend(Object connection) {
|
||||
RecordingBackend extended = new RecordingBackend();
|
||||
extended.publicationAllowed = false;
|
||||
extended.connection = connection;
|
||||
return extended;
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsEveryPartitionWhenTheQueryHasNoPartitionPredicate() {
|
||||
Table table = dayPartitionedTable();
|
||||
|
||||
Reference in new issue
Block a user