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
+44
-1
@@ -57,8 +57,12 @@ class RedshiftExternalFunctionIntegrationTest {
|
||||
}
|
||||
|
||||
private static int stubCount(Statement statement, String name) throws SQLException {
|
||||
return stubCount(statement, "public", name);
|
||||
}
|
||||
|
||||
private static int stubCount(Statement statement, String schema, String name) throws SQLException {
|
||||
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM pg_proc p JOIN pg_namespace n "
|
||||
+ "ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = '" + name + "'")) {
|
||||
+ "ON n.oid = p.pronamespace WHERE n.nspname = '" + schema + "' AND p.proname = '" + name + "'")) {
|
||||
rows.next();
|
||||
return rows.getInt(1);
|
||||
}
|
||||
@@ -127,4 +131,43 @@ class RedshiftExternalFunctionIntegrationTest {
|
||||
assertEquals(0, stubCount(statement, "exfunc_tx"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(120)
|
||||
void createsCallsAndDropsUnqualifiedFunctionInSessionSearchPath() throws Exception {
|
||||
clusterId = "it-fn-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE SCHEMA analytics");
|
||||
statement.execute("CREATE SCHEMA other");
|
||||
statement.execute("SET search_path TO analytics");
|
||||
|
||||
statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum"));
|
||||
|
||||
assertTrue(bound("analytics", "exfunc_sum", List.of("integer", "integer")));
|
||||
assertFalse(bound("public", "exfunc_sum", List.of("integer", "integer")));
|
||||
assertEquals(1, stubCount(statement, "analytics", "exfunc_sum"));
|
||||
assertEquals(0, stubCount(statement, "public", "exfunc_sum"));
|
||||
|
||||
SQLException qualifiedCall = assertThrows(SQLException.class,
|
||||
() -> statement.executeQuery("SELECT analytics.exfunc_sum(1, 2)"));
|
||||
assertEquals("0A000", qualifiedCall.getSQLState());
|
||||
|
||||
statement.execute("DROP FUNCTION analytics.exfunc_sum(INT, INT)");
|
||||
assertFalse(bound("analytics", "exfunc_sum", List.of("integer", "integer")));
|
||||
assertEquals(0, stubCount(statement, "analytics", "exfunc_sum"));
|
||||
|
||||
statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum"));
|
||||
statement.execute("SET search_path TO other, analytics");
|
||||
statement.execute("DROP FUNCTION exfunc_sum(INT, INT)");
|
||||
assertFalse(bound("analytics", "exfunc_sum", List.of("integer", "integer")));
|
||||
assertEquals(0, stubCount(statement, "analytics", "exfunc_sum"));
|
||||
|
||||
statement.execute("SET search_path TO nonexistent_schema");
|
||||
SQLException noSchema = assertThrows(SQLException.class,
|
||||
() -> statement.execute(create("exfunc_none", "INT", "lambda_none")));
|
||||
assertEquals("3F000", noSchema.getSQLState());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.ToLongFunction;
|
||||
|
||||
import static io.floci.aws.testing.PostgresDataRows.dataRow;
|
||||
|
||||
/** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */
|
||||
final class FakeCopyBackend {
|
||||
private final Socket socket;
|
||||
@@ -208,19 +210,4 @@ final class FakeCopyBackend {
|
||||
new byte[]{'W'}, PostgresWire.cStringBytes("COPY events, line " + line
|
||||
+ ", column id: \"bad\""), new byte[1]);
|
||||
}
|
||||
|
||||
private static byte[] dataRow(List<String> row) throws Exception {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()});
|
||||
for (String value : row) {
|
||||
if (value == null) {
|
||||
bytes.write(PostgresWire.int32(-1));
|
||||
continue;
|
||||
}
|
||||
byte[] field = value.getBytes(StandardCharsets.UTF_8);
|
||||
bytes.write(PostgresWire.int32(field.length));
|
||||
bytes.write(field);
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
}
|
||||
+66
-6
@@ -2,6 +2,7 @@ package io.floci.aws.services.redshift.proxy;
|
||||
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.redshift.RedshiftAuditLogPublisher;
|
||||
import io.floci.aws.services.redshift.spectrum.BackendSql;
|
||||
import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor;
|
||||
import io.floci.aws.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.floci.aws.services.redshift.spectrum.SpectrumSession;
|
||||
@@ -26,7 +27,10 @@ import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static io.floci.aws.testing.InlineMocks.inlineMock;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
@@ -72,6 +76,15 @@ class RedshiftInterceptingBridgeTest {
|
||||
}
|
||||
|
||||
private void startBridge(SpectrumInterceptor spectrumInterceptor, RedshiftAuditLogPublisher audit) throws IOException {
|
||||
openSockets();
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
|
||||
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null);
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
private void openSockets() throws IOException {
|
||||
clientListener = new ServerSocket(0);
|
||||
testClientEnd = new Socket("localhost", clientListener.getLocalPort());
|
||||
bridgeClientEnd = clientListener.accept();
|
||||
@@ -79,12 +92,6 @@ class RedshiftInterceptingBridgeTest {
|
||||
backendListener = new ServerSocket(0);
|
||||
bridgeBackendEnd = new Socket("localhost", backendListener.getLocalPort());
|
||||
testBackendEnd = backendListener.accept();
|
||||
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
|
||||
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null);
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -669,6 +676,59 @@ class RedshiftInterceptingBridgeTest {
|
||||
Mockito.verify(interceptor, Mockito.never()).execute(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(20)
|
||||
void aRegisteredDropFunctionIsRefusedNotForwardedWhenTheBackendStaysBusy() throws Exception {
|
||||
String sql = "DROP FUNCTION exfunc_sum(INT)";
|
||||
SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class);
|
||||
SpectrumQueryPreparation preparation = Mockito.mock(SpectrumQueryPreparation.class);
|
||||
Mockito.when(interceptor.preparation()).thenReturn(preparation);
|
||||
Mockito.when(preparation.needsBackendForDdl(Mockito.eq(sql), Mockito.any())).thenReturn(true);
|
||||
openSockets();
|
||||
// a held backend lock stands in for a busy backend; the short budget keeps the test from waiting out 2 s
|
||||
ReentrantLock backendLock = new ReentrantLock(true);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, interceptor, backendLock, 100);
|
||||
CountDownLatch held = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Thread holder = Thread.ofVirtual().start(() -> {
|
||||
backendLock.lock();
|
||||
try {
|
||||
held.countDown();
|
||||
release.await();
|
||||
} catch (InterruptedException expected) {
|
||||
// Only an interrupt from outside the test ends the wait early; keep its status.
|
||||
Thread.currentThread().interrupt();
|
||||
} finally {
|
||||
backendLock.unlock();
|
||||
}
|
||||
});
|
||||
assertTrue(held.await(1, TimeUnit.SECONDS));
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
PostgresWireDecoder backendIn = new PostgresWireDecoder(testBackendEnd.getInputStream());
|
||||
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage("drop", sql, List.of());
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeParse(parse, sql));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
|
||||
// the flush the bridge sends to look for the backend's replies is all that reaches it
|
||||
assertEquals('H', backendIn.nextMessage().type());
|
||||
|
||||
InputStream response = testClientEnd.getInputStream();
|
||||
assertEquals('E', response.read());
|
||||
int length = ByteBuffer.wrap(response.readNBytes(4)).getInt();
|
||||
String error = new String(response.readNBytes(length - 4), StandardCharsets.UTF_8);
|
||||
|
||||
release.countDown();
|
||||
holder.join(1000);
|
||||
assertTrue(error.contains("58030"), error);
|
||||
assertTrue(error.contains("Unable to prepare external function DDL"), error);
|
||||
Mockito.verify(interceptor, Mockito.never()).plan(Mockito.anyString(), Mockito.any(SpectrumSession.class),
|
||||
Mockito.any(BackendSql.class));
|
||||
// the Parse itself never reaches the backend, so PostgreSQL cannot drop the stub behind the registry
|
||||
testBackendEnd.setSoTimeout(500);
|
||||
assertThrows(SocketTimeoutException.class, backendIn::nextMessage);
|
||||
}
|
||||
|
||||
private static void skipFrameBody(InputStream in) throws IOException {
|
||||
int length = ByteBuffer.wrap(in.readNBytes(4)).getInt();
|
||||
in.readNBytes(length - 4);
|
||||
|
||||
+124
@@ -9,13 +9,18 @@ import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import static io.floci.aws.testing.PostgresDataRows.dataRow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PostgresBackendSessionTest {
|
||||
|
||||
@@ -269,4 +274,123 @@ class PostgresBackendSessionTest {
|
||||
assertEquals("25P02", error.sqlState());
|
||||
session.onSync();
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryStringReadsFirstColumnOfFirstRowAndHandlesNullAndEmpty() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<Void> server = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
InputStream input = socket.getInputStream();
|
||||
OutputStream output = socket.getOutputStream();
|
||||
// First query returns "analytics".
|
||||
readFrame(input);
|
||||
send(output, 'D', dataRow(List.of("analytics")));
|
||||
send(output, 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
// Second query returns SQL NULL.
|
||||
readFrame(input);
|
||||
send(output, 'D', dataRow(Collections.singletonList(null)));
|
||||
send(output, 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
// Third query returns no rows.
|
||||
readFrame(input);
|
||||
send(output, 'C', "SELECT 0\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(output, 'Z', new byte[]{'I'});
|
||||
return null;
|
||||
}
|
||||
});
|
||||
PostgresBackendSession session = new PostgresBackendSession(backend);
|
||||
assertEquals(Optional.of("analytics"), session.queryString("SELECT pg_catalog.current_schema()"));
|
||||
assertEquals(Optional.empty(), session.queryString("SELECT pg_catalog.current_schema()"));
|
||||
assertEquals(Optional.empty(), session.queryString("SELECT n.nspname FROM pg_proc WHERE false"));
|
||||
server.get();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extendedQueryStringReadsFirstColumnWithoutSync() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<String> messages = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
StringBuilder types = new StringBuilder();
|
||||
Frame frame;
|
||||
do {
|
||||
frame = readFrame(socket.getInputStream());
|
||||
types.append(frame.type());
|
||||
} while (frame.type() != 'H');
|
||||
send(socket.getOutputStream(), '1', new byte[0]);
|
||||
send(socket.getOutputStream(), '2', new byte[0]);
|
||||
send(socket.getOutputStream(), 'D', dataRow(List.of("analytics")));
|
||||
send(socket.getOutputStream(), 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8));
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
send(socket.getOutputStream(), '3', new byte[0]);
|
||||
return types.toString();
|
||||
}
|
||||
});
|
||||
Optional<String> schema = new PostgresExtendedBackendSession(backend)
|
||||
.queryString("SELECT pg_catalog.current_schema()");
|
||||
assertEquals(Optional.of("analytics"), schema);
|
||||
assertEquals("PBECCH", messages.get());
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSimpleLookupThatTimesOutClosesTheBackendSoLateRepliesCannotReachTheClient() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
backend.setSoTimeout(200);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<Void> server = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
readFrame(socket.getInputStream());
|
||||
// never replies: the lookup times out while its answer is still to come
|
||||
assertEquals(-1, socket.getInputStream().read());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
SpectrumReadException error = assertThrows(SpectrumReadException.class,
|
||||
() -> new PostgresBackendSession(backend).queryString("SELECT pg_catalog.current_schema()"));
|
||||
|
||||
assertEquals("58030", error.sqlState());
|
||||
assertTrue(backend.isClosed());
|
||||
server.get();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExtendedLookupThatTimesOutClosesTheBackendSoLateRepliesCannotReachTheClient() throws Exception {
|
||||
try (ServerSocket listener = new ServerSocket(0);
|
||||
Socket backend = new Socket("localhost", listener.getLocalPort())) {
|
||||
backend.setSoTimeout(200);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
Future<Void> server = executor.submit(() -> {
|
||||
try (Socket socket = listener.accept()) {
|
||||
Frame frame;
|
||||
do {
|
||||
frame = readFrame(socket.getInputStream());
|
||||
} while (frame.type() != 'H');
|
||||
// ParseComplete only: the rest of the exchange is still to come when the lookup gives up
|
||||
send(socket.getOutputStream(), '1', new byte[0]);
|
||||
assertEquals(-1, socket.getInputStream().read());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
SpectrumReadException error = assertThrows(SpectrumReadException.class,
|
||||
() -> new PostgresExtendedBackendSession(backend).queryString("SELECT pg_catalog.current_schema()"));
|
||||
|
||||
assertEquals("58030", error.sqlState());
|
||||
assertTrue(backend.isClosed());
|
||||
server.get();
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
@@ -20,6 +20,7 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SpectrumExternalFunctionPreparationTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
@@ -36,6 +37,7 @@ class SpectrumExternalFunctionPreparationTest {
|
||||
void setUp() {
|
||||
functions = new ExternalFunctionRegistry(AccountAwareStorageBackend.<ExternalFunctionBinding>inMemory(ACCOUNT));
|
||||
backend = mock(BackendSql.class);
|
||||
when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("public"));
|
||||
GlueService glue = mock(GlueService.class);
|
||||
KinesisStreamingViews views = new KinesisStreamingViews(
|
||||
new KinesisViewRegistry(AccountAwareStorageBackend.<KinesisViewBinding>inMemory(ACCOUNT)),
|
||||
@@ -231,4 +233,68 @@ class SpectrumExternalFunctionPreparationTest {
|
||||
verify(backend).execute(argThat(sql -> sql.contains("public.exfunc_sum")
|
||||
&& sql.contains("invoking Lambda from SQL is not supported yet")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsUnqualifiedFunctionInTheCurrentSchemaReportedByTheBackend() {
|
||||
when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("analytics"));
|
||||
|
||||
assertThat(preparation.prepare(CREATE, SESSION, backend), equalTo(true));
|
||||
|
||||
verify(backend).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION \"analytics\".\"exfunc_sum\"(integer, integer) ")
|
||||
&& sql.contains("External function analytics.exfunc_sum")));
|
||||
assertThat(bound("analytics", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true));
|
||||
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesUnqualifiedCreateWhenNoSchemaIsSelected() {
|
||||
when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.empty());
|
||||
|
||||
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
|
||||
() -> preparation.prepare(CREATE, SESSION, backend));
|
||||
|
||||
assertThat(error.sqlState(), equalTo("3F000"));
|
||||
verify(backend, never()).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void qualifiedCreateDoesNotAskTheBackendForCurrentSchema() {
|
||||
preparation.prepare("CREATE EXTERNAL FUNCTION \"Sales\".f_now() RETURNS VARCHAR(8) STABLE "
|
||||
+ "LAMBDA 'now' IAM_ROLE '" + ROLE + "'", SESSION, backend);
|
||||
|
||||
verify(backend, never()).queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unqualifiedDropResolvesFunctionAlongSearchPath() {
|
||||
when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("analytics"));
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
String resolveSql = SpectrumQueryPreparation.resolveFunctionSchemaSql("exfunc_sum", List.of("integer", "integer"));
|
||||
when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("other"));
|
||||
when(backend.queryString(resolveSql)).thenReturn(Optional.of("analytics"));
|
||||
|
||||
String drop = "DROP FUNCTION exfunc_sum(INT, INT)";
|
||||
assertThat(preparation.needsBackendForDdl(drop, SESSION), equalTo(true));
|
||||
assertThat(preparation.handlesDdl(drop, SESSION, backend), equalTo(true));
|
||||
assertThat(preparation.prepare(drop, SESSION, backend), equalTo(true));
|
||||
|
||||
verify(backend).execute("DROP FUNCTION \"analytics\".\"exfunc_sum\"(integer, integer) RESTRICT");
|
||||
assertThat(bound("analytics", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unqualifiedDropLeavesOrdinaryFunctionInEarlierSearchPathSchemaToBackend() {
|
||||
preparation.prepare(CREATE, SESSION, backend);
|
||||
|
||||
String resolveSql = SpectrumQueryPreparation.resolveFunctionSchemaSql("exfunc_sum", List.of("integer", "integer"));
|
||||
when(backend.queryString(resolveSql)).thenReturn(Optional.of("analytics"));
|
||||
|
||||
String drop = "DROP FUNCTION exfunc_sum(INT, INT)";
|
||||
assertThat(preparation.handlesDdl(drop, SESSION, backend), equalTo(false));
|
||||
assertThat(preparation.prepare(drop, SESSION, backend), equalTo(false));
|
||||
|
||||
verify(backend, never()).execute(argThat(sql -> sql.startsWith("DROP FUNCTION")));
|
||||
assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true));
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,10 @@ import org.postgresql.copy.CopyManager;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -44,4 +46,20 @@ class RedshiftDataBackendSqlTest {
|
||||
() -> new RedshiftDataBackendSql(connection).execute("SELECT 1"));
|
||||
assertEquals("42501", error.sqlState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryStringReadsFirstColumnAndHandlesNullOrNoRows() throws Exception {
|
||||
Connection connection = mock(Connection.class);
|
||||
Statement statement = mock(Statement.class);
|
||||
ResultSet rows = mock(ResultSet.class);
|
||||
when(connection.createStatement()).thenReturn(statement);
|
||||
when(statement.executeQuery("SELECT pg_catalog.current_schema()")).thenReturn(rows);
|
||||
when(rows.next()).thenReturn(true, true, false);
|
||||
when(rows.getString(1)).thenReturn("analytics", (String) null);
|
||||
|
||||
RedshiftDataBackendSql backend = new RedshiftDataBackendSql(connection);
|
||||
assertEquals(Optional.of("analytics"), backend.queryString("SELECT pg_catalog.current_schema()"));
|
||||
assertEquals(Optional.empty(), backend.queryString("SELECT pg_catalog.current_schema()"));
|
||||
assertEquals(Optional.empty(), backend.queryString("SELECT pg_catalog.current_schema()"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.floci.aws.core.common.PostgresWire;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
/** Builds the body of a PostgreSQL {@code DataRow} message for tests that fake a backend. */
|
||||
public final class PostgresDataRows {
|
||||
|
||||
private PostgresDataRows() {
|
||||
}
|
||||
|
||||
/** One text column per value; a null value is an SQL NULL. */
|
||||
public static byte[] dataRow(List<String> row) {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try {
|
||||
bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()});
|
||||
for (String value : row) {
|
||||
if (value == null) {
|
||||
bytes.write(PostgresWire.int32(-1));
|
||||
continue;
|
||||
}
|
||||
byte[] field = value.getBytes(StandardCharsets.UTF_8);
|
||||
bytes.write(PostgresWire.int32(field.length));
|
||||
bytes.write(field);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// a ByteArrayOutputStream does not fail, so this cannot happen
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user