Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.beam.sdk.io.gcp.spanner.changestreams.model.PartitionMetadata;
import org.apache.beam.sdk.io.gcp.spanner.changestreams.model.PartitionMetadata.State;
Expand Down Expand Up @@ -83,13 +82,23 @@ public class PartitionMetadataDao {
* @return true if the table exists, false if the table does not exist.
*/
public boolean tableExists() {
final String checkTableExistsStmt =
"SELECT t.table_name FROM information_schema.tables AS t "
+ "WHERE t.table_catalog = '' AND "
+ "t.table_schema = '' AND "
+ "t.table_name = '"
+ metadataTableName
+ "'";
final String checkTableExistsStmt;
if (this.isPostgres()) {
checkTableExistsStmt =
"SELECT t.table_name FROM information_schema.tables AS t "
+ "WHERE t.table_schema = 'public' AND "
+ "t.table_name = '"
+ metadataTableName
+ "'";
} else {
checkTableExistsStmt =
"SELECT t.table_name FROM information_schema.tables AS t "
+ "WHERE t.table_catalog = '' AND "
+ "t.table_schema = '' AND "
+ "t.table_name = '"
+ metadataTableName
+ "'";
}
try (ResultSet queryResultSet =
databaseClient
.singleUseReadOnlyTransaction()
Expand Down Expand Up @@ -681,22 +690,20 @@ private Statement getPartitionsMatchingState(
List<String> composedPartitionTokens, State state) {
Statement statement;
if (this.dialect == Dialect.POSTGRESQL) {
StringBuilder sqlStringBuilder =
new StringBuilder("SELECT * FROM \"" + metadataTableName + "\"");
sqlStringBuilder.append(" WHERE \"");
sqlStringBuilder.append(COLUMN_STATE + "\" = " + "'" + state.toString() + "'");
if (!composedPartitionTokens.isEmpty()) {
sqlStringBuilder.append(" AND \"");
sqlStringBuilder.append(COLUMN_PARTITION_TOKEN);
sqlStringBuilder.append("\"");
sqlStringBuilder.append(" = ANY (Array[");
sqlStringBuilder.append(
composedPartitionTokens.stream()
.map(s -> "'" + s + "'")
.collect(Collectors.joining(",")));
sqlStringBuilder.append("])");
}
statement = Statement.newBuilder(sqlStringBuilder.toString()).build();
statement =
Statement.newBuilder(
"SELECT * FROM \""
+ metadataTableName
+ "\" WHERE \""
+ COLUMN_STATE
+ "\" = $1 AND \""
+ COLUMN_PARTITION_TOKEN
+ "\" = ANY ($2)")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to change the behavior for empty composedPartitionTokens array.
Previously it wouldn't check COLUMN_PARTITION_TOKEN but now I think that it will do ANY() which evaluates to false.

Maybe have a branch on if composedPartitionTokens is empty and have two statements you bind to?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it seems change the behavior. However, this change may be safe

Here is why:

  • Method semantics & all callers in PartitionMetadataDao.java: getPartitionsMatchingState(List composedPartitionTokens, State state) is private and only has two callers:
  1. updateToScheduled(List composedPartitionTokens) (lines 535–557): queries which tokens among composedPartitionTokens are currently in State.CREATED, then loops for (String composedPartitionToken : composedPartitionTokens) to update only those tokens to SCHEDULED. When composedPartitionTokens is empty, that for loop executes 0 iterations and updates nothing. Under the old PostgreSQL code, omitting AND "PartitionToken" = ANY(...) ran SELECT * FROM "" WHERE "State" = 'CREATED' — performing an unnecessary full scan (and taking read locks on all CREATED rows in the table inside a read-write transaction) only to discard every row returned.
  2. updateToRunning(String composedPartitionToken) (lines 564–582): always passes Collections.singletonList(composedPartitionToken) (never empty).
  • Matches the GoogleSQL branch (lines 707–722):

java
"SELECT * FROM " + metadataTableName
+ " WHERE " + COLUMN_PARTITION_TOKEN + " IN UNNEST(@composedPartitionTokens) AND "
+ COLUMN_STATE + " = @State"

In GoogleSQL, passing an empty list binds an empty ARRAY to @composedPartitionTokens, and IN UNNEST([]) evaluates to false (0 rows).

The only reason the original PostgreSQL code had if (!composedPartitionTokens.isEmpty()) was because it used raw SQL string concatenation (= ANY (Array[...])), where an untyped empty literal Array[] (without ::text[]) is a PostgreSQL syntax error (cannot determine type of empty array).
With a typed bound Spanner parameter $2 (Value.stringArray(...)), Spanner PostgreSQL resolves "PartitionToken" = ANY ($2) to the exact same $in_array(STRING, ARRAY) AST as GoogleSQL's IN UNNEST(@composedPartitionTokens) (verified in parameterized_queries.test), cleanly returning 0 rows when $2 is empty.

.bind("p1")
.to(state.toString())
.bind("p2")
.to(Value.stringArray(new ArrayList<>(composedPartitionTokens)))
.build();
} else {
statement =
Statement.newBuilder(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
package org.apache.beam.sdk.io.gcp.spanner.changestreams.dao;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
Expand All @@ -31,7 +33,9 @@
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.Dialect;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.TransactionRunner;
Expand Down Expand Up @@ -406,4 +410,173 @@ public void testExtractTvfName() {
assertEquals("tvf", PartitionMetadataDao.extractTvfName("partitionToken123#tvf"));
assertEquals("", PartitionMetadataDao.extractTvfName("partitionToken123"));
}

@Test
public void testTableExistsGoogleSql() {
ReadOnlyTransaction readOnlyTx = mock(ReadOnlyTransaction.class);
ResultSet resultSet = mock(ResultSet.class);
when(databaseClient.singleUseReadOnlyTransaction()).thenReturn(readOnlyTx);
when(readOnlyTx.executeQuery(any(Statement.class), any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true);

assertTrue(partitionMetadataDao.tableExists());

ArgumentCaptor<Statement> statementCaptor = ArgumentCaptor.forClass(Statement.class);
verify(readOnlyTx).executeQuery(statementCaptor.capture(), any());
assertEquals(
"SELECT t.table_name FROM information_schema.tables AS t "
+ "WHERE t.table_catalog = '' AND "
+ "t.table_schema = '' AND "
+ "t.table_name = '"
+ METADATA_TABLE_NAME
+ "'",
statementCaptor.getValue().getSql());
}

@Test
public void testTableExistsPostgres() {
ReadOnlyTransaction readOnlyTx = mock(ReadOnlyTransaction.class);
ResultSet resultSet = mock(ResultSet.class);
when(databaseClient.singleUseReadOnlyTransaction()).thenReturn(readOnlyTx);
when(readOnlyTx.executeQuery(any(Statement.class), any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(false);

PartitionMetadataDao pgDao =
new PartitionMetadataDao(METADATA_TABLE_NAME, databaseClient, Dialect.POSTGRESQL);
assertTrue(pgDao.tableExists());
assertFalse(pgDao.tableExists());

ArgumentCaptor<Statement> statementCaptor = ArgumentCaptor.forClass(Statement.class);
verify(readOnlyTx, times(2)).executeQuery(statementCaptor.capture(), any());
assertEquals(
"SELECT t.table_name FROM information_schema.tables AS t "
+ "WHERE t.table_schema = 'public' AND "
+ "t.table_name = '"
+ METADATA_TABLE_NAME
+ "'",
statementCaptor.getValue().getSql());
}

@Test
public void testInTransactionContextUpdateToScheduledPostgres() {
PartitionMetadataDao.InTransactionContext pgTransactionContext =
new PartitionMetadataDao.InTransactionContext(
METADATA_TABLE_NAME, transaction, Dialect.POSTGRESQL);
ResultSet resultSet = mock(ResultSet.class);
when(transaction.executeQuery(any(), any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getString(any())).thenReturn(PARTITION_TOKEN);

ArgumentCaptor<Statement> statementCaptor = ArgumentCaptor.forClass(Statement.class);
ArgumentCaptor<ImmutableList<Mutation>> mutations =
ArgumentCaptor.forClass(ImmutableList.class);
doNothing().when(transaction).buffer(mutations.capture());

assertNull(pgTransactionContext.updateToScheduled(Collections.singletonList(PARTITION_TOKEN)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add test coverage of 0 and multiple tokens as well

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — added testInTransactionContextUpdateToScheduledPostgresEmptyTokens (0 tokens) and testInTransactionContextUpdateToScheduledPostgresMultipleTokens (multiple tokens) in 49ac029.


verify(transaction).executeQuery(statementCaptor.capture(), any());
Statement captured = statementCaptor.getValue();
assertEquals(
"SELECT * FROM \""
+ METADATA_TABLE_NAME
+ "\" WHERE \"State\" = $1 AND \"PartitionToken\" = ANY ($2)",
captured.getSql());
assertEquals(State.CREATED.toString(), captured.getParameters().get("p1").getString());
assertEquals(
Collections.singletonList(PARTITION_TOKEN),
captured.getParameters().get("p2").getStringArray());
assertEquals(1, mutations.getValue().size());
}

@Test
public void testInTransactionContextUpdateToScheduledPostgresEmptyTokens() {
PartitionMetadataDao.InTransactionContext pgTransactionContext =
new PartitionMetadataDao.InTransactionContext(
METADATA_TABLE_NAME, transaction, Dialect.POSTGRESQL);
ResultSet resultSet = mock(ResultSet.class);
when(transaction.executeQuery(any(), any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(false);

ArgumentCaptor<Statement> statementCaptor = ArgumentCaptor.forClass(Statement.class);

assertNull(pgTransactionContext.updateToScheduled(Collections.emptyList()));

verify(transaction).executeQuery(statementCaptor.capture(), any());
Statement captured = statementCaptor.getValue();
assertEquals(
"SELECT * FROM \""
+ METADATA_TABLE_NAME
+ "\" WHERE \"State\" = $1 AND \"PartitionToken\" = ANY ($2)",
captured.getSql());
assertEquals(State.CREATED.toString(), captured.getParameters().get("p1").getString());
assertEquals(Collections.emptyList(), captured.getParameters().get("p2").getStringArray());
verify(transaction, times(0)).buffer(any(Iterable.class));
}

@Test
public void testInTransactionContextUpdateToScheduledPostgresMultipleTokens() {
PartitionMetadataDao.InTransactionContext pgTransactionContext =
new PartitionMetadataDao.InTransactionContext(
METADATA_TABLE_NAME, transaction, Dialect.POSTGRESQL);
ResultSet resultSet = mock(ResultSet.class);
when(transaction.executeQuery(any(), any())).thenReturn(resultSet);
when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
when(resultSet.getString(PartitionMetadataAdminDao.COLUMN_PARTITION_TOKEN))
.thenReturn("token1")
.thenReturn("token3");

ArgumentCaptor<Statement> statementCaptor = ArgumentCaptor.forClass(Statement.class);
ArgumentCaptor<ImmutableList<Mutation>> mutations =
ArgumentCaptor.forClass(ImmutableList.class);
doNothing().when(transaction).buffer(mutations.capture());

List<String> inputTokens = ImmutableList.of("token1", "token2", "token3");
assertNull(pgTransactionContext.updateToScheduled(inputTokens));

verify(transaction).executeQuery(statementCaptor.capture(), any());
Statement captured = statementCaptor.getValue();
assertEquals(
"SELECT * FROM \""
+ METADATA_TABLE_NAME
+ "\" WHERE \"State\" = $1 AND \"PartitionToken\" = ANY ($2)",
captured.getSql());
assertEquals(State.CREATED.toString(), captured.getParameters().get("p1").getString());
assertEquals(inputTokens, captured.getParameters().get("p2").getStringArray());

verify(transaction, times(2)).buffer(any(ImmutableList.class));
List<ImmutableList<Mutation>> bufferedBatches = mutations.getAllValues();
assertEquals(2, bufferedBatches.size());
assertEquals(
"token1",
bufferedBatches
.get(0)
.get(0)
.asMap()
.get(PartitionMetadataAdminDao.COLUMN_PARTITION_TOKEN)
.getString());
assertEquals(
State.SCHEDULED.toString(),
bufferedBatches
.get(0)
.get(0)
.asMap()
.get(PartitionMetadataAdminDao.COLUMN_STATE)
.getString());
assertEquals(
"token3",
bufferedBatches
.get(1)
.get(0)
.asMap()
.get(PartitionMetadataAdminDao.COLUMN_PARTITION_TOKEN)
.getString());
assertEquals(
State.SCHEDULED.toString(),
bufferedBatches
.get(1)
.get(0)
.asMap()
.get(PartitionMetadataAdminDao.COLUMN_STATE)
.getString());
}
}
Loading