mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(redshift): resolve unqualified external functions through the session search_path (#9196)
This commit is contained in:
1 parent
f093a0bc6e
commit
dee5f3c59b
17 files changed
+583
-41
No files matched your search
@@ -155,8 +155,14 @@ public class RedshiftInterceptingBridge {
|
||||
* budget the caller supplies.
|
||||
*/
|
||||
RedshiftInterceptingBridge(Socket client, Socket backend, ReentrantLock backendLock, long ownershipWaitMillis) {
|
||||
this(client, backend, null, null, null, List.of(), null, null, null, null, null, null, backendLock,
|
||||
ownershipWaitMillis, null);
|
||||
this(client, backend, null, backendLock, ownershipWaitMillis);
|
||||
}
|
||||
|
||||
/** For tests: as above, with the Spectrum interceptor whose ownership-gated paths the test drives. */
|
||||
RedshiftInterceptingBridge(Socket client, Socket backend, SpectrumInterceptor spectrumInterceptor,
|
||||
ReentrantLock backendLock, long ownershipWaitMillis) {
|
||||
this(client, backend, null, null, null, List.of(), spectrumInterceptor, "000000000000:c", "dev", null, null,
|
||||
null, backendLock, ownershipWaitMillis, null);
|
||||
}
|
||||
|
||||
private RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService,
|
||||
@@ -364,7 +370,23 @@ public class RedshiftInterceptingBridge {
|
||||
if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty()
|
||||
&& !coordinator.isDiscardingUntilSync()) {
|
||||
try {
|
||||
SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), spectrumSession());
|
||||
SpectrumInterceptor.Plan plan;
|
||||
if (spectrumInterceptor.preparation() != null
|
||||
&& spectrumInterceptor.preparation().needsBackendForDdl(parse.sql(), spectrumSession())) {
|
||||
write(backendOut, new byte[]{'H', 0, 0, 0, 4});
|
||||
SpectrumInterceptor.Plan[] resolved = new SpectrumInterceptor.Plan[1];
|
||||
boolean owned = runWithBackendOwned(() -> {
|
||||
resolved[0] = spectrumInterceptor.plan(parse.sql(), spectrumSession(), relationalBackend);
|
||||
return true;
|
||||
});
|
||||
if (!owned) {
|
||||
// Forwarding would let PostgreSQL drop the stub and leave its binding behind.
|
||||
throw new SpectrumReadException("58030", "Unable to prepare external function DDL");
|
||||
}
|
||||
plan = resolved[0];
|
||||
} else {
|
||||
plan = spectrumInterceptor.plan(parse.sql(), spectrumSession());
|
||||
}
|
||||
if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query
|
||||
|| plan instanceof SpectrumInterceptor.Plan.ExternalDdl) {
|
||||
awaitPriorBackendResponses();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.redshift.spectrum;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface BackendSql {
|
||||
default boolean permitsCachePublication() {
|
||||
@@ -15,6 +16,14 @@ public interface BackendSql {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a query that yields at most one text value: the first column of the first row, or empty when there is no
|
||||
* row or the value is SQL NULL.
|
||||
*/
|
||||
default Optional<String> queryString(String sql) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
void execute(String sql);
|
||||
long copyIn(String copySql, InputStream data);
|
||||
}
|
||||
@@ -27,6 +27,12 @@ public class ExternalFunctionRegistry extends SchemaBindingRegistry<ExternalFunc
|
||||
ExternalFunctionBinding.nameOf(schemaName, functionName, argumentTypes));
|
||||
}
|
||||
|
||||
public boolean hasFunctionNamed(SpectrumSession session, String functionName, List<String> argumentTypes) {
|
||||
return list(session.accountId(), session.clusterKey(), session.databaseName()).stream()
|
||||
.anyMatch(binding -> binding.functionName().equals(functionName)
|
||||
&& binding.argumentTypes().equals(argumentTypes));
|
||||
}
|
||||
|
||||
public void unbindFunction(ExternalFunctionBinding binding) {
|
||||
unbind(binding.accountId(), binding.clusterKey(), binding.databaseName(), binding.bindingName());
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class PostgresBackendSession implements BackendSql {
|
||||
private static final String SQLSTATE_IO = "58030";
|
||||
@@ -21,6 +22,32 @@ public final class PostgresBackendSession implements BackendSql {
|
||||
return backend;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> queryString(String sql) {
|
||||
try {
|
||||
OutputStream output = backend.getOutputStream();
|
||||
output.write(PostgresWireDecoder.encodeQuery(sql));
|
||||
output.flush();
|
||||
return awaitSingleString(new PostgresWireDecoder(backend.getInputStream()));
|
||||
} catch (IOException exception) {
|
||||
abandon(backend, exception);
|
||||
throw new SpectrumReadException(SQLSTATE_IO, "Unable to run a statement on the Redshift backend", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes a backend whose private exchange did not finish. Its replies may still arrive, and the response pump
|
||||
* would forward them to the client as if the client had asked; a closed connection is the one state where
|
||||
* nothing can be misattributed.
|
||||
*/
|
||||
static void abandon(Socket backend, IOException cause) {
|
||||
try {
|
||||
backend.close();
|
||||
} catch (IOException closeFailure) {
|
||||
cause.addSuppressed(closeFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
try {
|
||||
@@ -126,6 +153,44 @@ public final class PostgresBackendSession implements BackendSql {
|
||||
throw new IOException("PostgreSQL closed before ReadyForQuery");
|
||||
}
|
||||
|
||||
private static Optional<String> awaitSingleString(PostgresWireDecoder decoder) throws IOException {
|
||||
SpectrumReadException failure = null;
|
||||
String value = null;
|
||||
boolean seenRow = false;
|
||||
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
|
||||
while (message != null) {
|
||||
if (message.type() == 'D' && !seenRow) {
|
||||
seenRow = true;
|
||||
value = firstColumn(message.body());
|
||||
} else if (message.type() == 'E') {
|
||||
failure = toException(message.body());
|
||||
} else if (message.type() == 'Z') {
|
||||
if (failure != null) {
|
||||
throw failure;
|
||||
}
|
||||
return Optional.ofNullable(value);
|
||||
}
|
||||
message = decoder.nextMessage();
|
||||
}
|
||||
throw new IOException("PostgreSQL closed before ReadyForQuery");
|
||||
}
|
||||
|
||||
static String firstColumn(byte[] body) {
|
||||
if (body == null || body.length < 6) {
|
||||
return null;
|
||||
}
|
||||
int columns = ((body[0] & 0xff) << 8) | (body[1] & 0xff);
|
||||
if (columns < 1) {
|
||||
return null;
|
||||
}
|
||||
int length = ((body[2] & 0xff) << 24) | ((body[3] & 0xff) << 16)
|
||||
| ((body[4] & 0xff) << 8) | (body[5] & 0xff);
|
||||
if (length < 0 || body.length < 6 + length) {
|
||||
return null;
|
||||
}
|
||||
return new String(body, 6, length, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static long rowCount(String tag) {
|
||||
int space = tag.lastIndexOf(' ');
|
||||
if (space < 0) {
|
||||
|
||||
+28
@@ -7,6 +7,7 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Runs preparation without ending the client's transaction or destroying its portals. */
|
||||
@@ -38,6 +39,18 @@ public final class PostgresExtendedBackendSession implements BackendSql {
|
||||
failedUntilSync = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> queryString(String sql) {
|
||||
try {
|
||||
start(sql);
|
||||
closeAndFlush();
|
||||
return awaitSingleStringClosed();
|
||||
} catch (IOException exception) {
|
||||
PostgresBackendSession.abandon(backend, exception);
|
||||
throw failure(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
try {
|
||||
@@ -136,6 +149,21 @@ public final class PostgresExtendedBackendSession implements BackendSql {
|
||||
return tag;
|
||||
}
|
||||
|
||||
private Optional<String> awaitSingleStringClosed() throws IOException {
|
||||
String value = null;
|
||||
boolean seenRow = false;
|
||||
for (int closed = 0; closed < 2;) {
|
||||
Response response = read();
|
||||
if (response.type() == 'D' && !seenRow) {
|
||||
seenRow = true;
|
||||
value = PostgresBackendSession.firstColumn(response.body());
|
||||
} else if (response.type() == '3') {
|
||||
closed++;
|
||||
}
|
||||
}
|
||||
return Optional.ofNullable(value);
|
||||
}
|
||||
|
||||
private void readUntil(char type) throws IOException {
|
||||
Response response;
|
||||
do {
|
||||
|
||||
@@ -45,7 +45,11 @@ public final class SpectrumInterceptor {
|
||||
}
|
||||
|
||||
public Plan plan(String sql, SpectrumSession session) {
|
||||
if (preparation != null && preparation.handlesDdl(sql, session)) {
|
||||
return plan(sql, session, null);
|
||||
}
|
||||
|
||||
public Plan plan(String sql, SpectrumSession session, BackendSql backend) {
|
||||
if (preparation != null && preparation.handlesDdl(sql, session, backend)) {
|
||||
return new Plan.ExternalDdl(sql, session);
|
||||
}
|
||||
if (preparation != null && preparation.referencesExternal(sql, session)) {
|
||||
@@ -55,9 +59,10 @@ public final class SpectrumInterceptor {
|
||||
}
|
||||
|
||||
public Decision intercept(String sql, SpectrumSession session, Socket backend) {
|
||||
Plan plan = plan(sql, session);
|
||||
PostgresBackendSession backendSql = new PostgresBackendSession(backend);
|
||||
Plan plan = plan(sql, session, backendSql);
|
||||
if (plan instanceof Plan.Forward && preparation != null) {
|
||||
preparation.prepare(sql, session, new PostgresBackendSession(backend));
|
||||
preparation.prepare(sql, session, backendSql);
|
||||
}
|
||||
return execute(plan, session.accountId(), session.databaseName(), backend);
|
||||
}
|
||||
|
||||
+58
-11
@@ -33,8 +33,10 @@ public class SpectrumQueryPreparation {
|
||||
private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class);
|
||||
private static final String DUPLICATE_SCHEMA = "42P06";
|
||||
private static final String UNDEFINED_FUNCTION = "42883";
|
||||
/** Where an unqualified function lands: the default search path of a Redshift database resolves to it. */
|
||||
private static final String INVALID_SCHEMA_NAME = "3F000";
|
||||
/** Fallback when checking an unqualified DROP FUNCTION without a live backend session. */
|
||||
private static final String DEFAULT_FUNCTION_SCHEMA = "public";
|
||||
static final String CURRENT_SCHEMA_SQL = "SELECT pg_catalog.current_schema()";
|
||||
private static final Pattern JOIN = Pattern.compile("\\bJOIN\\b", Pattern.CASE_INSENSITIVE);
|
||||
// Each batch is inserted on its own, so a view that groups or aggregates would keep a partial row per batch.
|
||||
private static final Pattern AGGREGATE = Pattern.compile(
|
||||
@@ -175,16 +177,24 @@ public class SpectrumQueryPreparation {
|
||||
externalSchemaNames(schemas, kinesisSchemaNames, mskSchemaNames)).isPresent();
|
||||
}
|
||||
|
||||
public boolean needsBackendForDdl(String sql, SpectrumSession session) {
|
||||
return parser.parse(sql).orElse(null) instanceof ExternalStatement.DropFunction function
|
||||
&& function.schemaName() == null
|
||||
&& functions.hasFunctionNamed(session, function.functionName(), function.argumentTypes());
|
||||
}
|
||||
|
||||
public boolean handlesDdl(String sql, SpectrumSession session) {
|
||||
return handlesDdl(sql, session, null);
|
||||
}
|
||||
|
||||
public boolean handlesDdl(String sql, SpectrumSession session, BackendSql backend) {
|
||||
ExternalStatement statement = parser.parse(sql).orElse(null);
|
||||
return switch (statement) {
|
||||
case ExternalStatement.CreateSchema ignored -> true;
|
||||
case ExternalStatement.CreateKinesisSchema ignored -> true;
|
||||
case ExternalStatement.CreateMskSchema ignored -> true;
|
||||
case ExternalStatement.CreateFunction ignored -> true;
|
||||
case ExternalStatement.DropFunction function -> functions.findFunction(session,
|
||||
schemaOrDefault(function.schemaName()), function.functionName(),
|
||||
function.argumentTypes()).isPresent();
|
||||
case ExternalStatement.DropFunction function -> findFunctionToDrop(function, session, backend).isPresent();
|
||||
case ExternalStatement.CreateTable table -> session.inTransaction()
|
||||
|| bindingsOf(registry, session).containsKey(table.schemaName())
|
||||
|| bindingsOf(kinesisSchemas, session).containsKey(table.schemaName())
|
||||
@@ -556,7 +566,7 @@ public class SpectrumQueryPreparation {
|
||||
private boolean createFunction(ExternalStatement.CreateFunction function, SpectrumSession session,
|
||||
BackendSql backend) {
|
||||
rejectTransaction(session);
|
||||
String schema = schemaOrDefault(function.schemaName());
|
||||
String schema = function.schemaName() != null ? function.schemaName() : currentSchema(backend);
|
||||
ExternalFunctionBinding binding = new ExternalFunctionBinding(session.accountId(), session.clusterKey(),
|
||||
session.databaseName(), schema, function.functionName(), function.argumentTypes(),
|
||||
function.returnType(), function.volatility(), function.lambdaFunction(), function.iamRoleArn(),
|
||||
@@ -583,13 +593,12 @@ public class SpectrumQueryPreparation {
|
||||
}
|
||||
|
||||
private boolean dropFunction(ExternalStatement.DropFunction function, SpectrumSession session, BackendSql backend) {
|
||||
rejectTransaction(session);
|
||||
String schema = schemaOrDefault(function.schemaName());
|
||||
Optional<ExternalFunctionBinding> binding = functions.findFunction(session, schema, function.functionName(),
|
||||
function.argumentTypes());
|
||||
Optional<ExternalFunctionBinding> binding = findFunctionToDrop(function, session, backend);
|
||||
if (binding.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
rejectTransaction(session);
|
||||
String schema = binding.get().schemaName();
|
||||
try {
|
||||
backend.execute(dropStubSql(schema, function.functionName(), function.argumentTypes(),
|
||||
function.ifExists(), function.cascade()));
|
||||
@@ -604,8 +613,46 @@ public class SpectrumQueryPreparation {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String schemaOrDefault(String schemaName) {
|
||||
return schemaName == null ? DEFAULT_FUNCTION_SCHEMA : schemaName;
|
||||
private Optional<ExternalFunctionBinding> findFunctionToDrop(ExternalStatement.DropFunction function,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
if (function.schemaName() != null) {
|
||||
return functions.findFunction(session, function.schemaName(), function.functionName(),
|
||||
function.argumentTypes());
|
||||
}
|
||||
if (!functions.hasFunctionNamed(session, function.functionName(), function.argumentTypes())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (backend == null) {
|
||||
return functions.findFunction(session, DEFAULT_FUNCTION_SCHEMA, function.functionName(),
|
||||
function.argumentTypes());
|
||||
}
|
||||
Optional<String> resolved = backend.queryString(resolveFunctionSchemaSql(
|
||||
function.functionName(), function.argumentTypes()));
|
||||
if (resolved.isPresent()) {
|
||||
return functions.findFunction(session, resolved.get(), function.functionName(), function.argumentTypes());
|
||||
}
|
||||
// The stub may already be gone; check the current schema so a stale binding is cleared when DROP fails (42883).
|
||||
return currentSchemaOf(backend)
|
||||
.flatMap(schema -> functions.findFunction(session, schema, function.functionName(),
|
||||
function.argumentTypes()));
|
||||
}
|
||||
|
||||
private static String currentSchema(BackendSql backend) {
|
||||
return currentSchemaOf(backend).orElseThrow(() -> new SpectrumSqlException(INVALID_SCHEMA_NAME,
|
||||
"no schema has been selected to create in"));
|
||||
}
|
||||
|
||||
/** The session's current schema, empty when the search_path selects none. */
|
||||
private static Optional<String> currentSchemaOf(BackendSql backend) {
|
||||
return backend.queryString(CURRENT_SCHEMA_SQL).filter(schema -> !schema.isEmpty());
|
||||
}
|
||||
|
||||
static String resolveFunctionSchemaSql(String functionName, List<String> argumentTypes) {
|
||||
String signature = ExternalTableMaterializer.quote(functionName)
|
||||
+ "(" + String.join(", ", argumentTypes) + ")";
|
||||
return "SELECT n.nspname FROM pg_catalog.pg_proc p "
|
||||
+ "JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace "
|
||||
+ "WHERE p.oid = pg_catalog.to_regprocedure(" + PostgresWire.quoteLiteral(signature) + ")";
|
||||
}
|
||||
|
||||
private static String stubSql(ExternalStatement.CreateFunction function, String schema, boolean replace) {
|
||||
|
||||
@@ -7,8 +7,10 @@ import org.postgresql.PGConnection;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Optional;
|
||||
|
||||
final class RedshiftDataBackendSql implements BackendSql {
|
||||
private final Connection connection;
|
||||
@@ -23,6 +25,24 @@ final class RedshiftDataBackendSql implements BackendSql {
|
||||
this.execution = execution;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> queryString(String sql) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
if (execution != null) {
|
||||
execution.track(statement);
|
||||
}
|
||||
try (ResultSet rows = statement.executeQuery(sql)) {
|
||||
return rows.next() ? Optional.ofNullable(rows.getString(1)) : Optional.empty();
|
||||
} finally {
|
||||
if (execution != null) {
|
||||
execution.untrack(statement);
|
||||
}
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
throw failure(exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
|
||||
@@ -548,7 +548,10 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
|
||||
}
|
||||
boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find() || CopyJobSql.requiresAutoCommit(sql)
|
||||
|| preparation != null && target.spectrum() != null
|
||||
&& preparation.handlesDdl(sql, target.spectrum());
|
||||
&& (preparation.needsBackendForDdl(sql, target.spectrum())
|
||||
? preparation.handlesDdl(sql, target.spectrum(),
|
||||
new RedshiftDataBackendSql(connection, execution))
|
||||
: preparation.handlesDdl(sql, target.spectrum()));
|
||||
if (autoCommit) {
|
||||
if (session != null && session.inTransaction()) {
|
||||
throw new SQLException("Statement cannot run inside a transaction block", "25001");
|
||||
|
||||
Reference in new issue
Block a user