Skip to content
Open
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 @@ -62,6 +62,13 @@ public abstract class Index implements Serializable {
@Nullable
abstract ImmutableList<String> orderBy();

/**
* The UNNEST clauses of a search index partitioned by repeated values. Each element has the form
* {@code "<column> <alias>"}, matching INFORMATION_SCHEMA.INDEXES.SEARCH_UNNEST.
*/
@Nullable
abstract ImmutableList<String> unnest();

public static Builder builder(Dialect dialect) {
return new AutoValue_Index.Builder().dialect(dialect).nullFiltered(false).unique(false);
}
Expand Down Expand Up @@ -106,6 +113,7 @@ private void prettyPrintPg(Appendable appendable) throws IOException {
.map(c -> c.prettyPrint())
.collect(Collectors.joining(", "));
appendable.append("(").append(indexColumnsString).append(")");
appendable.append(unnestString());

String storingString =
indexColumns().stream()
Expand Down Expand Up @@ -210,6 +218,7 @@ private void prettyPrintGsql(Appendable appendable) throws IOException {
.map(c -> c.prettyPrint())
.collect(Collectors.joining(", "));
appendable.append("(").append(indexColumnsString).append(")");
appendable.append(unnestString());

String storingString =
indexColumns().stream()
Expand Down Expand Up @@ -259,6 +268,37 @@ private void prettyPrintGsql(Appendable appendable) throws IOException {
}
}

/**
* Returns the UNNEST clauses of a search index, e.g. {@code " UNNEST(`Tracks`) AS `Track`"}, or
* an empty string if there are none.
*/
private String unnestString() {
if (unnest() == null || unnest().isEmpty()) {
return "";
}
return unnest().stream()
.map(this::prettyPrintUnnest)
.collect(Collectors.joining(", ", " ", ""));
}

private String prettyPrintUnnest(String unnest) {
// Spanner column names and UNNEST aliases can only contain letters, digits and underscores in
// both dialects, so the last space reliably separates the (possibly dotted) column path from
// the alias.
String trimmed = unnest.trim();
int separator = trimmed.lastIndexOf(' ');
if (separator <= 0) {
throw new IllegalArgumentException(
String.format("Invalid UNNEST clause for index %s: '%s'", name(), unnest));
}
String column = trimmed.substring(0, separator).trim();
String alias = trimmed.substring(separator + 1);
return "UNNEST("
+ quoteIdentifier(column, dialect())
+ ") AS "
+ quoteIdentifier(alias, dialect());
Comment thread
pinthekin marked this conversation as resolved.
Resolved
}

abstract Builder autoToBuilder();

public Builder toBuilder() {
Expand Down Expand Up @@ -328,6 +368,8 @@ public Builder nullFiltered() {

public abstract Builder orderBy(ImmutableList<String> keys);

public abstract Builder unnest(ImmutableList<String> unnest);

abstract Index autoBuild();

public Index build() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,8 @@ Statement listColumnsSQL() {
}

private void listIndexes(Map<String, NavigableMap<String, Index.Builder>> indexes) {
Statement statement = listIndexesSQL();
boolean searchUnnestSupported = isSearchUnnestSupported();
Statement statement = listIndexesSQL(searchUnnestSupported);

ResultSet resultSet = context.executeQuery(statement);
while (resultSet.next()) {
Expand Down Expand Up @@ -512,6 +513,11 @@ private void listIndexes(Map<String, NavigableMap<String, Index.Builder>> indexe
? ImmutableList.<String>builder().addAll(resultSet.getStringList(9)).build()
: null;

ImmutableList<String> searchUnnest =
searchUnnestSupported && !resultSet.isNull(10)
? ImmutableList.copyOf(resultSet.getStringList(10))
: null;

Map<String, Index.Builder> tableIndexes =
indexes.computeIfAbsent(tableName, k -> Maps.newTreeMap());

Expand All @@ -526,17 +532,59 @@ private void listIndexes(Map<String, NavigableMap<String, Index.Builder>> indexe
.type(type)
.partitionBy(searchPartitionBy)
.orderBy(searchOrderBy)
.unnest(searchUnnest)
.filter(filter));
}
}

/**
* Returns whether INFORMATION_SCHEMA.INDEXES has the SEARCH_UNNEST column, which describes the
* UNNEST clauses of search indexes partitioned by repeated values. Older databases and the
* emulator don't have it.
*/
private boolean isSearchUnnestSupported() {
Statement statement;
switch (dialect) {
case GOOGLE_STANDARD_SQL:
statement =
Statement.of(
"SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_CATALOG = '' AND"
+ " c.TABLE_SCHEMA = 'INFORMATION_SCHEMA' AND c.TABLE_NAME = 'INDEXES' AND"
+ " c.COLUMN_NAME = 'SEARCH_UNNEST'");
break;
case POSTGRESQL:
statement =
Statement.of(
"SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS c WHERE"
+ " c.TABLE_SCHEMA = 'information_schema' AND c.TABLE_NAME = 'indexes' AND"
+ " c.COLUMN_NAME = 'search_unnest'");
break;
default:
throw new IllegalArgumentException("Unrecognized dialect: " + dialect);
}
try (ResultSet resultSet = context.executeQuery(statement)) {
boolean supported = resultSet.next() && resultSet.getLong(0) > 0;
if (!supported) {
LOG.info("INFORMATION_SCHEMA.INDEXES.SEARCH_UNNEST is not present");
}
return supported;
}
}

@VisibleForTesting
Statement listIndexesSQL() {
return listIndexesSQL(false);
}

@VisibleForTesting
Statement listIndexesSQL(boolean includeSearchUnnest) {
String searchUnnestColumn = includeSearchUnnest ? ", t.search_unnest" : "";
switch (dialect) {
case GOOGLE_STANDARD_SQL:
return Statement.of(
"SELECT t.table_schema, t.table_name, t.index_name, t.parent_table_name, t.is_unique,"
+ " t.is_null_filtered, t.filter, t.index_type, t.search_partition_by, t.search_order_by"
+ searchUnnestColumn
+ " FROM information_schema.indexes AS t"
+ " WHERE t.table_schema NOT IN"
+ " ('INFORMATION_SCHEMA', 'SPANNER_SYS') AND"
Expand All @@ -546,6 +594,7 @@ Statement listIndexesSQL() {
return Statement.of(
"SELECT t.table_schema, t.table_name, t.index_name, t.parent_table_name, t.is_unique,"
+ " t.is_null_filtered, t.filter, t.index_type, t.search_partition_by, t.search_order_by"
+ searchUnnestColumn
+ " FROM information_schema.indexes AS t "
+ " WHERE t.table_schema NOT IN "
+ " ('information_schema', 'spanner_sys', 'pg_catalog')"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,97 @@ public void testpgSearchIndex() {
+ " INCLUDE (\"data\") PARTITION BY \"userid\" ORDER BY \"orderid\" INTERLEAVE IN \"Users\" WITH (sort_order_sharding=TRUE)"));
}

@Test
public void testArrayPartitionedSearchIndex() {
Index.Builder builder =
Index.builder(Dialect.GOOGLE_STANDARD_SQL)
.name("AlbumsByTracks")
.type("SEARCH")
.table("Albums")
.unnest(ImmutableList.of("Tracks Track", "Genres Genre"))
.partitionBy(ImmutableList.of("Track", "Genre"))
.orderBy(ImmutableList.of("ReleaseTimestamp"));
builder
.columns()
.create()
.name("AlbumTitle_Tokens")
.none()
.endIndexColumn()
.create()
.name("AlbumTitle")
.storing()
.endIndexColumn()
.end();
Index index = builder.build();
assertThat(
index.prettyPrint(),
equalToCompressingWhiteSpace(
"CREATE SEARCH INDEX `AlbumsByTracks` ON `Albums`(`AlbumTitle_Tokens` )"
+ " UNNEST(`Tracks`) AS `Track`, UNNEST(`Genres`) AS `Genre`"
+ " STORING (`AlbumTitle`) PARTITION BY `Track`,`Genre` ORDER BY"
+ " `ReleaseTimestamp`"));
}

@Test
public void testpgArrayPartitionedSearchIndex() {
Index.Builder builder =
Index.builder(Dialect.POSTGRESQL)
.name("albumsbytracks")
.type("SEARCH")
.table("albums")
.unnest(ImmutableList.of("tracks track"))
.partitionBy(ImmutableList.of("track"));
builder
.columns()
.create()
.name("albumtitle_tokens")
.none()
.endIndexColumn()
.create()
.name("albumtitle")
.storing()
.endIndexColumn()
.end();
Index index = builder.build();
assertThat(
index.prettyPrint(),
equalToCompressingWhiteSpace(
"CREATE SEARCH INDEX \"albumsbytracks\" ON \"albums\"(\"albumtitle_tokens\" )"
+ " UNNEST(\"tracks\") AS \"track\" INCLUDE (\"albumtitle\")"
+ " PARTITION BY \"track\""));
}

@Test
public void testSearchIndexUnnestDottedPath() {
// Each part of a dotted UNNEST path is quoted separately.
Index.Builder builder =
Index.builder(Dialect.GOOGLE_STANDARD_SQL)
.name("SingersByCity")
.type("SEARCH")
.table("Singers")
.unnest(ImmutableList.of("SingerInfo.residence City"))
.partitionBy(ImmutableList.of("City"));
builder.columns().create().name("FirstName_Tokens").none().endIndexColumn().end();
assertThat(
builder.build().prettyPrint(),
equalToCompressingWhiteSpace(
"CREATE SEARCH INDEX `SingersByCity` ON `Singers`(`FirstName_Tokens` )"
+ " UNNEST(`SingerInfo`.`residence`) AS `City` PARTITION BY `City`"));
}

@Test
public void testSearchIndexInvalidUnnest() {
Index.Builder builder =
Index.builder(Dialect.GOOGLE_STANDARD_SQL)
.name("AlbumsByTracks")
.type("SEARCH")
.table("Albums")
.unnest(ImmutableList.of("Tracks"));
builder.columns().create().name("AlbumTitle_Tokens").none().endIndexColumn().end();
Index index = builder.build();
assertThrows(IllegalArgumentException.class, index::prettyPrint);
}

@Test
public void testVectorIndex() {
Index.Builder builder =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,61 @@ private SharedTestCase pgSearchIndexes() {
});
}

private SharedTestCase arrayPartitionedSearchIndexes() {
List<String> statements =
Arrays.asList(
"CREATE TABLE `t_arrayPartitionedSearchIndexes_Albums` ("
+ " `AlbumId` STRING(MAX) NOT NULL,"
+ " `AlbumTitle` STRING(MAX),"
+ " `AlbumTitle_Tokens` TOKENLIST AS (TOKENIZE_FULLTEXT(`AlbumTitle`)) HIDDEN,"
+ " `Tracks` ARRAY<STRING(MAX)>,"
+ " ) PRIMARY KEY (`AlbumId` ASC)",
" CREATE SEARCH INDEX `i_arrayPartitionedSearchIndexes_AlbumsByTracks`"
+ " ON `t_arrayPartitionedSearchIndexes_Albums`(`AlbumTitle_Tokens`)"
+ " UNNEST(`Tracks`) AS `Track`"
+ " STORING (`AlbumTitle`)"
+ " PARTITION BY `Track`");

return new SharedTestCase(
statements,
ddl -> {
Table table = ddl.table("t_arrayPartitionedSearchIndexes_Albums");
assertThat(table, notNullValue());
assertThat(table.indexes(), hasSize(1));
assertThat(
table.indexes().get(0),
equalTo(
"CREATE SEARCH INDEX `i_arrayPartitionedSearchIndexes_AlbumsByTracks` ON `t_arrayPartitionedSearchIndexes_Albums`(`AlbumTitle_Tokens` ) UNNEST(`Tracks`) AS `Track` STORING (`AlbumTitle`) PARTITION BY `Track`"));
});
}

private SharedTestCase pgArrayPartitionedSearchIndexes() {
List<String> statements =
Arrays.asList(
"CREATE TABLE \"t_pgArrayPartitionedSearchIndexes_Albums\" ("
+ " \"albumid\" character varying NOT NULL,"
+ " \"albumtitle\" character varying,"
+ " \"albumtitle_tokens\" spanner.tokenlist GENERATED ALWAYS AS (spanner.tokenize_fulltext(albumtitle)) STORED HIDDEN,"
+ " \"tracks\" character varying[],"
+ " PRIMARY KEY (\"albumid\")"
+ " )",
" CREATE SEARCH INDEX \"i_pgArrayPartitionedSearchIndexes_AlbumsByTracks\""
+ " ON \"t_pgArrayPartitionedSearchIndexes_Albums\"(\"albumtitle_tokens\")"
+ " UNNEST (\"tracks\") AS \"track\""
+ " INCLUDE (\"albumtitle\")"
+ " PARTITION BY \"track\"");

return new SharedTestCase(
statements,
ddl -> {
Table table = ddl.table("t_pgArrayPartitionedSearchIndexes_Albums");
assertThat(
table.indexes(),
hasItems(
"CREATE SEARCH INDEX \"i_pgArrayPartitionedSearchIndexes_AlbumsByTracks\" ON \"t_pgArrayPartitionedSearchIndexes_Albums\"(\"albumtitle_tokens\" ) UNNEST(\"tracks\") AS \"track\" INCLUDE (\"albumtitle\") PARTITION BY \"track\""));
});
}

private SharedTestCase vectorIndexes() {
List<String> statements =
Arrays.asList(
Expand Down Expand Up @@ -2163,6 +2218,7 @@ public void sharedInformationSchemaScannerTestGsql() throws Exception {
reserved(),
indexes(),
searchIndexes(),
arrayPartitionedSearchIndexes(),
vectorIndexes(),
foreignKeys(),
checkConstraints(),
Expand Down Expand Up @@ -2204,6 +2260,7 @@ public void sharedInformationSchemaScannerTestPg() throws Exception {
pgInterleavedIn(),
pgReserved(),
pgSearchIndexes(),
pgArrayPartitionedSearchIndexes(),
pgVectorIndexes(),
pgIndexes(),
pgForeignKeys(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,33 @@ public void testListIndexesSQL() {
+ " ORDER BY t.table_name, t.index_name"));
}

@Test
public void testListIndexesSQLWithSearchUnnest() {
assertThat(
googleSQLInfoScanner.listIndexesSQL(true).getSql(),
equalToCompressingWhiteSpace(
"SELECT t.table_schema, t.table_name, t.index_name, t.parent_table_name, t.is_unique,"
+ " t.is_null_filtered, t.filter, t.index_type, t.search_partition_by, t.search_order_by,"
+ " t.search_unnest"
+ " FROM information_schema.indexes AS t"
+ " WHERE t.table_schema NOT IN"
+ " ('INFORMATION_SCHEMA', 'SPANNER_SYS') AND"
+ " (t.index_type='INDEX' OR t.index_type='SEARCH' OR t.index_type='VECTOR') AND t.spanner_is_managed = FALSE"
+ " ORDER BY t.table_name, t.index_name"));

assertThat(
postgresSQLInfoScanner.listIndexesSQL(true).getSql(),
equalToCompressingWhiteSpace(
"SELECT t.table_schema, t.table_name, t.index_name, t.parent_table_name, t.is_unique,"
+ " t.is_null_filtered, t.filter, t.index_type, t.search_partition_by, t.search_order_by,"
+ " t.search_unnest"
+ " FROM information_schema.indexes AS t "
+ " WHERE t.table_schema NOT IN "
+ " ('information_schema', 'spanner_sys', 'pg_catalog')"
+ " AND (t.index_type='INDEX' OR t.index_type='SEARCH' OR t.index_type='ScaNN') AND t.spanner_is_managed = 'NO' "
+ " ORDER BY t.table_name, t.index_name"));
}

@Test
public void testListIndexOptions() {
ReadContext mockContext = mock(ReadContext.class);
Expand Down