mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift): complete Glue external table lifecycle (#5866)
* feat(redshift): complete Glue external table lifecycle * fix(test): use existing frame helper in Spectrum bridge test * fix(redshift): safeguard external catalog lifecycle operations * fix(redshift): shorten spectrum catalog lock waits and reuse test helper
This commit is contained in:
1 parent
ffb3d84bad
commit
c33823bd48
14 files changed
+1042
-60
No files matched your search
+2
-2
@@ -48,8 +48,8 @@ final class ExtendedSpectrumExchange {
|
||||
PortalCursor cursor = cursors.get(portalName);
|
||||
if (cursor == null) {
|
||||
SpectrumInterceptor.Decision decision = interceptor.execute(plan, accountId, database, backend);
|
||||
if (decision instanceof SpectrumInterceptor.Decision.Handled) {
|
||||
forward(client, commandComplete("CREATE EXTERNAL"));
|
||||
if (decision instanceof SpectrumInterceptor.Decision.Handled handled) {
|
||||
forward(client, commandComplete(handled.commandTag()));
|
||||
failed = false;
|
||||
return;
|
||||
}
|
||||
|
||||
+18
-17
@@ -216,9 +216,9 @@ public class RedshiftInterceptingBridge {
|
||||
writeSimpleSpectrumError(new SpectrumReadException("58030", "Unable to prepare external query"));
|
||||
return;
|
||||
}
|
||||
if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Handled) {
|
||||
if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Handled handled) {
|
||||
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
|
||||
write(client.getOutputStream(), commandComplete("CREATE EXTERNAL\0"));
|
||||
write(client.getOutputStream(), commandComplete(handled.commandTag() + "\0"));
|
||||
reportLocalReady();
|
||||
return;
|
||||
}
|
||||
@@ -270,6 +270,22 @@ public class RedshiftInterceptingBridge {
|
||||
// resolve to the stale Spectrum plan in handleBind/handleDescribe/handleExecute.
|
||||
spectrumStatements.remove(parse.statementName());
|
||||
relationalStatements.remove(parse.statementName());
|
||||
if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty()
|
||||
&& !coordinator.isDiscardingUntilSync()) {
|
||||
try {
|
||||
SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), spectrumSession());
|
||||
if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query
|
||||
|| plan instanceof SpectrumInterceptor.Plan.ExternalDdl) {
|
||||
awaitPriorBackendResponses();
|
||||
spectrumStatements.put(parse.statementName(), plan);
|
||||
write(client.getOutputStream(), backendFrame('1', EMPTY_BODY));
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
writeParseSpectrumError(exception);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// After a backend error the backend discards everything up to Sync, so a preparation round trip
|
||||
// would only wait out the socket timeout; forward the Parse and let the backend discard it.
|
||||
if (spectrumInterceptor != null && spectrumInterceptor.preparation() != null
|
||||
@@ -291,21 +307,6 @@ public class RedshiftInterceptingBridge {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty()) {
|
||||
try {
|
||||
SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), spectrumSession());
|
||||
if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query
|
||||
|| plan instanceof SpectrumInterceptor.Plan.ExternalDdl) {
|
||||
awaitPriorBackendResponses();
|
||||
spectrumStatements.put(parse.statementName(), plan);
|
||||
write(client.getOutputStream(), backendFrame('1', EMPTY_BODY));
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
writeParseSpectrumError(exception);
|
||||
return;
|
||||
}
|
||||
}
|
||||
CopyStatementParser.S3Statement statement = parse.parameterTypeOids().isEmpty()
|
||||
? parseS3Statement(parse.sql()) : null;
|
||||
ExtendedQuerySession.Mutation mutation = session.stageParse(parse.statementName(), statement);
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
/** Coordinates Spectrum catalog mutations with readers, including aliases of the same Glue database. */
|
||||
@ApplicationScoped
|
||||
public class ExternalCatalogLocks {
|
||||
private static final Duration DEFAULT_TRANSACTION_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
private final Duration transactionTimeout;
|
||||
private final Map<CatalogKey, ReentrantReadWriteLock> locks = new ConcurrentHashMap<>();
|
||||
|
||||
public ExternalCatalogLocks() {
|
||||
this(DEFAULT_TRANSACTION_TIMEOUT);
|
||||
}
|
||||
|
||||
public ExternalCatalogLocks(Duration transactionTimeout) {
|
||||
this.transactionTimeout = transactionTimeout;
|
||||
}
|
||||
|
||||
public Guard read(ExternalSchemaBinding binding, boolean transactionOpen) {
|
||||
return acquire(binding, false, transactionOpen);
|
||||
}
|
||||
|
||||
public Guard write(ExternalSchemaBinding binding) {
|
||||
return acquire(binding, true, false);
|
||||
}
|
||||
|
||||
private Guard acquire(ExternalSchemaBinding binding, boolean write, boolean transactionOpen) {
|
||||
CatalogKey key = new CatalogKey(binding.accountId(), binding.glueDatabase().toLowerCase(Locale.ROOT));
|
||||
ReentrantReadWriteLock catalog = locks.computeIfAbsent(key, ignored -> new ReentrantReadWriteLock(true));
|
||||
Lock lock = write ? catalog.writeLock() : catalog.readLock();
|
||||
try {
|
||||
if (transactionOpen) {
|
||||
if (!lock.tryLock(transactionTimeout.toNanos(), TimeUnit.NANOSECONDS)) {
|
||||
throw new SpectrumReadException("58030", "Timed out waiting for external catalog access");
|
||||
}
|
||||
} else {
|
||||
lock.lockInterruptibly();
|
||||
}
|
||||
return new Guard(lock);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new SpectrumReadException("58030", "Interrupted while waiting for external catalog access", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private record CatalogKey(String accountId, String databaseName) { }
|
||||
|
||||
public record Guard(Lock lock) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-3
@@ -294,9 +294,22 @@ public class ExternalStatementParser {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
Matcher value = PARTITION_VALUE.matcher(text.substring(open + 1, close).trim() + ",");
|
||||
while (value.find()) {
|
||||
values.put(identifier(value.group(1)), value.group(2).replace("''", "'"));
|
||||
String keys = text.substring(open + 1, close).trim();
|
||||
Matcher value = PARTITION_VALUE.matcher(keys);
|
||||
int position = 0;
|
||||
while (position < keys.length()) {
|
||||
if (!value.region(position, keys.length()).lookingAt()) {
|
||||
throw new SpectrumSqlException("42601", "Malformed partition key list");
|
||||
}
|
||||
String name = identifier(value.group(1));
|
||||
if (values.keySet().stream().anyMatch(existing -> existing.equalsIgnoreCase(name))) {
|
||||
throw new SpectrumSqlException("42601", "Duplicate partition key: " + name);
|
||||
}
|
||||
values.put(name, value.group(2).replace("''", "'"));
|
||||
position = value.end();
|
||||
if (position == keys.length() && keys.endsWith(",")) {
|
||||
throw new SpectrumSqlException("42601", "Malformed partition key list");
|
||||
}
|
||||
}
|
||||
if (values.isEmpty()) {
|
||||
return List.of();
|
||||
|
||||
+48
-3
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -60,6 +61,7 @@ public class ExternalTableMaterializer {
|
||||
private final S3Service s3Service;
|
||||
private final IamService iamService;
|
||||
private final EmulatorConfig config;
|
||||
private final ExternalCatalogLocks catalogLocks;
|
||||
private final ConcurrentHashMap<String, String> fingerprints = new ConcurrentHashMap<>();
|
||||
/** Column definitions each loaded table was created with, to tell a data reload from a schema change. */
|
||||
private final ConcurrentHashMap<String, String> schemaSignatures = new ConcurrentHashMap<>();
|
||||
@@ -94,15 +96,34 @@ public class ExternalTableMaterializer {
|
||||
|
||||
public ExternalTableMaterializer(FlociDuckClient duckClient, GlueService glueService, S3Service s3Service,
|
||||
IamService iamService, EmulatorConfig config) {
|
||||
this(duckClient, glueService, s3Service, iamService, config, new ExternalCatalogLocks());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public ExternalTableMaterializer(FlociDuckClient duckClient, GlueService glueService, S3Service s3Service,
|
||||
IamService iamService, EmulatorConfig config, ExternalCatalogLocks catalogLocks) {
|
||||
this.duckClient = duckClient;
|
||||
this.glueService = glueService;
|
||||
this.s3Service = s3Service;
|
||||
this.iamService = iamService;
|
||||
this.config = config;
|
||||
this.catalogLocks = catalogLocks;
|
||||
}
|
||||
|
||||
ExternalCatalogLocks catalogLocks() {
|
||||
return catalogLocks;
|
||||
}
|
||||
|
||||
public Outcome ensureCurrent(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
String tableName) {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
|
||||
session.inTransaction() || !backend.permitsCachePublication())) {
|
||||
return ensureCurrentLocked(backend, session, binding, tableName);
|
||||
}
|
||||
}
|
||||
|
||||
private Outcome ensureCurrentLocked(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
String tableName) {
|
||||
Table table;
|
||||
try {
|
||||
table = RequestScopes.callAs(session.accountId(), () -> glueService.getTable(binding.glueDatabase(), tableName));
|
||||
@@ -211,6 +232,20 @@ public class ExternalTableMaterializer {
|
||||
forgetMatching(key -> key.equals(clusterKey + "|" + databaseName + "|" + schemaName + "|" + tableName));
|
||||
}
|
||||
|
||||
/** Reloads data after a catalog change without dropping the table's grants and dependent views. */
|
||||
public void invalidateTable(String clusterKey, String databaseName, String schemaName, String tableName) {
|
||||
String key = clusterKey + "|" + databaseName + "|" + schemaName + "|" + tableName;
|
||||
ReentrantLock lock = locks.computeIfAbsent(key, ignored -> new ReentrantLock());
|
||||
lock.lock();
|
||||
try {
|
||||
fingerprints.remove(key);
|
||||
latestLoads.remove(key);
|
||||
pendingLoads.values().forEach(loads -> loads.remove(key));
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/** Forgets every table of one external schema, so a dropped and recreated schema is reloaded. */
|
||||
public void forgetSchema(String clusterKey, String databaseName, String schemaName) {
|
||||
String prefix = schemaPrefix(clusterKey, databaseName, schemaName);
|
||||
@@ -218,9 +253,19 @@ public class ExternalTableMaterializer {
|
||||
}
|
||||
|
||||
private void forgetMatching(Predicate<String> matches) {
|
||||
fingerprints.keySet().removeIf(matches);
|
||||
schemaSignatures.keySet().removeIf(matches);
|
||||
latestLoads.keySet().removeIf(matches);
|
||||
locks.forEach((key, lock) -> {
|
||||
if (matches.test(key)) {
|
||||
lock.lock();
|
||||
try {
|
||||
fingerprints.remove(key);
|
||||
schemaSignatures.remove(key);
|
||||
latestLoads.remove(key);
|
||||
pendingLoads.values().forEach(loads -> loads.remove(key));
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Keep locks: removing a held lock lets another thread create a second lock for the same table.
|
||||
}
|
||||
|
||||
|
||||
+5
-2
@@ -89,7 +89,7 @@ public final class SpectrumInterceptor {
|
||||
switch (plan) {
|
||||
case Plan.ExternalDdl(String sql, SpectrumSession session) -> {
|
||||
if (preparation.prepare(sql, session, new PostgresBackendSession(backend))) {
|
||||
return new Decision.Handled();
|
||||
return new Decision.Handled(preparation.commandTag(sql));
|
||||
}
|
||||
return execute(plan(sql, accountId, databaseName), accountId, databaseName, backend);
|
||||
}
|
||||
@@ -145,7 +145,10 @@ public final class SpectrumInterceptor {
|
||||
}
|
||||
|
||||
public sealed interface Decision permits Decision.Handled, Decision.Forward, Decision.Rewritten {
|
||||
record Handled() implements Decision {
|
||||
record Handled(String commandTag) implements Decision {
|
||||
public Handled() {
|
||||
this("CREATE EXTERNAL");
|
||||
}
|
||||
}
|
||||
|
||||
record Forward() implements Decision {
|
||||
|
||||
+198
-13
@@ -4,9 +4,13 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.glue.GlueService;
|
||||
import io.github.hectorvent.floci.services.glue.model.Database;
|
||||
import io.github.hectorvent.floci.services.glue.model.Partition;
|
||||
import io.github.hectorvent.floci.services.glue.model.Table;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -24,15 +28,24 @@ public class SpectrumQueryPreparation {
|
||||
private final ExternalStatementParser parser;
|
||||
private final GlueService glue;
|
||||
private final ExternalMetadataWriter metadata;
|
||||
private final ExternalCatalogLocks catalogLocks;
|
||||
private final Map<BackendSql, List<ExternalSchemaBinding>> pendingBindings = new ConcurrentHashMap<>();
|
||||
|
||||
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
|
||||
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata) {
|
||||
this(registry, materializer, parser, glue, metadata, new ExternalCatalogLocks());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer,
|
||||
ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata,
|
||||
ExternalCatalogLocks catalogLocks) {
|
||||
this.registry = registry;
|
||||
this.materializer = materializer;
|
||||
this.parser = parser;
|
||||
this.glue = glue;
|
||||
this.metadata = metadata;
|
||||
this.catalogLocks = catalogLocks;
|
||||
}
|
||||
|
||||
public boolean prepare(String sql, SpectrumSession session, BackendSql backend) {
|
||||
@@ -57,10 +70,24 @@ public class SpectrumQueryPreparation {
|
||||
}
|
||||
|
||||
public boolean handlesDdl(String sql, SpectrumSession session) {
|
||||
Optional<ExternalStatement> statement = parser.parse(sql);
|
||||
return statement.orElse(null) instanceof ExternalStatement.CreateSchema
|
||||
|| statement.orElse(null) instanceof ExternalStatement.CreateTable table
|
||||
&& (session.inTransaction() || bindings(session).containsKey(table.schemaName()));
|
||||
ExternalStatement statement = parser.parse(sql).orElse(null);
|
||||
return switch (statement) {
|
||||
case ExternalStatement.CreateSchema ignored -> true;
|
||||
case ExternalStatement.CreateTable table -> session.inTransaction() || bindings(session).containsKey(table.schemaName());
|
||||
case ExternalStatement.AddPartitions partitions -> bindings(session).containsKey(partitions.schemaName());
|
||||
case ExternalStatement.DropTable table -> bindings(session).containsKey(table.schemaName());
|
||||
case ExternalStatement.DropSchema schema -> bindings(session).containsKey(schema.schemaName());
|
||||
case null -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public String commandTag(String sql) {
|
||||
return switch (parser.parse(sql).orElse(null)) {
|
||||
case ExternalStatement.AddPartitions ignored -> "ALTER TABLE";
|
||||
case ExternalStatement.DropTable ignored -> "DROP TABLE";
|
||||
case ExternalStatement.DropSchema ignored -> "DROP SCHEMA";
|
||||
case null, default -> "CREATE EXTERNAL";
|
||||
};
|
||||
}
|
||||
|
||||
private boolean prepareInScope(String sql, SpectrumSession session, BackendSql backend) {
|
||||
@@ -75,10 +102,31 @@ public class SpectrumQueryPreparation {
|
||||
}
|
||||
if (statement.orElse(null) instanceof ExternalStatement.CreateTable table && bindings.containsKey(table.schemaName())) {
|
||||
ExternalSchemaBinding binding = bindings.get(table.schemaName());
|
||||
glue.createTable(binding.glueDatabase(), GlueTableBuilder.toGlueTable(table));
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.write(binding)) {
|
||||
requireCurrentBinding(session, binding);
|
||||
glue.createTable(binding.glueDatabase(), GlueTableBuilder.toGlueTable(table));
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
switch (statement.orElse(null)) {
|
||||
case ExternalStatement.AddPartitions partitions when bindings.containsKey(partitions.schemaName()) -> {
|
||||
rejectTransaction(session);
|
||||
addPartitions(partitions, bindings.get(partitions.schemaName()), session, backend);
|
||||
return true;
|
||||
}
|
||||
case ExternalStatement.DropTable table when bindings.containsKey(table.schemaName()) -> {
|
||||
rejectTransaction(session);
|
||||
dropTable(table, bindings.get(table.schemaName()), session, backend);
|
||||
return true;
|
||||
}
|
||||
case ExternalStatement.DropSchema schema when bindings.containsKey(schema.schemaName()) -> {
|
||||
rejectTransaction(session);
|
||||
dropSchema(schema, bindings.get(schema.schemaName()), session, backend);
|
||||
return true;
|
||||
}
|
||||
case null, default -> { }
|
||||
}
|
||||
Optional<ExternalReferenceScanner.Reference> write = ExternalReferenceScanner.writeTarget(sql, bindings.keySet());
|
||||
if (write.isPresent()) {
|
||||
throw new SpectrumSqlException("0A000", "Writes to external relation \""
|
||||
@@ -87,18 +135,155 @@ public class SpectrumQueryPreparation {
|
||||
Set<String> refreshed = new HashSet<>();
|
||||
for (ExternalReferenceScanner.Reference reference : ExternalReferenceScanner.scan(sql, bindings.keySet())) {
|
||||
ExternalSchemaBinding binding = bindings.get(reference.schema());
|
||||
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table());
|
||||
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
|
||||
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
|
||||
+ "." + reference.table() + "\" does not exist");
|
||||
}
|
||||
if (outcome == ExternalTableMaterializer.Outcome.LOADED && refreshed.add(binding.schemaName())) {
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.read(binding,
|
||||
session.inTransaction() || !backend.permitsCachePublication())) {
|
||||
requireCurrentBinding(session, binding);
|
||||
ExternalTableMaterializer.Outcome outcome = materializer.ensureCurrent(backend, session, binding, reference.table());
|
||||
if (outcome == ExternalTableMaterializer.Outcome.NOT_EXTERNAL) {
|
||||
throw new SpectrumSqlException("42P01", "external relation \"" + reference.schema()
|
||||
+ "." + reference.table() + "\" does not exist");
|
||||
}
|
||||
if (outcome == ExternalTableMaterializer.Outcome.LOADED && refreshed.add(binding.schemaName())) {
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void rejectTransaction(SpectrumSession session) {
|
||||
if (session.inTransaction()) {
|
||||
throw new SpectrumSqlException("25001", "External catalog changes cannot run inside a transaction block");
|
||||
}
|
||||
}
|
||||
|
||||
private void addPartitions(ExternalStatement.AddPartitions statement, ExternalSchemaBinding binding,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.write(binding)) {
|
||||
requireCurrentBinding(session, binding);
|
||||
addPartitionsLocked(statement, binding, session, backend);
|
||||
}
|
||||
}
|
||||
|
||||
private void addPartitionsLocked(ExternalStatement.AddPartitions statement, ExternalSchemaBinding binding,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
Table table = glue.getTable(binding.glueDatabase(), statement.tableName());
|
||||
if (table.getPartitionKeys() == null || table.getPartitionKeys().isEmpty()) {
|
||||
throw new SpectrumSqlException("22023", "External table has no partition keys");
|
||||
}
|
||||
List<Partition> requested = statement.partitions().stream()
|
||||
.map(spec -> GlueTableBuilder.toGluePartition(table, spec)).toList();
|
||||
Set<List<String>> values = new HashSet<>();
|
||||
for (Partition partition : glue.getPartitions(binding.glueDatabase(), statement.tableName())) {
|
||||
values.add(partition.getValues());
|
||||
}
|
||||
List<Partition> additions = new ArrayList<>();
|
||||
for (Partition partition : requested) {
|
||||
if (values.add(partition.getValues())) {
|
||||
additions.add(partition);
|
||||
} else if (!statement.ifNotExists()) {
|
||||
throw new SpectrumSqlException("42710", "Partition already exists: " + partition.getValues());
|
||||
}
|
||||
}
|
||||
requireSchemaOwner(backend, binding.schemaName());
|
||||
List<Partition> created = new ArrayList<>();
|
||||
try {
|
||||
for (Partition partition : additions) {
|
||||
glue.createPartition(binding.glueDatabase(), statement.tableName(), partition);
|
||||
created.add(partition);
|
||||
}
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
} catch (RuntimeException failure) {
|
||||
for (Partition partition : created.reversed()) {
|
||||
try {
|
||||
glue.deletePartition(binding.glueDatabase(), statement.tableName(), partition.getValues());
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
LOG.warnv(cleanupFailure, "Unable to undo partition {0} of {1}.{2}",
|
||||
partition.getValues(), binding.glueDatabase(), statement.tableName());
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
} finally {
|
||||
materializer.invalidateTable(session.clusterKey(), session.databaseName(), binding.schemaName(), statement.tableName());
|
||||
}
|
||||
}
|
||||
|
||||
private void dropTable(ExternalStatement.DropTable statement, ExternalSchemaBinding binding,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.write(binding)) {
|
||||
requireCurrentBinding(session, binding);
|
||||
dropTableLocked(statement, binding, session, backend);
|
||||
}
|
||||
}
|
||||
|
||||
private void dropTableLocked(ExternalStatement.DropTable statement, ExternalSchemaBinding binding,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
boolean exists = true;
|
||||
try {
|
||||
glue.getTable(binding.glueDatabase(), statement.tableName());
|
||||
} catch (AwsException exception) {
|
||||
if (!statement.ifExists() || !"EntityNotFoundException".equals(exception.getErrorCode())) {
|
||||
throw exception;
|
||||
}
|
||||
exists = false;
|
||||
}
|
||||
requireSchemaOwner(backend, binding.schemaName());
|
||||
// Cold tables have no PostgreSQL relation. Check any cached relation's dependencies before deleting Glue metadata.
|
||||
backend.execute("DROP TABLE IF EXISTS " + ExternalTableMaterializer.quote(binding.schemaName()) + "."
|
||||
+ ExternalTableMaterializer.quote(statement.tableName()) + (statement.cascade() ? " CASCADE" : " RESTRICT"));
|
||||
materializer.forget(session.clusterKey(), session.databaseName(), binding.schemaName(), statement.tableName());
|
||||
if (exists) {
|
||||
glue.deleteTable(binding.glueDatabase(), statement.tableName());
|
||||
}
|
||||
metadata.refresh(backend, session.accountId(), binding);
|
||||
}
|
||||
|
||||
private void dropSchema(ExternalStatement.DropSchema statement, ExternalSchemaBinding binding,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
try (ExternalCatalogLocks.Guard ignored = catalogLocks.write(binding)) {
|
||||
requireCurrentBinding(session, binding);
|
||||
requireSchemaOwner(backend, binding.schemaName());
|
||||
if (!statement.cascade() && hasGlueTables(binding)) {
|
||||
throw new SpectrumSqlException("2BP01", "Cannot drop external schema because it contains external tables");
|
||||
}
|
||||
// One implicit PostgreSQL transaction keeps the local schema and its SVV metadata in sync.
|
||||
backend.execute("DROP SCHEMA " + (statement.ifExists() ? "IF EXISTS " : "")
|
||||
+ ExternalTableMaterializer.quote(binding.schemaName()) + (statement.cascade() ? " CASCADE" : " RESTRICT")
|
||||
+ "; " + metadata.purgeSql(binding.schemaName()));
|
||||
registry.unbind(session.accountId(), session.clusterKey(), session.databaseName(), binding.schemaName());
|
||||
materializer.forgetSchema(session.clusterKey(), session.databaseName(), binding.schemaName());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasGlueTables(ExternalSchemaBinding binding) {
|
||||
try {
|
||||
return !glue.getTables(binding.glueDatabase()).isEmpty();
|
||||
} catch (AwsException exception) {
|
||||
if (!"EntityNotFoundException".equals(exception.getErrorCode())) {
|
||||
throw exception;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void requireCurrentBinding(SpectrumSession session, ExternalSchemaBinding binding) {
|
||||
if (!binding.equals(bindings(session).get(binding.schemaName()))) {
|
||||
throw new SpectrumSqlException("42P01", "External schema binding changed; retry the statement");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireSchemaOwner(BackendSql backend, String schemaName) {
|
||||
String body = "BEGIN IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = "
|
||||
+ sqlLiteral(schemaName) + " AND pg_catalog.pg_has_role(current_user, n.nspowner, 'USAGE')) THEN "
|
||||
+ "RAISE EXCEPTION 'Must be owner of external schema' USING ERRCODE = '42501'; END IF; END";
|
||||
backend.execute("DO " + sqlLiteral(body));
|
||||
}
|
||||
|
||||
private static String sqlLiteral(String value) {
|
||||
return "'" + value.replace("'", "''") + "'";
|
||||
}
|
||||
|
||||
private boolean createSchema(ExternalStatement.CreateSchema schema, SpectrumSession session, BackendSql backend) {
|
||||
if (session.inTransaction()) {
|
||||
throw new SpectrumSqlException("0A000", "CREATE EXTERNAL SCHEMA inside a transaction is not supported");
|
||||
|
||||
Reference in new issue
Block a user