fix(glue): paginate catalog database, table, partition and version lists (#7827)

This commit is contained in:
galsuchetzky-act authored and GitHub committed 2026-11-11 12:23:16 -04:00
1 parent 3eb01eb8e9
commit aea5c9ad05
11 files changed
+639 -18

No files matched your search

+6 -4
View File
@@ -31,7 +31,7 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske
|--------|-------------|
| CreateDatabase | Creates a database in the local Glue Data Catalog. |
| GetDatabase | Returns a stored Data Catalog database. |
| GetDatabases | Lists databases in the local Glue Data Catalog. |
| GetDatabases | Lists databases in pages using `MaxResults` and `NextToken`. |
| DeleteDatabase | Deletes a database from the local Glue Data Catalog. |
#### Tables
@@ -40,11 +40,11 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske
|--------|-------------|
| CreateTable | Creates a table definition in the local Glue Data Catalog. |
| GetTable | Returns a stored table definition and resolves schema references when possible. |
| GetTables | Lists table definitions for a database. |
| GetTables | Lists table definitions for a database in pages using `MaxResults` and `NextToken`. |
| UpdateTable | Replaces a table definition; the previous version is archived unless `SkipArchive` is set. |
| DeleteTable | Deletes a table definition from a database. |
| BatchDeleteTable | Deletes several tables of a database, reporting the missing ones in `Errors`. |
| GetTableVersions | Lists the current and archived versions of a table, newest first. |
| GetTableVersions | Lists the current and archived versions of a table, newest first, in pages using `MaxResults` and `NextToken`. |
| GetTableVersion | Returns one version by `VersionId`, or the current version when none is given. |
| DeleteTableVersion | Deletes an archived version; the current version cannot be deleted, as on AWS. |
| BatchDeleteTableVersion | Deletes several archived versions, reporting the ones not deleted in `Errors`. |
@@ -55,7 +55,7 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske
| Action | Description |
|--------|-------------|
| CreatePartition | Creates a partition for a Data Catalog table. |
| GetPartitions | Lists partitions stored for a Data Catalog table. With a `Segment`, returns that segment's share of them: each partition is in exactly one of `TotalSegments` (1 to 10) segments; a `Segment` member that is not an integer is a `SerializationException`. AWS documents `SegmentNumber` values from 0 through `TotalSegments` minus 1 and not what a larger one returns, so a `SegmentNumber` of `TotalSegments` or more returning no partitions is Floci's reading. |
| GetPartitions | Lists partitions stored for a Data Catalog table in pages using `MaxResults` and `NextToken`. With a `Segment`, returns that segment's share of them: each partition is in exactly one of `TotalSegments` (1 to 10) segments; a `Segment` member that is not an integer is a `SerializationException`. AWS documents `SegmentNumber` values from 0 through `TotalSegments` minus 1 and not what a larger one returns, so a `SegmentNumber` of `TotalSegments` or more returning no partitions is Floci's reading. |
| BatchDeletePartition | Deletes up to 25 partitions, reporting the ones not found in `Errors`. |
| CreatePartitionIndex | Registers a partition index on a table. Keys must name partition columns, and a table holds at most 3 indexes. The index reports `CREATING` before `ACTIVE`. |
| GetPartitionIndexes | Lists a table's partition indexes, each with its keys resolved to name and type. |
@@ -437,3 +437,5 @@ aws glue list-schema-versions \
--schema-id RegistryName=local-registry,SchemaName=orders \
--endpoint-url $AWS_ENDPOINT_URL
```
Catalog pagination for GetDatabases, GetTables, GetPartitions and GetTableVersions uses opaque continuation cursors ordered by database name, table name, partition values and descending version number respectively. Removing the last returned item or inserting items before its cursor does not invalidate continuation. Table schema references are resolved for the selected page.
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsJsonTimestamp;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.services.glue.model.*;
import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService;
import io.floci.aws.services.glue.schemaregistry.model.Registry;
@@ -90,9 +91,7 @@ public class GlueJsonHandler {
Database db = glueService.getDatabase(name);
yield Response.ok(Map.of("Database", db)).build();
}
case "GetDatabases" -> {
yield Response.ok(Map.of("DatabaseList", glueService.getDatabases())).build();
}
case "GetDatabases" -> handleGetDatabases(request);
case "DeleteDatabase" -> {
String name = request.get("Name").asText();
glueService.deleteDatabase(name, region);
@@ -141,9 +140,13 @@ public class GlueJsonHandler {
glueService.getPartitionIndexes(dbName, tableName))).build();
}
case "GetTables" -> {
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException");
String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException");
String dbName = request.get("DatabaseName").asText();
List<Table> tables = glueService.getTables(dbName).stream().map(GlueService::withReadDefaults).toList();
yield Response.ok(Map.of("TableList", tables)).build();
GlueService.Page<Table> page = glueService.getTables(
dbName, maxResults, nextToken);
List<Table> tables = page.items().stream().map(GlueService::withReadDefaults).toList();
yield Response.ok(pageResponse("TableList", tables, page.nextToken())).build();
}
case "UpdateTable" -> {
String dbName = request.get("DatabaseName").asText();
@@ -153,9 +156,13 @@ public class GlueJsonHandler {
yield Response.ok().build();
}
case "GetTableVersions" -> {
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException");
String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException");
String dbName = request.get("DatabaseName").asText();
String tableName = request.get("TableName").asText();
yield Response.ok(Map.of("TableVersions", glueService.getTableVersions(dbName, tableName))).build();
GlueService.Page<Map<String, Object>> page = glueService.getTableVersions(
dbName, tableName, maxResults, nextToken);
yield Response.ok(pageResponse("TableVersions", page.items(), page.nextToken())).build();
}
case "GetTableVersion" -> {
String dbName = request.get("DatabaseName").asText();
@@ -203,13 +210,16 @@ public class GlueJsonHandler {
case "GetPartition" -> handleGetPartition(request);
case "BatchGetPartition" -> handleBatchGetPartition(request);
case "GetPartitions" -> {
Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException");
String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException");
String dbName = request.get("DatabaseName").asText();
String tableName = request.get("TableName").asText();
String expression = request.path("Expression").asText(null);
GlueService.Segment segment = request.hasNonNull("Segment") ? segment(request.get("Segment")) : null;
List<Partition> partitions = glueService.getPartitions(dbName, tableName, expression, segment).stream()
.map(GlueService::withReadDefaults).toList();
yield Response.ok(Map.of("Partitions", partitions)).build();
GlueService.Page<Partition> page = glueService.getPartitions(dbName, tableName, expression, segment,
maxResults, nextToken);
List<Partition> partitions = page.items().stream().map(GlueService::withReadDefaults).toList();
yield Response.ok(pageResponse("Partitions", partitions, page.nextToken())).build();
}
case "DeletePartition" -> handleDeletePartition(request);
case "BatchDeletePartition" -> handleBatchDeletePartition(request);
@@ -1102,6 +1112,13 @@ public class GlueJsonHandler {
return vn.asLong();
}
private Response handleGetDatabases(JsonNode request) {
GlueService.Page<Database> page = glueService.getDatabases(
Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"),
Pagination.parseNextToken(request, "NextToken", "InvalidInputException"));
return Response.ok(pageResponse("DatabaseList", page.items(), page.nextToken())).build();
}
private Integer readMaxResults(JsonNode request) {
JsonNode node = request.get("MaxResults");
if (node == null || node.isNull()) {
@@ -10,6 +10,8 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.Base64Url;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.StorageBackend;
@@ -62,6 +64,7 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -69,6 +72,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -388,6 +392,12 @@ public class GlueService {
return databases;
}
public Page<Database> getDatabases(Integer maxResults, String nextToken) {
return paginate(() -> getDatabases().stream()
.sorted(Comparator.comparing(Database::getName)).toList(), maxResults, nextToken, 100,
Database::getName, "glue-databases");
}
/**
* Heals a database persisted before CatalogId was modelled. The store is namespaced by
* account, so the reader is always the owning account and the healed value is stable —
@@ -466,6 +476,13 @@ public class GlueService {
return resolved;
}
public Page<Table> getTables(String databaseName, Integer maxResults, String nextToken) {
String prefix = normalizeName(databaseName) + ":";
Page<Table> page = paginate(() -> tableStore.scan(key -> key.startsWith(prefix)),
maxResults, nextToken, 100, Table::getName, "glue-tables:" + prefix);
return new Page<>(page.items().stream().map(this::withResolvedSchemaReference).toList(), page.nextToken());
}
/**
* SearchTables over every table of the catalog. SearchText matches a substring of the name,
* database, description, owner, column names and comments and parameter values, or the whole
@@ -698,6 +715,13 @@ public class GlueService {
.toList();
}
public Page<Map<String, Object>> getTableVersions(String databaseName, String tableName,
Integer maxResults, String nextToken) {
return paginate(() -> getTableVersions(databaseName, tableName), maxResults, nextToken, 100,
version -> String.format("%019d", Long.MAX_VALUE - versionIdAsLong((Table) version.get("Table"))),
"glue-versions:" + tableKey(databaseName, tableName));
}
/** One archived version, or the current table when no VersionId is given, as AWS answers. */
public Map<String, Object> getTableVersion(String databaseName, String tableName, String versionId) {
Table current = getTable(databaseName, tableName);
@@ -953,6 +977,29 @@ public class GlueService {
.toList();
}
public Page<Partition> getPartitions(String databaseName, String tableName, String expression,
Segment segment, Integer maxResults, String nextToken) {
return paginate(() -> getPartitions(databaseName, tableName, expression, segment),
maxResults, nextToken, 1000, GlueService::partitionCursor,
"glue-partitions:" + tableKey(databaseName, tableName));
}
/** Fixed-width UTF-16 digits and terminators preserve the null-first tuple ordering. */
private static String partitionCursor(Partition partition) {
StringBuilder cursor = new StringBuilder();
List<String> values = partition.getValues() == null ? List.of() : partition.getValues();
for (String value : values) {
cursor.append(value == null ? '0' : '1');
if (value != null) {
for (int index = 0; index < value.length(); index++) {
cursor.append(HexFormat.of().toHexDigits(value.charAt(index)));
}
}
cursor.append('/');
}
return cursor.toString();
}
private static void validateSegment(Segment segment) {
if (segment == null) {
return;
@@ -3430,12 +3477,18 @@ public class GlueService {
return paginate(() -> all, maxResults, nextToken, 1000);
}
private <T> Page<T> paginate(Supplier<List<T>> items, Integer maxResults, String nextToken, int maximum,
Function<T, String> cursorOf, String namespace) {
int limit = pageLimit(maxResults, maximum);
PaginatedResult<T> page = Pagination.paginate(items.get(), cursorOf,
limit, nextToken, namespace,
token -> new AwsException("InvalidInputException", "Invalid NextToken", 400));
return new Page<>(page.items(), page.nextToken());
}
private <T> Page<T> paginate(Supplier<List<T>> items, Integer maxResults, String nextToken, int maximum) {
if (maxResults != null && (maxResults < 1 || maxResults > maximum)) {
throw new AwsException("InvalidInputException", "MaxResults must be between 1 and " + maximum, 400);
}
int limit = pageLimit(maxResults, maximum);
List<T> all = items.get();
int limit = maxResults == null ? 100 : maxResults;
int start = 0;
if (nextToken != null && !nextToken.isBlank()) {
try {
@@ -3451,4 +3504,11 @@ public class GlueService {
String newToken = end < all.size() ? String.valueOf(end) : null;
return new Page<>(List.copyOf(all.subList(start, end)), newToken);
}
private static int pageLimit(Integer maxResults, int maximum) {
if (maxResults != null && (maxResults < 1 || maxResults > maximum)) {
throw new AwsException("InvalidInputException", "MaxResults must be between 1 and " + maximum, 400);
}
return maxResults == null ? 100 : maxResults;
}
}
@@ -0,0 +1,29 @@
package io.floci.aws.services.glue;
import io.floci.aws.testing.AwsTestClients;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import java.util.UUID;
import java.util.function.BiConsumer;
final class GlueCatalogPaginationTestSupport {
private GlueCatalogPaginationTestSupport() {
}
static void withCatalog(String account, String prefix, BiConsumer<GlueClient, String> action) {
String database = prefix + UUID.randomUUID().toString().replace("-", "");
try (GlueClient client = AwsTestClients.create(GlueClient.builder(), account, Region.US_EAST_1)) {
client.createDatabase(request -> request.databaseInput(input -> input.name(database)));
try {
action.accept(client, database);
} finally {
client.getTablesPaginator(request -> request.databaseName(database)).stream()
.flatMap(page -> page.tableList().stream()).forEach(table -> client.deleteTable(request -> request
.databaseName(database).name(table.name())));
client.deleteDatabase(request -> request.name(database));
}
}
}
}
@@ -0,0 +1,69 @@
package io.floci.aws.services.glue;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.InvalidInputException;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class GlueCatalogPaginationValidationIntegrationTest {
enum Operation {
DATABASES(100), TABLES(100), VERSIONS(100), PARTITIONS(1000);
final int maximum;
Operation(int maximum) {
this.maximum = maximum;
}
void call(GlueClient client, String database, Integer size, String token) {
switch (this) {
case DATABASES -> client.getDatabases(request -> request.maxResults(size).nextToken(token));
case TABLES -> client.getTables(request -> request.databaseName(database).maxResults(size).nextToken(token));
case VERSIONS -> client.getTableVersions(request -> request.databaseName(database).tableName("example")
.maxResults(size).nextToken(token));
case PARTITIONS -> client.getPartitions(request -> request.databaseName(database).tableName("example")
.maxResults(size).nextToken(token));
}
}
}
static Stream<Arguments> invalidSizes() {
return Stream.of(Operation.values()).flatMap(operation -> Stream.of(-1, 0, operation.maximum + 1)
.map(size -> Arguments.of(operation, size)));
}
static Stream<Arguments> invalidTokens() {
return Stream.of(Operation.values()).flatMap(operation -> Stream.of("not-a-token", "-1", "2147483647")
.map(token -> Arguments.of(operation, token)));
}
@ParameterizedTest
@MethodSource("invalidSizes")
void rejectsSizesOutsideEachOperationsRange(Operation operation, int size) {
assertInvalid(operation, size, null);
}
@ParameterizedTest
@MethodSource("invalidTokens")
void rejectsMalformedTokensForEachOperation(Operation operation, String token) {
assertInvalid(operation, null, token);
}
private static void assertInvalid(Operation operation, Integer size, String token) {
GlueCatalogPaginationTestSupport.withCatalog("741648700614", "validation_", (client, database) -> {
client.createTable(request -> request.databaseName(database).tableInput(input -> input.name("example")));
InvalidInputException failure = assertThrows(InvalidInputException.class,
() -> operation.call(client, database, size, token));
assertEquals(400, failure.statusCode());
});
}
}
@@ -0,0 +1,69 @@
package io.floci.aws.services.glue;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.Database;
import software.amazon.awssdk.services.glue.model.GetDatabasesResponse;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class GlueDatabasesPaginationIntegrationTest {
@Test
void sdkPagesDatabasesWithoutLosingFieldsOrCrossingAccounts() {
String prefix = "page-" + UUID.randomUUID();
List<String> names = List.of(prefix + "-a", prefix + "-b", prefix + "-c");
try (GlueClient client = AwsTestClients.create(GlueClient.builder(), "741648700611", Region.US_EAST_1);
GlueClient foreignAccount = AwsTestClients.create(GlueClient.builder(), "741648700612", Region.US_EAST_1)) {
for (String name : names.reversed()) {
client.createDatabase(request -> request.databaseInput(builder -> builder
.name(name).description("details-" + name)));
}
foreignAccount.createDatabase(request -> request.databaseInput(builder -> builder.name(prefix + "-0")));
try {
assertEquals(names, client.getDatabases(request -> {}).databaseList().stream()
.map(Database::name).sorted().toList());
GetDatabasesResponse first = client.getDatabases(request -> request.maxResults(1));
assertEquals(List.of(names.get(0)), first.databaseList().stream()
.map(Database::name).toList());
assertNotNull(first.nextToken());
assertEquals("details-" + names.getFirst(), first.databaseList().getFirst().description());
assertEquals("741648700611", first.databaseList().getFirst().catalogId());
GetDatabasesResponse second = client.getDatabases(request -> request
.maxResults(1).nextToken(first.nextToken()));
assertEquals(List.of(names.get(1)), second.databaseList().stream()
.map(Database::name).toList());
assertNotNull(second.nextToken());
GetDatabasesResponse last = client.getDatabases(request -> request
.maxResults(1).nextToken(second.nextToken()));
assertEquals(List.of(names.get(2)), last.databaseList().stream()
.map(Database::name).toList());
assertNull(last.nextToken());
assertEquals(names, client.getDatabasesPaginator(request -> request.maxResults(2))
.stream().flatMap(page -> page.databaseList().stream()).map(Database::name).toList());
} finally {
names.forEach(name -> client.deleteDatabase(request -> request.name(name)));
foreignAccount.deleteDatabase(request -> request.name(prefix + "-0"));
}
}
}
@Test
void sdkReadsAnEmptyPageAtTheMaximumPageSizeWithoutAToken() {
try (GlueClient client = AwsTestClients.create(GlueClient.builder(), "741648700613", Region.US_EAST_1)) {
GetDatabasesResponse response = client.getDatabases(request -> request.maxResults(100));
assertTrue(response.databaseList().isEmpty());
assertNull(response.nextToken());
}
}
}
@@ -58,6 +58,79 @@ class GlueJsonHandlerTest {
schemaRegistryService, mapper);
}
@Test
void databasesPageAcrossResultsAndPreserveMetadata() throws Exception {
for (String name : List.of("third", "first", "second")) {
ObjectNode create = mapper.createObjectNode();
create.putObject("DatabaseInput").put("Name", name).put("Description", "description-" + name);
handler.handle("CreateDatabase", create, REGION);
}
JsonNode first = mapper.valueToTree(body(handler.handle("GetDatabases",
mapper.createObjectNode().put("MaxResults", 2), REGION)));
assertEquals(2, first.get("DatabaseList").size());
assertEquals("first", first.get("DatabaseList").get(0).get("Name").asText());
assertEquals("description-first", first.get("DatabaseList").get(0).get("Description").asText());
assertEquals(ACCOUNT_ID, first.get("DatabaseList").get(0).get("CatalogId").asText());
JsonNode last = mapper.valueToTree(body(handler.handle("GetDatabases",
mapper.createObjectNode().put("MaxResults", 2)
.put("NextToken", first.get("NextToken").asText()), REGION)));
assertEquals(1, last.get("DatabaseList").size());
assertEquals("third", last.get("DatabaseList").get(0).get("Name").asText());
assertFalse(last.has("NextToken"));
}
@Test
void databasesUseHundredRowDefault() throws Exception {
for (int index = 0; index < 101; index++) {
ObjectNode create = mapper.createObjectNode();
create.putObject("DatabaseInput").put("Name", "database-%03d".formatted(index));
handler.handle("CreateDatabase", create, REGION);
}
JsonNode first = mapper.valueToTree(body(handler.handle("GetDatabases", mapper.createObjectNode(), REGION)));
assertEquals(100, first.get("DatabaseList").size());
JsonNode last = mapper.valueToTree(body(handler.handle("GetDatabases",
mapper.createObjectNode().put("NextToken", first.get("NextToken").asText()), REGION)));
assertEquals(1, last.get("DatabaseList").size());
assertFalse(last.has("NextToken"));
}
@Test
void databasesRejectInvalidPageSizesAndTokens() {
for (int limit : List.of(-1, 0, 101)) {
AwsException error = assertThrows(AwsException.class, () -> handler.handle("GetDatabases",
mapper.createObjectNode().put("MaxResults", limit), REGION));
assertEquals("InvalidInputException", error.getErrorCode());
}
for (String token : List.of("invalid", "-1", "1")) {
AwsException error = assertThrows(AwsException.class, () -> handler.handle("GetDatabases",
mapper.createObjectNode().put("NextToken", token), REGION));
assertEquals("InvalidInputException", error.getErrorCode());
}
}
@Test
void catalogListsRejectNonIntegerPageSizesAndNonStringTokens() {
for (String action : List.of("GetDatabases", "GetTables", "GetPartitions", "GetTableVersions")) {
for (JsonNode value : List.of(mapper.getNodeFactory().textNode("1"),
mapper.getNodeFactory().numberNode(1.5), mapper.getNodeFactory().numberNode(Long.MAX_VALUE))) {
ObjectNode request = mapper.createObjectNode().put("DatabaseName", "catalog-db").put("TableName", "catalog-table");
request.set("MaxResults", value);
assertEquals("InvalidInputException", assertThrows(AwsException.class,
() -> handler.handle(action, request, REGION)).getErrorCode());
}
assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> handler.handle(action,
mapper.createObjectNode().put("DatabaseName", "catalog-db").put("TableName", "catalog-table").put("NextToken", 0), REGION)).getErrorCode());
}
}
@Test
void databasesReturnEmptyTerminalPage() throws Exception {
JsonNode empty = mapper.valueToTree(body(handler.handle("GetDatabases",
mapper.createObjectNode().put("MaxResults", 100), REGION)));
assertEquals(0, empty.get("DatabaseList").size());
assertFalse(empty.has("NextToken"));
}
private void createDatabaseAndTable(String dbName, String tableName) throws Exception {
ObjectNode createDb = mapper.createObjectNode();
createDb.putObject("DatabaseInput").put("Name", dbName);
@@ -0,0 +1,89 @@
package io.floci.aws.services.glue;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.GetPartitionsResponse;
import software.amazon.awssdk.services.glue.model.Partition;
import java.util.List;
import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class GluePartitionsPaginationIntegrationTest {
@Test
void sdkTraversesAllSelectedPartitionsWithoutDuplicates() {
withPartitions((client, database) -> {
List<List<String>> all = client.getPartitions(request -> request.databaseName(database).tableName("example"))
.partitions().stream().map(Partition::values).toList();
assertEquals(3, all.size());
GetPartitionsResponse first = client.getPartitions(request -> request
.databaseName(database).tableName("example").maxResults(1));
assertEquals(all.subList(0, 1), first.partitions().stream().map(Partition::values).toList());
assertNotNull(first.nextToken());
GetPartitionsResponse second = client.getPartitions(request -> request
.databaseName(database).tableName("example").maxResults(1).nextToken(first.nextToken()));
assertEquals(all.subList(1, 2), second.partitions().stream().map(Partition::values).toList());
assertNotNull(second.nextToken());
GetPartitionsResponse last = client.getPartitions(request -> request
.databaseName(database).tableName("example").maxResults(1).nextToken(second.nextToken()));
assertEquals(all.subList(2, 3), last.partitions().stream().map(Partition::values).toList());
assertNull(last.nextToken());
assertEquals(all, client.getPartitionsPaginator(request -> request
.databaseName(database).tableName("example").maxResults(2)).stream().flatMap(page -> page.partitions().stream())
.map(Partition::values).toList());
GetPartitionsResponse maximum = client.getPartitions(request -> request
.databaseName(database).tableName("example").maxResults(1000));
assertEquals(all, maximum.partitions().stream().map(Partition::values).toList());
assertNull(maximum.nextToken());
});
}
@Test
void expressionSelectionPrecedesPaging() {
withPartitions((client, database) -> {
GetPartitionsResponse response = client.getPartitions(request -> request.databaseName(database)
.tableName("example").expression("day = 'second'").maxResults(1));
assertEquals(List.of(List.of("second")), response.partitions().stream().map(Partition::values).toList());
assertNull(response.nextToken());
});
}
@Test
void segmentSelectionPrecedesPaging() {
withPartitions((client, database) -> {
List<List<String>> all = client.getPartitions(request -> request.databaseName(database)
.tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2)))
.partitions().stream().map(Partition::values).toList();
assertEquals(2, all.size());
GetPartitionsResponse first = client.getPartitions(request -> request.databaseName(database)
.tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2)).maxResults(1));
assertEquals(all.subList(0, 1), first.partitions().stream().map(Partition::values).toList());
assertNotNull(first.nextToken());
GetPartitionsResponse last = client.getPartitions(request -> request.databaseName(database)
.tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2))
.maxResults(1).nextToken(first.nextToken()));
assertEquals(all.subList(1, 2), last.partitions().stream().map(Partition::values).toList());
assertNull(last.nextToken());
});
}
private static void withPartitions(BiConsumer<GlueClient, String> action) {
GlueCatalogPaginationTestSupport.withCatalog("741648700007", "partitions_", (client, database) -> {
client.createTable(request -> request.databaseName(database).tableInput(input -> input.name("example")
.partitionKeys(key -> key.name("day").type("string"))
.storageDescriptor(sd -> sd.columns(column -> column.name("id").type("string")))));
for (String value : List.of("first", "second", "third")) {
client.createPartition(request -> request.databaseName(database).tableName("example")
.partitionInput(input -> input.values(value)
.storageDescriptor(sd -> sd.columns(column -> column.name("id").type("string")))));
}
action.accept(client, database);
});
}
}
@@ -62,6 +62,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class GlueServiceTest {
@@ -90,7 +96,7 @@ class GlueServiceTest {
void setUp() {
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID);
StorageFactory storageFactory = new InMemoryStorageFactory();
schemaRegistryService = new GlueSchemaRegistryService(storageFactory, regionResolver);
schemaRegistryService = spy(new GlueSchemaRegistryService(storageFactory, regionResolver));
kmsService = new KmsService(storageFactory, regionResolver);
databaseStore = new InMemoryStorage<>();
tableStore = new InMemoryStorage<>();
@@ -225,6 +231,99 @@ class GlueServiceTest {
assertEquals("Database cannot be renamed", exception.getMessage());
}
private static Table paginationTable(String name) {
Table table = new Table();
table.setName(name);
return table;
}
@Test
void catalogDatabaseCursorSurvivesDeletionAndShrinking() {
glueService.createDatabase(new Database("db2"));
glueService.createDatabase(new Database("db3"));
GlueService.Page<Database> first = glueService.getDatabases(2, null);
glueService.deleteDatabase("db1");
glueService.deleteDatabase("db2");
GlueService.Page<Database> last = glueService.getDatabases(2, first.nextToken());
assertEquals(List.of("db3"), last.items().stream().map(Database::getName).toList());
assertNull(last.nextToken());
glueService.deleteDatabase("db3");
assertTrue(glueService.getDatabases(2, first.nextToken()).items().isEmpty());
}
@Test
void tableCursorIgnoresInsertionsBeforeAndDeletionOfItsItem() {
for (String name : List.of("alpha", "charlie", "echo")) {
glueService.createTable("db1", paginationTable(name));
}
GlueService.Page<Table> first = glueService.getTables("db1", 2, null);
assertEquals(List.of("alpha", "charlie"), first.items().stream().map(Table::getName).toList());
glueService.deleteTable("db1", "charlie");
glueService.createTable("db1", paginationTable("bravo"));
glueService.createTable("db1", paginationTable("delta"));
GlueService.Page<Table> last = glueService.getTables("db1", 2, first.nextToken());
assertEquals(List.of("delta", "echo"), last.items().stream().map(Table::getName).toList());
assertNull(last.nextToken());
}
@Test
void tableVersionCursorPreservesDescendingOrderAfterAnUpdate() {
glueService.createTable("db1", paginationTable("versioned"));
glueService.updateTable("db1", paginationTable("versioned"), null, false);
glueService.updateTable("db1", paginationTable("versioned"), null, false);
GlueService.Page<Map<String, Object>> first = glueService.getTableVersions("db1", "versioned", 1, null);
assertEquals("2", first.items().getFirst().get("VersionId"));
glueService.updateTable("db1", paginationTable("versioned"), null, false);
GlueService.Page<Map<String, Object>> second = glueService.getTableVersions("db1", "versioned", 1,
first.nextToken());
assertEquals("1", second.items().getFirst().get("VersionId"));
}
@Test
void partitionCursorPreservesTupleOrderAfterItsPrefixShrinks() {
Table table = paginationTable("partitioned");
table.setPartitionKeys(List.of(new Column("group", "string"), new Column("value", "string")));
glueService.createTable("db1", table);
for (List<String> values : List.of(List.of("a", "first"), List.of("a", "second"),
List.of("a0", "x"), List.of("aa", "y"), List.of("é", "z"))) {
Partition partition = new Partition();
partition.setValues(values);
glueService.createPartition("db1", "partitioned", partition);
}
GlueService.Page<Partition> first = glueService.getPartitions("db1", "partitioned", null, null, 2, null);
assertEquals(List.of(List.of("a", "first"), List.of("a", "second")),
first.items().stream().map(Partition::getValues).toList());
glueService.deletePartition("db1", "partitioned", List.of("a", "first"));
glueService.deletePartition("db1", "partitioned", List.of("a", "second"));
for (String value : List.of("middle", "third")) {
Partition partition = new Partition();
partition.setValues(List.of("a", value));
glueService.createPartition("db1", "partitioned", partition);
}
GlueService.Page<Partition> last = glueService.getPartitions("db1", "partitioned", null, null, 100,
first.nextToken());
assertEquals(List.of(List.of("a", "third"), List.of("a0", "x"), List.of("aa", "y"), List.of("é", "z")),
last.items().stream().map(Partition::getValues).toList());
assertNull(last.nextToken());
}
@Test
void tablePagingResolvesOnlyTheReturnedSchemas() {
schemaRegistryService.createRegistry("r1", null, null, REGION);
schemaRegistryService.createSchema(new RegistryId("r1", null),
"users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION);
for (String name : List.of("alpha", "bravo", "charlie")) {
Table table = tableReferencing("r1", "users", null, null);
table.setName(name);
glueService.createTable("db1", table);
}
clearInvocations(schemaRegistryService);
GlueService.Page<Table> first = glueService.getTables("db1", 1, null);
assertEquals("alpha", first.items().getFirst().getName());
assertEquals("id", first.items().getFirst().getStorageDescriptor().getColumns().getFirst().getName());
verify(schemaRegistryService, times(1)).getSchemaVersion(any(), any(), any(), anyBoolean(), any());
}
@Test
void getTableWithValidSchemaReferenceReturnsDerivedColumns() {
schemaRegistryService.createRegistry("r1", null, null, REGION);
@@ -0,0 +1,58 @@
package io.floci.aws.services.glue;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.GetTableVersionsResponse;
import software.amazon.awssdk.services.glue.model.TableVersion;
import java.util.List;
import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class GlueTableVersionsPaginationIntegrationTest {
@Test
void sdkTraversesCurrentAndArchivedVersionsWithoutDuplicates() {
withVersions((client, database) -> {
List<String> all = client.getTableVersions(request -> request.databaseName(database).tableName("example"))
.tableVersions().stream().map(TableVersion::versionId).toList();
assertEquals(3, all.size());
GetTableVersionsResponse first = client.getTableVersions(request -> request
.databaseName(database).tableName("example").maxResults(1));
assertEquals(all.subList(0, 1), first.tableVersions().stream().map(TableVersion::versionId).toList());
assertNotNull(first.nextToken());
GetTableVersionsResponse second = client.getTableVersions(request -> request
.databaseName(database).tableName("example").maxResults(1).nextToken(first.nextToken()));
assertEquals(all.subList(1, 2), second.tableVersions().stream().map(TableVersion::versionId).toList());
assertNotNull(second.nextToken());
GetTableVersionsResponse last = client.getTableVersions(request -> request
.databaseName(database).tableName("example").maxResults(1).nextToken(second.nextToken()));
assertEquals(all.subList(2, 3), last.tableVersions().stream().map(TableVersion::versionId).toList());
assertNull(last.nextToken());
assertEquals(all, client.getTableVersionsPaginator(request -> request
.databaseName(database).tableName("example").maxResults(2)).stream().flatMap(page -> page.tableVersions().stream())
.map(TableVersion::versionId).toList());
GetTableVersionsResponse maximum = client.getTableVersions(request -> request
.databaseName(database).tableName("example").maxResults(100));
assertEquals(all, maximum.tableVersions().stream().map(TableVersion::versionId).toList());
assertNull(maximum.nextToken());
});
}
private static void withVersions(BiConsumer<GlueClient, String> action) {
GlueCatalogPaginationTestSupport.withCatalog("741648700005", "versions_", (client, database) -> {
client.createTable(request -> request.databaseName(database)
.tableInput(input -> input.name("example").description("first")));
client.updateTable(request -> request.databaseName(database)
.tableInput(input -> input.name("example").description("second")));
client.updateTable(request -> request.databaseName(database)
.tableInput(input -> input.name("example").description("third")));
action.accept(client, database);
});
}
}
@@ -0,0 +1,56 @@
package io.floci.aws.services.glue;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.GetTablesResponse;
import software.amazon.awssdk.services.glue.model.Table;
import java.util.List;
import java.util.function.BiConsumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class GlueTablesPaginationIntegrationTest {
@Test
void sdkTraversesAllTablesWithoutDuplicates() {
withTables((client, database) -> {
List<String> all = client.getTables(request -> request.databaseName(database))
.tableList().stream().map(Table::name).toList();
assertEquals(3, all.size());
GetTablesResponse first = client.getTables(request -> request
.databaseName(database).maxResults(1));
assertEquals(all.subList(0, 1), first.tableList().stream().map(Table::name).toList());
assertNotNull(first.nextToken());
GetTablesResponse second = client.getTables(request -> request
.databaseName(database).maxResults(1).nextToken(first.nextToken()));
assertEquals(all.subList(1, 2), second.tableList().stream().map(Table::name).toList());
assertNotNull(second.nextToken());
GetTablesResponse last = client.getTables(request -> request
.databaseName(database).maxResults(1).nextToken(second.nextToken()));
assertEquals(all.subList(2, 3), last.tableList().stream().map(Table::name).toList());
assertNull(last.nextToken());
assertEquals(all, client.getTablesPaginator(request -> request
.databaseName(database).maxResults(2)).stream().flatMap(page -> page.tableList().stream())
.map(Table::name).toList());
GetTablesResponse maximum = client.getTables(request -> request
.databaseName(database).maxResults(100));
assertEquals(all, maximum.tableList().stream().map(Table::name).toList());
assertNull(maximum.nextToken());
});
}
private static void withTables(BiConsumer<GlueClient, String> action) {
GlueCatalogPaginationTestSupport.withCatalog("741648700006", "tables_", (client, database) -> {
for (String name : List.of("first", "second", "third")) {
client.createTable(request -> request.databaseName(database)
.tableInput(input -> input.name(name)));
}
action.accept(client, database);
});
}
}