diff --git a/docs/README.md b/docs/README.md index a28cab84b..e3d0c5eba 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ The documentation is published at **https://snowflake-labs.github.io/pg_lake/**. - [Geospatial](./spatial.md) - [Performance](./performance.md) - [dbt](./dbt.md) +- [External query engines](./external-query-engines.md) **Use cases** - [Sync Postgres tables to Iceberg](./use-case-iceberg-sync.md) diff --git a/docs/concepts.md b/docs/concepts.md index aa5da257d..54636a0a0 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -63,6 +63,10 @@ All three can be used in the same query and the same transaction. `load_from` an `COPY ... FROM` load files into heap or Iceberg tables, and `COPY ... TO` writes any query result back out as files. +A `pg_lake_remote` foreign table reads a table of an +[external query engine](external-query-engines.md), another server that runs DuckDB SQL, instead +of files. + ## What happens when you query When you query an Iceberg table or a data lake file table: diff --git a/docs/external-query-engines.md b/docs/external-query-engines.md new file mode 100644 index 000000000..6e37b68b1 --- /dev/null +++ b/docs/external-query-engines.md @@ -0,0 +1,157 @@ +--- +title: External query engines +parent: User guide +nav_order: 7 +--- + +# External query engines +{: .no_toc } + +pg_lake runs the queries on its tables in pgduck_server. A foreign table of the +`pg_lake_remote` foreign data wrapper is served by another server instead, an *external query +engine*: any server that speaks the PostgreSQL wire protocol and runs DuckDB SQL, the way +pgduck_server does. PostgreSQL plans the query, pg_lake sends the DuckDB SQL for the engine's +tables to the engine, and reads the result rows back. The tables are read-only. + +1. TOC +{:toc} + +## Setting up an engine + +A superuser creates a server for the engine, user mappings with the credentials to connect, +and a foreign table for each table or view on the engine: + +```sql +CREATE SERVER analytics FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=analytics.internal port=5433 dbname=analytics sslmode=verify-full'); + +CREATE USER MAPPING FOR app_user SERVER analytics + OPTIONS (user 'app_user', password 'secret'); + +CREATE FOREIGN TABLE public.hits ( + id bigint, + url text, + event_time timestamptz +) +SERVER analytics +OPTIONS (schema_name 'main', table_name 'hits'); + +GRANT SELECT ON public.hits TO app_user; +``` + +| Object | Option | Description | +|:--|:--|:--| +| Server | `conninfo` | Required. A [libpq connection string](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) or URI for the engine. It cannot contain the `user`, secrets such as `password` or `sslpassword`, or libpq's debug options such as `replication`, since every user can read the options of a server. | +| User mapping | `user` | The user to connect as. | +| User mapping | `password`, `sslpassword` | The password, and the passphrase of the client key. pg_lake takes every option that libpq treats as a secret, which in PostgreSQL 18 also includes `oauth_client_secret`. | +| User mapping | `sslcert`, `sslkey` | A client certificate and key for this user, as files on the PostgreSQL server. Only superusers can set them. | +| User mapping | `password_required` | Whether a non-superuser has to connect with a password, `true` by default. Only superusers can set it to `false`, see [passwords](#passwords). | +| Foreign table | `table_name` | Required. The name of the table or view on the engine. Only superusers can set it, see [privileges](#privileges). | +| Foreign table | `schema_name` | The schema of the table on the engine. Without it, the engine's search path finds the table; DuckDB's default schema is `main`. Only superusers can set it. | + +The user mapping options are added to the server's `conninfo`. Settings that are the same for +every user, such as `sslmode` and `sslrootcert`, go in the `conninfo`. + +## Privileges + +No role has `USAGE` on the `pg_lake_remote` wrapper, so only superusers create its servers. A +superuser can grant `USAGE` on a server, which lets a role create its own user mapping. + +Only superusers can create foreign tables on these servers or change their options, because +`table_name` and `schema_name` decide what the engine reads. DuckDB reads a table name it does +not find in its catalog as a file or URL, such as `'/etc/hosts.csv'` or +`'s3://bucket/data.parquet'`, with the engine's own access to its file system and object +storage, and none of pg_lake's checks, like the `lake_read` role, apply. Grant `SELECT` on the +foreign table to the roles that read it. The owner of a foreign table can rename it, which +does not change the table that it reads. + +pg_lake connects with the user mapping of the user that reads the table: the current user, or, +for a table in a view, the owner of the view, unless the view has `security_invoker` set. This +is the user whose privileges PostgreSQL checks, as with other foreign tables. If that user has +no user mapping for the server, pg_lake uses the `PUBLIC` user mapping. Without either, a +superuser connects with just the server's `conninfo`, and a non-superuser gets an error. Since +a query is sent to the engine as one user, a query that reads a table of a view and the same +table directly as another user is not sent to the engine as a whole. + +The owner of a server can change its `conninfo`, and so point it at another host, which +receives the credentials of every user mapping of the server. Keep servers owned by superusers. + +### Passwords + +As with `postgres_fdw`, a non-superuser has to have a password in the user mapping, and the +engine has to ask for it. Otherwise a role could connect with the engine's `trust` or `peer` +authentication, or with the password file of the PostgreSQL server's operating system user, +as any remote user it names. + +For an engine that runs next to PostgreSQL and only accepts connections from it, for example +on a Unix socket with `trust` authentication as pgduck_server does, a superuser can lift the +requirement: + +```sql +CREATE USER MAPPING FOR PUBLIC SERVER analytics OPTIONS (password_required 'false'); +``` + +Every role that can read a table of the server then queries the engine as the same remote +user, with whatever access the engine gives an unauthenticated connection. Use it only for an +engine that gives all its users the same data, and keep the server and its foreign tables +owned by superusers. + +## Querying + +When all tables of a query are on the same server and read as the same user, pg_lake sends the +whole query to the engine, so joins, aggregates, sorting and `LIMIT` run there, as they do for +Iceberg tables on pgduck_server. Otherwise each table is scanned on its own and PostgreSQL +computes the rest, for example when a query joins an engine table with a heap table, an Iceberg +table, a table of another server, or a view owned by another user. `EXPLAIN (VERBOSE)` shows why +a query was not sent as a whole, such as `Table on another query engine` or +`Table read as another user`. + +`EXPLAIN` shows the server under `Engine: DuckDB`, and the plan that the engine returns for the +query it gets. + +A cancel request or `statement_timeout` also cancels the query on the engine, and interrupts a +connection attempt that hangs. + +`INSERT`, `UPDATE`, `DELETE`, `MERGE`, `COPY ... FROM` and `TRUNCATE` are refused. +`INSERT ... SELECT` from an engine table into an Iceberg table works, but runs in PostgreSQL, +since pgduck_server, which writes the Iceberg table, cannot read the engine's table. + +### Column types + +Columns are matched by name, so the engine's table can have its columns in another order, and +more of them. pg_lake casts each column to the DuckDB type of its declared type, so that the +engine computes with the declared type even if its column has another one: an engine +`INTEGER` declared as `text` is compared and sorted as text. DuckDB drops a cast to the type a +column already has, so filters on columns of the declared type still reach the engine's scan. + +pg_lake only casts types that have an exact DuckDB type. It does not cast `numeric` without a +precision or with more than 38 digits, geometry, arrays, composite types, maps, and types that +DuckDB does not have. The engine has to return these columns in the declared type. + +## What an engine has to provide + +- The PostgreSQL wire protocol, version 3. pg_lake uses the extended query protocol, single-row + mode, and text-format results, rendered in the PostgreSQL text format as pgduck_server renders + them. Query parameters, as in prepared statements, are sent as text without types, and the + query casts each one to its type, so an engine binds them as strings. Errors come back with + their SQLSTATE, and a cancel request cancels the running query. +- DuckDB SQL, including the functions that pg_lake adds to DuckDB, since pg_lake rewrites some + PostgreSQL functions into them: `acosh_pg`, `atanh_pg`, `initcap_pg`, `substring_pg`, + `lake_nth_suffix`, `nullify_any_type`, `to_date`, `uuid_extract_timestamp_pg` and + `uuid_extract_version_pg`, and the macros `lake_regexp_matches`, `generate_series_int`, + `generate_series_int_step` and `jsonb`. It also uses DuckDB's `json` and `icu` extensions, + and `spatial` for geospatial queries. +- `explain (format 'json') `, which returns DuckDB's plan in the second column of one + row, for `EXPLAIN`. +- Only the engine's own tables and views for a table name. An engine must not read a name that + it does not know as a file or URL for the user of a user mapping, as DuckDB does. + +## Limitations + +- Each scan of a query opens its own connection to the engine, and connections are not reused. + Scans do not share a snapshot, so two scans in one query can see different versions of the + engine's data, and the engine's data is not part of PostgreSQL transactions. +- `ANALYZE`, `IMPORT FOREIGN SCHEMA` and a `column_name` option are not supported. The column + names of the foreign table have to match the engine's. +- pg_lake does not check which functions an engine supports. A query that uses a function the + engine lacks fails on the engine. diff --git a/pg_lake_engine/include/pg_lake/pgduck/client.h b/pg_lake_engine/include/pg_lake/pgduck/client.h index 73763bea2..6338298db 100644 --- a/pg_lake_engine/include/pg_lake/pgduck/client.h +++ b/pg_lake_engine/include/pg_lake/pgduck/client.h @@ -20,6 +20,7 @@ #include "libpq-fe.h" +#include "datatype/timestamp.h" #include "nodes/pg_list.h" #define DEFAULT_PGDUCK_SERVER_CONNINFO "host=/tmp port=5332" @@ -37,12 +38,23 @@ typedef struct PGDuckConnection uint32 connectionId; PGconn *conn; + /* foreign server of an external query engine, NULL for pgduck_server */ + char *serverName; + } PGDuckConnection; extern PGDLLEXPORT PGDuckConnection * GetPGDuckConnection(void); extern PGDLLEXPORT PGDuckConnection * GetPGDuckConnectionWithSessionTimeZone(void); extern PGDLLEXPORT PGDuckConnection * TryGetPGDuckConnection(char **errorMessage); +extern PGDLLEXPORT PGDuckConnection * TryGetPGDuckConnectionWithConninfo(const char *conninfo, + const char *serverName, + char **errorMessage); extern PGDLLEXPORT void ReleasePGDuckConnection(PGDuckConnection * pgDuckConnection); +extern PGDLLEXPORT PGconn *ConnectToExternalQueryEngine(const char *conninfo); +extern PGDLLEXPORT void DisconnectFromExternalQueryEngine(PGconn *connection); +#if PG_VERSION_NUM >= 170000 +extern PGDLLEXPORT const char *CancelQueryEngineCommand(PGconn *connection, TimestampTz endtime); +#endif extern PGDLLEXPORT int64 ExecuteCommandInPGDuck(char *query); extern PGDLLEXPORT List *ExecuteCommandsInPGDuck(List *commands); extern PGDLLEXPORT bool ExecuteOptionalCommandInPGDuck(char *command); diff --git a/pg_lake_engine/include/pg_lake/pgduck/query_engine.h b/pg_lake_engine/include/pg_lake/pgduck/query_engine.h index 66a786cf4..63d5145de 100644 --- a/pg_lake_engine/include/pg_lake/pgduck/query_engine.h +++ b/pg_lake_engine/include/pg_lake/pgduck/query_engine.h @@ -22,12 +22,15 @@ #include "pg_lake/pgduck/client.h" /* - * A query engine runs the DuckDB SQL that we generate for a scan. All pg_lake - * tables are served by pgduck_server. + * A query engine runs the DuckDB SQL that we generate for a scan. + * pgduck_server serves all pg_lake tables. A foreign table of the + * pg_lake_remote foreign data wrapper is served by an external query engine, + * identified by its foreign server. * - * An engine is reached as the user that its tables are read as, so a query - * is only sent to one engine when all its tables have the same server and - * user. pgduck_server is the same for every user. + * An external engine is reached with the user mapping of the user that its + * tables are read as, so a query is only sent to one engine when all its + * tables have the same server and user. pgduck_server is the same for every + * user. */ typedef struct QueryEngine { @@ -43,10 +46,15 @@ typedef struct QueryEngine #define PGDUCK_QUERY_ENGINE ((QueryEngine) {InvalidOid, InvalidOid}) +#define PG_LAKE_REMOTE_FDW_NAME "pg_lake_remote" + +extern PGDLLEXPORT bool IsExternalEngineTable(Oid relationId); +extern PGDLLEXPORT bool IsQueryEngineTable(RangeTblEntry *rte); extern PGDLLEXPORT bool QueryEnginesEqual(QueryEngine left, QueryEngine right); extern PGDLLEXPORT QueryEngine GetRelationQueryEngine(Oid relationId, Oid checkAsUser); extern PGDLLEXPORT QueryEngine GetRteQueryEngine(RangeTblEntry *rte, List *rteperminfos); extern PGDLLEXPORT QueryEngine GetQueryEngineForRteList(List *rteList, Oid checkAsUser); extern PGDLLEXPORT QueryEngine GetQueryEngineForQuery(Query *query); +extern PGDLLEXPORT char *GetQueryEngineName(QueryEngine queryEngine); extern PGDLLEXPORT PGDuckConnection * GetQueryEngineConnection(QueryEngine queryEngine, bool setSessionTimeZone); diff --git a/pg_lake_engine/src/pgduck/client.c b/pg_lake_engine/src/pgduck/client.c index 4d154083a..243e0c13b 100644 --- a/pg_lake_engine/src/pgduck/client.c +++ b/pg_lake_engine/src/pgduck/client.c @@ -42,6 +42,9 @@ static void InitializePGDuckClient(void); static void SetupPgDuckConnectionHash(void); +static PGDuckConnection * TrackPGDuckConnection(PGconn *connection, + const char *serverName, + bool releaseExternalFD); static void PGDuckClientTransactionCallback(XactEvent event, void *arg); static void PGDuckClientSubtransactionCallback(SubXactEvent event, @@ -51,7 +54,7 @@ static void PGDuckClientSubtransactionCallback(SubXactEvent event, static uint32 ReleaseAllPGDuckConnections(SubTransactionId subTransactionId); static void CancelRunningCommandOnConnection(PGconn *conn); static bool CancelQuery(PGconn *conn); -static bool StartCancelQuery(PGconn *conn); +static bool StartCancelQuery(PGconn *conn, TimestampTz endtime); static bool FinishCancelQuery(PGconn *conn, TimestampTz endtime, bool consume_input); static bool WaitForLastResultWithTimeout(PGconn *conn, TimestampTz endtime, PGresult **result, bool *timed_out); @@ -87,6 +90,9 @@ typedef struct PgDuckServerConnectionHashEntry SubTransactionId subTransactionId; PGDuckConnection pgDuckConnection; + /* opened by ConnectToExternalQueryEngine, which reserved an fd */ + bool releaseExternalFD; + } PgDuckServerConnectionHashEntry; /* @@ -230,6 +236,54 @@ TryGetPGDuckConnection(char **errorMessage) return NULL; } + return TrackPGDuckConnection(connection, NULL, false); +} + + +/* + * TryGetPGDuckConnectionWithConninfo is like TryGetPGDuckConnection, but + * connects to the external query engine of the given foreign server at the + * given conninfo. + * + * The engine may be on another host, so unlike pgduck_server's socket the + * connection attempt can block for long, and statement_timeout or a cancel + * request interrupts it. + */ +PGDuckConnection * +TryGetPGDuckConnectionWithConninfo(const char *conninfo, const char *serverName, + char **errorMessage) +{ + InitializePGDuckClient(); + + PGconn *connection = ConnectToExternalQueryEngine(conninfo); + + if (connection == NULL) + { + *errorMessage = pstrdup("out of memory"); + return NULL; + } + + if (PQstatus(connection) != CONNECTION_OK) + { + *errorMessage = pstrdup(PQerrorMessage(connection)); + + DisconnectFromExternalQueryEngine(connection); + + return NULL; + } + + return TrackPGDuckConnection(connection, serverName, true); +} + + +/* + * TrackPGDuckConnection adds a new connection to the hash, so that it is + * closed when the (sub)transaction that opened it ends. + */ +static PGDuckConnection * +TrackPGDuckConnection(PGconn *connection, const char *serverName, + bool releaseExternalFD) +{ int connectionId = ConnectionId++; bool found = false; PgDuckServerConnectionHashEntry *entry = @@ -238,9 +292,13 @@ TryGetPGDuckConnection(char **errorMessage) if (!found) { entry->subTransactionId = GetCurrentSubTransactionId(); + entry->releaseExternalFD = releaseExternalFD; entry->pgDuckConnection.conn = connection; entry->pgDuckConnection.connectionId = connectionId; + entry->pgDuckConnection.serverName = + serverName != NULL ? + MemoryContextStrdup(PgDuckConnectionMemoryContext, serverName) : NULL; } return &entry->pgDuckConnection; @@ -502,6 +560,8 @@ ReleasePGDuckConnection(PGDuckConnection * pgDuckConnection) } PGconn *conn = entry->pgDuckConnection.conn; + char *serverName = entry->pgDuckConnection.serverName; + bool releaseExternalFD = entry->releaseExternalFD; /* * Clear the handle before removing the entry: HASH_REMOVE returns a @@ -509,10 +569,17 @@ ReleasePGDuckConnection(PGDuckConnection * pgDuckConnection) * with it the caller's PGDuckConnection, can be marked as released. */ entry->pgDuckConnection.conn = NULL; + entry->pgDuckConnection.serverName = NULL; hash_search(PgDuckConnectionHash, &connectionId, HASH_REMOVE, NULL); - PQfinish(conn); + if (serverName != NULL) + pfree(serverName); + + if (releaseExternalFD) + DisconnectFromExternalQueryEngine(conn); + else + PQfinish(conn); } @@ -917,7 +984,10 @@ ThrowIfPGDuckResultHasError(PGDuckConnection * pgDuckConnection, PGresult *resul errmsg("%s", message), messageDetail ? errdetail("%s", messageDetail) : 0, messageHint ? errhint("%s", messageHint) : 0, - messageContext ? errcontext("%s", messageContext) : 0)); + messageContext ? errcontext("%s", messageContext) : 0, + pgDuckConnection->serverName != NULL ? + errcontext("remote query on server \"%s\"", + pgDuckConnection->serverName) : 0)); } @@ -1080,20 +1150,35 @@ CancelQuery(PGconn *conn) endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(), CONNECTION_CLEANUP_TIMEOUT); - if (!StartCancelQuery(conn)) + if (!StartCancelQuery(conn, endtime)) return false; return FinishCancelQuery(conn, endtime, false); } /* - * StartCancelQuery sends a cancellation over the given connection. + * StartCancelQuery sends a cancellation over the given connection. From + * PostgreSQL 17 on, it waits for the server at most until endtime, so that an + * external query engine that never answers cannot hang the backend. * - * Copied ad verbatim from pgfdw_cancel_query_begin. + * Copied from pgfdw_cancel_query_begin. */ static bool -StartCancelQuery(PGconn *conn) +StartCancelQuery(PGconn *conn, TimestampTz endtime) { +#if PG_VERSION_NUM >= 170000 + const char *errorMessage = CancelQueryEngineCommand(conn, endtime); + + if (errorMessage != NULL) + { + ereport(WARNING, + (errcode(ERRCODE_CONNECTION_FAILURE), + errmsg("could not send cancel request: %s", errorMessage))); + return false; + } + + return true; +#else PGcancel *cancel; char errbuf[256]; @@ -1116,6 +1201,7 @@ StartCancelQuery(PGconn *conn) } return true; +#endif } /* diff --git a/pg_lake_engine/src/pgduck/explain.c b/pg_lake_engine/src/pgduck/explain.c index 53bbf906d..40e1ce138 100644 --- a/pg_lake_engine/src/pgduck/explain.c +++ b/pg_lake_engine/src/pgduck/explain.c @@ -229,6 +229,19 @@ GetExplainJson(QueryEngine queryEngine, char *query, int numParams, int rowCount = PQntuples(result); int columnCount = PQnfields(result); + /* DuckDB returns the plan in the second of two columns */ + if (!QueryEnginesEqual(queryEngine, PGDUCK_QUERY_ENGINE) && + (columnCount < 2 || rowCount < 1)) + ereport(ERROR, + (errcode(ERRCODE_FDW_ERROR), + errmsg("server \"%s\" did not return a DuckDB query plan", + GetQueryEngineName(queryEngine)), + errdetail("EXPLAIN shows the plan that the query engine " + "returns for DuckDB's explain (format 'json'), " + "which has a row with two columns. The engine " + "returned %d rows with %d columns.", + rowCount, columnCount))); + if (columnCount < 2) ereport(ERROR, (errmsg("unexpected column count %d", columnCount))); diff --git a/pg_lake_engine/src/pgduck/external_connection.c b/pg_lake_engine/src/pgduck/external_connection.c new file mode 100644 index 000000000..797d7c5c2 --- /dev/null +++ b/pg_lake_engine/src/pgduck/external_connection.c @@ -0,0 +1,74 @@ +/* + * Copyright 2026 Snowflake Inc. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * Connecting to and disconnecting from an external query engine, and + * cancelling a command on a connection. + * + * From PostgreSQL 19, libpq-be-fe-helpers.h includes libpq-be-fe.h, which + * redefines PGresult and the libpq functions that use it in every file that + * includes it. The rest of pg_lake passes plain PGresults between files, so + * the helpers are only used here, where no PGresult is handled. + */ +#include "postgres.h" + +#include "libpq-fe.h" +#include "libpq/libpq-be-fe-helpers.h" +#include "utils/wait_event.h" + +#include "pg_lake/pgduck/client.h" + + +/* + * ConnectToExternalQueryEngine opens a connection to an external query + * engine. Unlike PQconnectdb, a cancel request or statement_timeout + * interrupts an attempt that hangs, and the connection's file descriptor is + * reserved, as in postgres_fdw. + */ +PGconn * +ConnectToExternalQueryEngine(const char *conninfo) +{ + return libpqsrv_connect(conninfo, PG_WAIT_EXTENSION); +} + + +/* + * DisconnectFromExternalQueryEngine closes a connection opened by + * ConnectToExternalQueryEngine and releases its file descriptor. + */ +void +DisconnectFromExternalQueryEngine(PGconn *connection) +{ + libpqsrv_disconnect(connection); +} + + +#if PG_VERSION_NUM >= 170000 + +/* + * CancelQueryEngineCommand asks the server of a connection to cancel the + * command it runs, waiting for it at most until endtime, and returns NULL, or + * else an error message. Unlike PQcancel, a server that accepts the cancel + * request but never answers cannot hang the backend, as in postgres_fdw. + */ +const char * +CancelQueryEngineCommand(PGconn *connection, TimestampTz endtime) +{ + return libpqsrv_cancel(connection, endtime); +} + +#endif diff --git a/pg_lake_engine/src/pgduck/query_engine.c b/pg_lake_engine/src/pgduck/query_engine.c index 526ec7e9a..1c9ef8f54 100644 --- a/pg_lake_engine/src/pgduck/query_engine.c +++ b/pg_lake_engine/src/pgduck/query_engine.c @@ -16,13 +16,25 @@ */ #include "postgres.h" - +#include "miscadmin.h" +#include "libpq-fe.h" + +#include "access/htup_details.h" +#include "access/reloptions.h" +#include "catalog/pg_class.h" +#include "catalog/pg_foreign_table.h" +#include "catalog/pg_user_mapping.h" +#include "commands/defrem.h" +#include "foreign/foreign.h" +#include "lib/stringinfo.h" #include "nodes/nodeFuncs.h" #include "nodes/parsenodes.h" #include "parser/parse_relation.h" +#include "pg_lake/parsetree/options.h" #include "pg_lake/pgduck/client.h" #include "pg_lake/pgduck/query_engine.h" #include "pg_lake/util/rel_utils.h" +#include "utils/syscache.h" /* @@ -41,6 +53,51 @@ typedef struct FindQueryEngineContext static bool FindQueryEngineWalker(Node *node, FindQueryEngineContext * context); static void CheckSameQueryEngine(QueryEngine queryEngine, QueryEngine otherEngine); +static PGDuckConnection * GetExternalEngineConnection(Oid serverId, Oid userId); +static List *GetExternalEngineUserOptions(Oid userId, Oid serverId); +static char *BuildExternalEngineConninfo(ForeignServer *server, List *userOptions); +static void AppendConninfoOption(StringInfo conninfo, const char *keyword, + const char *value); + + +/* + * IsExternalEngineTable returns whether the given relation is a foreign table + * of the pg_lake_remote foreign data wrapper, which is served by an external + * query engine. Users name these servers, so unlike lake tables we identify + * them by their foreign data wrapper. + */ +bool +IsExternalEngineTable(Oid relationId) +{ + HeapTuple foreignTableTuple = SearchSysCache1(FOREIGNTABLEREL, + ObjectIdGetDatum(relationId)); + + if (!HeapTupleIsValid(foreignTableTuple)) + return false; + + Oid serverId = ((Form_pg_foreign_table) GETSTRUCT(foreignTableTuple))->ftserver; + + ReleaseSysCache(foreignTableTuple); + + ForeignServer *server = GetForeignServer(serverId); + Oid remoteFdwId = get_foreign_data_wrapper_oid(PG_LAKE_REMOTE_FDW_NAME, true); + + return OidIsValid(remoteFdwId) && server->fdwid == remoteFdwId; +} + + +/* + * IsQueryEngineTable returns whether the RTE is a table that is served by a + * query engine: a pg_lake table or a table of an external query engine. + */ +bool +IsQueryEngineTable(RangeTblEntry *rte) +{ + if (rte->rtekind != RTE_RELATION || rte->relkind != RELKIND_FOREIGN_TABLE) + return false; + + return IsAnyLakeForeignTableById(rte->relid) || IsExternalEngineTable(rte->relid); +} /* @@ -61,6 +118,16 @@ QueryEnginesEqual(QueryEngine left, QueryEngine right) QueryEngine GetRelationQueryEngine(Oid relationId, Oid checkAsUser) { + if (IsExternalEngineTable(relationId)) + { + QueryEngine queryEngine = { + .serverId = GetForeignTable(relationId)->serverid, + .userId = checkAsUser + }; + + return queryEngine; + } + if (!IsAnyLakeForeignTableById(relationId)) elog(ERROR, "relation %s is not served by a query engine", GetQualifiedRelationName(relationId)); @@ -162,7 +229,7 @@ FindQueryEngineWalker(Node *node, FindQueryEngineContext * context) { RangeTblEntry *rte = (RangeTblEntry *) node; - if (rte->rtekind != RTE_RELATION || !IsAnyLakeForeignTableById(rte->relid)) + if (!IsQueryEngineTable(rte)) return false; QueryEngine relationEngine = GetRteQueryEngine(rte, context->rteperminfos); @@ -193,19 +260,205 @@ CheckSameQueryEngine(QueryEngine queryEngine, QueryEngine otherEngine) } +/* + * GetQueryEngineName returns the name of the given query engine: the name of + * its foreign server, or pgduck_server. + */ +char * +GetQueryEngineName(QueryEngine queryEngine) +{ + if (QueryEnginesEqual(queryEngine, PGDUCK_QUERY_ENGINE)) + return "pgduck_server"; + + return GetForeignServer(queryEngine.serverId)->servername; +} + + /* * GetQueryEngineConnection returns a new connection to the given query * engine. With setSessionTimeZone, the connection evaluates expressions in the - * session's TimeZone, which a connection that runs a user's query needs. + * session's TimeZone, which a connection that runs a user's query needs. An + * external engine is reached with the user mapping of the user that the + * tables are read as, or of the current user if it is InvalidOid, like + * ExecCheckPermissions does. */ PGDuckConnection * GetQueryEngineConnection(QueryEngine queryEngine, bool setSessionTimeZone) { - if (!QueryEnginesEqual(queryEngine, PGDUCK_QUERY_ENGINE)) - elog(ERROR, "unknown query engine %u", queryEngine.serverId); + if (QueryEnginesEqual(queryEngine, PGDUCK_QUERY_ENGINE)) + { + if (setSessionTimeZone) + return GetPGDuckConnectionWithSessionTimeZone(); + + return GetPGDuckConnection(); + } + + Oid userId = OidIsValid(queryEngine.userId) ? queryEngine.userId : GetUserId(); + + return GetExternalEngineConnection(queryEngine.serverId, userId); +} + + +/* + * GetExternalEngineConnection returns a new connection to the external query + * engine of the given foreign server, as the given user. + * + * Like postgres_fdw, non-superusers have to authenticate with the password + * from their user mapping, unless a superuser set password_required to false + * on it. Otherwise they could use the engine's trust or peer authentication, + * or the password file of the operating system user, under a remote user + * name of their choosing. + */ +static PGDuckConnection * +GetExternalEngineConnection(Oid serverId, Oid userId) +{ + ForeignServer *server = GetForeignServer(serverId); + List *userOptions = GetExternalEngineUserOptions(userId, serverId); + bool passwordRequired = !superuser_arg(userId) && + GetBoolOption(userOptions, "password_required", true); + + if (passwordRequired && !HasOption(userOptions, "password")) + ereport(ERROR, + (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED), + errmsg("password is required"), + errdetail("Non-superusers must provide a password in the user mapping."))); + + char *conninfo = BuildExternalEngineConninfo(server, userOptions); + char *errorMessage = NULL; + PGDuckConnection *connection = + TryGetPGDuckConnectionWithConninfo(conninfo, server->servername, + &errorMessage); + + if (connection == NULL) + ereport(ERROR, + (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION), + errmsg("could not connect to server \"%s\"", server->servername), + errdetail_internal("%s", pchomp(errorMessage)))); + + if (passwordRequired && !PQconnectionUsedPassword(connection->conn)) + { + ReleasePGDuckConnection(connection); - if (setSessionTimeZone) - return GetPGDuckConnectionWithSessionTimeZone(); + ereport(ERROR, + (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED), + errmsg("password is required"), + errdetail("Non-superuser cannot connect if the server does not request a password."), + errhint("Target server's authentication method must be changed or set the password_required=false in the user mapping attributes."))); + } + + return connection; +} + + +/* + * GetExternalEngineUserOptions returns the options of the user mapping of the + * given user for the given server, falling back to the PUBLIC user mapping. + * Unlike GetUserMapping, it returns NIL when neither exists, since a user + * mapping is optional for an engine that does not need credentials. + */ +static List * +GetExternalEngineUserOptions(Oid userId, Oid serverId) +{ + HeapTuple userMappingTuple = SearchSysCache2(USERMAPPINGUSERSERVER, + ObjectIdGetDatum(userId), + ObjectIdGetDatum(serverId)); + + if (!HeapTupleIsValid(userMappingTuple)) + userMappingTuple = SearchSysCache2(USERMAPPINGUSERSERVER, + ObjectIdGetDatum(InvalidOid), + ObjectIdGetDatum(serverId)); + + if (!HeapTupleIsValid(userMappingTuple)) + return NIL; + + bool isNull = false; + Datum optionsDatum = SysCacheGetAttr(USERMAPPINGUSERSERVER, + userMappingTuple, + Anum_pg_user_mapping_umoptions, + &isNull); + List *options = isNull ? NIL : untransformRelOptions(optionsDatum); + + ReleaseSysCache(userMappingTuple); + + return options; +} + + +/* + * BuildExternalEngineConninfo returns the conninfo for connecting to the + * given server: the options in its conninfo, followed by the libpq options + * of the user mapping (the user, secrets such as the password, and client + * certificates). + * + * We parse the server conninfo and write it back out as keyword/value pairs, + * since it may be a URI, to which we could not append the user mapping. + */ +static char * +BuildExternalEngineConninfo(ForeignServer *server, List *userOptions) +{ + char *serverConninfo = GetStringOption(server->options, "conninfo", true); + char *errorMessage = NULL; + PQconninfoOption *connOptions = PQconninfoParse(serverConninfo, &errorMessage); + + if (connOptions == NULL) + { + char *detail = errorMessage != NULL ? pchomp(errorMessage) : "out of memory"; + + PQfreemem(errorMessage); + ereport(ERROR, + (errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE), + errmsg("invalid \"conninfo\" option for server \"%s\"", + server->servername), + errdetail_internal("%s", detail))); + } + + StringInfoData conninfo; + + initStringInfo(&conninfo); + + for (PQconninfoOption *connOption = connOptions; connOption->keyword != NULL; connOption++) + { + if (connOption->val != NULL) + AppendConninfoOption(&conninfo, connOption->keyword, connOption->val); + } + + PQconninfoFree(connOptions); + + ListCell *optionCell = NULL; + + foreach(optionCell, userOptions) + { + DefElem *option = (DefElem *) lfirst(optionCell); + + if (strcmp(option->defname, "password_required") == 0) + continue; + + AppendConninfoOption(&conninfo, option->defname, defGetString(option)); + } + + return conninfo.data; +} + + +/* + * AppendConninfoOption appends keyword='value' to a conninfo string, escaping + * backslashes and single quotes in the value. + */ +static void +AppendConninfoOption(StringInfo conninfo, const char *keyword, const char *value) +{ + if (conninfo->len > 0) + appendStringInfoChar(conninfo, ' '); + + appendStringInfo(conninfo, "%s='", keyword); + + for (const char *valueChar = value; *valueChar != '\0'; valueChar++) + { + if (*valueChar == '\\' || *valueChar == '\'') + appendStringInfoChar(conninfo, '\\'); + + appendStringInfoChar(conninfo, *valueChar); + } - return GetPGDuckConnection(); + appendStringInfoChar(conninfo, '\''); } diff --git a/pg_lake_table/include/pg_lake/fdw/shippable.h b/pg_lake_table/include/pg_lake/fdw/shippable.h index c89b2ab23..647c0551c 100644 --- a/pg_lake_table/include/pg_lake/fdw/shippable.h +++ b/pg_lake_table/include/pg_lake/fdw/shippable.h @@ -44,7 +44,9 @@ typedef enum NotShippableReason NOT_SHIPPABLE_SQL_UNNEST_GROUP_BY_OR_WINDOW, NOT_SHIPPABLE_INFINITE_CONST_VALUE, NOT_SHIPPABLE_NAN_CONST_VALUE, - NOT_SHIPPABLE_SQL_JSON_EXPRESSION + NOT_SHIPPABLE_SQL_JSON_EXPRESSION, + NOT_SHIPPABLE_MIXED_QUERY_ENGINES, + NOT_SHIPPABLE_MIXED_QUERY_ENGINE_USERS } NotShippableReason; diff --git a/pg_lake_table/pg_lake_table--3.7--3.8.sql b/pg_lake_table/pg_lake_table--3.7--3.8.sql index 169beb422..a00dba7e4 100644 --- a/pg_lake_table/pg_lake_table--3.7--3.8.sql +++ b/pg_lake_table/pg_lake_table--3.7--3.8.sql @@ -3,3 +3,15 @@ -- Number of NULL values of the column in the data file. NULL means unknown, -- which is the case for every file written before this column existed. ALTER TABLE lake_table.data_file_column_stats ADD COLUMN null_count bigint; + +-- Tables served by an external query engine, a server that speaks the +-- PostgreSQL wire protocol and runs DuckDB SQL (docs/external-query-engines.md). +-- No role gets USAGE on the wrapper, so only superusers create its servers. +CREATE FUNCTION pg_lake_remote_validator(text[], oid) +RETURNS void +AS 'MODULE_PATHNAME' +LANGUAGE C STRICT; + +CREATE FOREIGN DATA WRAPPER pg_lake_remote + HANDLER pg_lake_table_handler + VALIDATOR pg_lake_remote_validator; diff --git a/pg_lake_table/src/duckdb/transform_query_to_duckdb.c b/pg_lake_table/src/duckdb/transform_query_to_duckdb.c index c2cc13248..55b1e4fee 100644 --- a/pg_lake_table/src/duckdb/transform_query_to_duckdb.c +++ b/pg_lake_table/src/duckdb/transform_query_to_duckdb.c @@ -54,6 +54,11 @@ #include "pg_lake/fdw/equality_delete.h" #include "pg_lake/pgduck/duckdb_identifier.h" #include "pg_lake/pgduck/keywords.h" +#include "pg_lake/pgduck/map.h" +#include "pg_lake/pgduck/numeric.h" +#include "pg_lake/pgduck/query_engine.h" +#include "pg_lake/pgduck/type.h" +#include "pg_lake/util/numeric.h" #include "pg_lake/fdw/writable_table.h" #include "pg_lake/fdw/schema_operations/register_field_ids.h" #include "pg_extension_base/pg_compat.h" @@ -66,6 +71,8 @@ static char *BuildReadDataSourceQueryForTableScan(PgLakeTableScan * tableScan, bool skipFullMatchFiles, TupleDesc projection); +static char *BuildExternalEngineTableQuery(Oid relationId); +static const char *GetExternalEngineColumnCastType(Oid typeId, int32 typeMod); static void EnsureServerType(Oid relationId); static void AppendEqualityReadGroups(StringInfo command, List *groups, int start, int count, List *positionDeletePaths, @@ -80,6 +87,8 @@ static char *FileScanConstantsArgument(List *fileScans); * * If EXPLAIN_REQUEST flag is set, it replaces the read_table function call with * the relation name. That's only for the explain output, even for analyze. + * Tables of an external query engine are replaced with the query on the remote + * table in both cases. * * If SKIP_FULL_MATCH_FILES flag is set, we skip fullyIncluded file scans. */ @@ -104,7 +113,9 @@ ReplaceReadTableFunctionCalls(char *query, char *readFunctionForServer = NULL; - if (explainRequested) + if (IsExternalEngineTable(relationId)) + readFunctionForServer = BuildExternalEngineTableQuery(relationId); + else if (explainRequested) readFunctionForServer = qualifiedRelationName; else readFunctionForServer = BuildReadDataSourceQueryForTableScan(tableScan, @@ -320,6 +331,124 @@ BuildReadDataSourceQueryForTableScan(PgLakeTableScan * tableScan, bool skipFullM } +/* + * BuildExternalEngineTableQuery returns a query fragment that reads a table + * served by an external query engine. + * + * The deparsed query gives the read_table() call a column alias list, which + * renames the columns by position, so we select the columns by name in the + * order of the foreign table. The engine may order them differently. + */ +static char * +BuildExternalEngineTableQuery(Oid relationId) +{ + ForeignTable *foreignTable = GetForeignTable(relationId); + char *schemaName = GetStringOption(foreignTable->options, "schema_name", false); + char *tableName = GetStringOption(foreignTable->options, "table_name", true); + + StringInfoData query; + + initStringInfo(&query); + appendStringInfoString(&query, "(SELECT "); + + Relation rel = relation_open(relationId, AccessShareLock); + TupleDesc tupleDesc = RelationGetDescr(rel); + bool hasColumns = false; + + for (int attnum = 1; attnum <= tupleDesc->natts; attnum++) + { + Form_pg_attribute column = TupleDescAttr(tupleDesc, attnum - 1); + + if (column->attisdropped) + continue; + + const char *columnName = duckdb_quote_identifier(NameStr(column->attname)); + const char *castType = GetExternalEngineColumnCastType(column->atttypid, + column->atttypmod); + + if (hasColumns) + appendStringInfoString(&query, ", "); + + if (castType != NULL) + appendStringInfo(&query, "CAST(%s AS %s) AS %s", columnName, castType, + columnName); + else + appendStringInfoString(&query, columnName); + + hasColumns = true; + } + + relation_close(rel, NoLock); + + if (!hasColumns) + appendStringInfoString(&query, "*"); + + appendStringInfoString(&query, " FROM "); + + if (schemaName != NULL) + appendStringInfo(&query, "%s.", duckdb_quote_identifier(schemaName)); + + appendStringInfo(&query, "%s)", duckdb_quote_identifier(tableName)); + + return query.data; +} + + +/* + * GetExternalEngineColumnCastType returns the DuckDB type that we cast a + * column of an external engine table with the given declared type to, or + * NULL if we do not cast it. + * + * The cast makes the engine compute with the declared type even if its + * column has another type, instead of, say, comparing integers where the + * foreign table declares text. DuckDB drops a cast to the type a column + * already has, so filters on a column of the declared type still reach the + * engine's scan. + * + * We only cast scalar types that have an exact DuckDB type. Not numeric + * without a precision, or wider than DuckDB's DECIMAL, which we would round, + * not geometry, whose DuckDB type needs the spatial extension, and not + * arrays, composite types and maps, which DuckDB casts unlike how PostgreSQL + * reads their text (lists of any depth, struct fields matched by name). The + * engine has to return those in the declared type. + */ +static const char * +GetExternalEngineColumnCastType(Oid typeId, int32 typeMod) +{ + typeId = ResolveDomainBaseTypeAndTypmod(typeId, &typeMod); + + PGType pgType = MakePGType(typeId, typeMod); + + switch (GetDuckDBTypeForPGType(pgType)) + { + case DUCKDB_TYPE_INVALID: + case DUCKDB_TYPE_LIST: + case DUCKDB_TYPE_STRUCT: + case DUCKDB_TYPE_MAP: + case DUCKDB_TYPE_GEOMETRY: + return NULL; + + case DUCKDB_TYPE_DECIMAL: + { + if (IsUnboundedNumeric(typeId, typeMod)) + return NULL; + + int precision = numeric_typmod_precision(typeMod); + int scale = numeric_typmod_scale(typeMod); + + if (precision > DUCKDB_MAX_NUMERIC_PRECISION || scale < 0 || + scale > precision) + return NULL; + + return psprintf("DECIMAL(%d,%d)", precision, scale); + } + + default: + return GetFullDuckDBTypeNameForPGType(pgType, DATA_FORMAT_INVALID); + } +} + + /* * Balance the UNION tree so parser depth grows logarithmically with groups. * Each data file appears once, and NOT EXISTS preserves the multiplicity of @@ -429,16 +558,17 @@ FileScanConstantsArgument(List *fileScans) * EnsureServerType checks that the server type for a given relation is supported. * * This function checks if the foreign server name associated with the relation - * matches the expected server type "pg_lake" or "pg_lake_iceberg". + * matches the expected server type "pg_lake" or "pg_lake_iceberg", or if the + * server is a pg_lake_remote server. */ static void EnsureServerType(Oid relationId) { - if (!IsAnyLakeForeignTableById(relationId)) + if (!IsAnyLakeForeignTableById(relationId) && !IsExternalEngineTable(relationId)) ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_OPTION_NAME), errmsg("unsupported server type for relation %s", GetQualifiedRelationName(relationId)), - errhint("Only pg_lake or pg_lake_iceberg " + errhint("Only pg_lake, pg_lake_iceberg or pg_lake_remote " "server type is supported."))); } diff --git a/pg_lake_table/src/fdw/deparse.c b/pg_lake_table/src/fdw/deparse.c index 0ecef00bc..674592745 100644 --- a/pg_lake_table/src/fdw/deparse.c +++ b/pg_lake_table/src/fdw/deparse.c @@ -2477,42 +2477,22 @@ deparseColumnRef(StringInfo buf, int varno, int varattno, RangeTblEntry *rte, } /* - * Append remote name of specified foreign table to buf. - * Use value of table_name FDW option (if any) instead of relation's name. - * Similarly, schema_name FDW option overrides schema name. + * Append name of specified foreign table to buf. + * + * Unlike postgres_fdw, we parse the deparsed query again and only then + * replace the table with the call that reads it, so we use the name of the + * local relation, not the table_name and schema_name options that a + * pg_lake_remote table uses to name the table on its query engine. */ static void deparseRelation(StringInfo buf, Relation rel) { - ForeignTable *table; - const char *nspname = NULL; - const char *relname = NULL; - ListCell *lc; - - /* obtain additional catalog information. */ - table = GetForeignTable(RelationGetRelid(rel)); - - /* - * Use value of FDW options if any, instead of the name of object itself. - */ - foreach(lc, table->options) - { - DefElem *def = (DefElem *) lfirst(lc); - - if (strcmp(def->defname, "schema_name") == 0) - nspname = defGetString(def); - else if (strcmp(def->defname, "table_name") == 0) - relname = defGetString(def); - } - /* * Note: we could skip printing the schema name if it's pg_catalog, but * that doesn't seem worth the trouble. */ - if (nspname == NULL) - nspname = get_namespace_name(RelationGetNamespace(rel)); - if (relname == NULL) - relname = RelationGetRelationName(rel); + const char *nspname = get_namespace_name(RelationGetNamespace(rel)); + const char *relname = RelationGetRelationName(rel); appendStringInfo(buf, "%s.%s", duckdb_quote_identifier(nspname), diff --git a/pg_lake_table/src/fdw/deparse_ruleutils.c b/pg_lake_table/src/fdw/deparse_ruleutils.c index 592ba523d..18392944b 100644 --- a/pg_lake_table/src/fdw/deparse_ruleutils.c +++ b/pg_lake_table/src/fdw/deparse_ruleutils.c @@ -43,6 +43,7 @@ #include "pg_lake/extensions/postgis.h" #include "pg_lake/fdw/deparse_ruleutils.h" #include "pg_lake/parsetree/rte.h" +#include "pg_lake/pgduck/query_engine.h" #include "pg_lake/pgduck/rewrite_query.h" #include "pg_lake/planner/restriction_collector.h" #include "pg_lake/extensions/postgis.h" @@ -81,7 +82,8 @@ static bool FixCtidVarWalker(Node *node, /* * ReplacePgLakeTableWithReadTableFunc replaces all occurrences of - * pg_lake tables with read_table(..) function calls. + * tables that are served by a query engine with read_table(..) function + * calls. */ List * ReplacePgLakeTableWithReadTableFunc(Node *node) @@ -173,7 +175,7 @@ ReplacePgLakeTableWalker(Node *node, ReplacePgLakeTableContext * context) RangeTblEntry *rte = (RangeTblEntry *) node; - if (IsAnyLakeForeignTable(rte)) + if (IsQueryEngineTable(rte)) { char *qualifiedRelationName = GetQualifiedRelationName(rte->relid); diff --git a/pg_lake_table/src/fdw/option.c b/pg_lake_table/src/fdw/option.c index 902d18326..c30adf6d7 100644 --- a/pg_lake_table/src/fdw/option.c +++ b/pg_lake_table/src/fdw/option.c @@ -28,9 +28,11 @@ #include +#include "libpq-fe.h" #include "access/reloptions.h" #include "catalog/pg_foreign_server.h" #include "catalog/pg_foreign_table.h" +#include "catalog/pg_user_mapping.h" #include "commands/defrem.h" #include "commands/extension.h" #include "foreign/foreign.h" @@ -66,6 +68,22 @@ typedef struct PgLakeOption static PgLakeOption * pg_lake_options; static PgLakeOption * pg_lake_iceberg_options; +/* + * Valid options for pg_lake_remote, whose tables are served by an external + * query engine. User mappings also take the libpq options that libpq marks + * as secret, such as password and sslpassword (see IsSecretLibpqOption). + */ +static const PgLakeOption pg_lake_remote_options[] = { + {"conninfo", ForeignServerRelationId}, + {"user", UserMappingRelationId}, + {"password_required", UserMappingRelationId}, + {"sslcert", UserMappingRelationId}, + {"sslkey", UserMappingRelationId}, + {"table_name", ForeignTableRelationId}, + {"schema_name", ForeignTableRelationId}, + {NULL, InvalidOid} +}; + /* * Helper functions */ @@ -73,6 +91,9 @@ static void InitPgLakeOptions(void); static void InitPgLakeIcebergOptions(void); static bool is_valid_option_pg_lake(const char *keyword, Oid context); static bool is_valid_option_pg_lake_iceberg(const char *keyword, Oid context); +static bool IsValidRemoteOption(const char *keyword, Oid context); +static bool IsSecretLibpqOption(const char *keyword); +static void ValidateRemoteConninfo(const char *conninfo); #include "miscadmin.h" @@ -84,6 +105,7 @@ static bool is_valid_option_pg_lake_iceberg(const char *keyword, Oid context); */ PG_FUNCTION_INFO_V1(pg_lake_table_validator); PG_FUNCTION_INFO_V1(pg_lake_iceberg_validator); +PG_FUNCTION_INFO_V1(pg_lake_remote_validator); Datum pg_lake_table_validator(PG_FUNCTION_ARGS) @@ -1039,3 +1061,239 @@ pg_lake_iceberg_validator(PG_FUNCTION_ARGS) } PG_RETURN_VOID(); } + + +/* + * pg_lake_remote_validator validates the options of pg_lake_remote servers, + * user mappings and foreign tables. Their tables are served by an external + * query engine, so there are no files to check. + */ +Datum +pg_lake_remote_validator(PG_FUNCTION_ARGS) +{ + List *options_list = untransformRelOptions(PG_GETARG_DATUM(0)); + Oid catalog = PG_GETARG_OID(1); + bool foundConninfo = false; + bool foundTableName = false; + ListCell *cell; + + foreach(cell, options_list) + { + DefElem *def = (DefElem *) lfirst(cell); + + if (!IsValidRemoteOption(def->defname, catalog)) + { + /* + * Unknown option specified, complain about it. Provide a hint + * with a valid option that looks similar, if there is one. + */ + const char *closest_match; + ClosestMatchState match_state; + bool has_valid_options = false; + + initClosestMatch(&match_state, def->defname, 4); + for (int i = 0; pg_lake_remote_options[i].keyword != NULL; i++) + { + if (catalog == pg_lake_remote_options[i].optcontext) + { + has_valid_options = true; + updateClosestMatch(&match_state, pg_lake_remote_options[i].keyword); + } + } + + if (catalog == UserMappingRelationId) + updateClosestMatch(&match_state, "password"); + + closest_match = getClosestMatch(&match_state); + ereport(ERROR, + (errcode(ERRCODE_FDW_INVALID_OPTION_NAME), + errmsg("invalid option \"%s\"", def->defname), + has_valid_options ? closest_match ? + errhint("Perhaps you meant the option \"%s\".", + closest_match) : 0 : + errhint("There are no valid options in this context."))); + } + + if (strcmp(def->defname, "password_required") == 0) + { + /* same rule as postgres_fdw */ + if (!defGetBoolean(def) && !superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("password_required=false is superuser-only"), + errhint("User mappings with the password_required option " + "set to false may only be created or modified " + "by the superuser."))); + + continue; + } + + if (strlen(defGetString(def)) == 0) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg("option \"%s\" cannot be empty", def->defname))); + + if (strcmp(def->defname, "conninfo") == 0) + { + ValidateRemoteConninfo(defGetString(def)); + foundConninfo = true; + } + else if (strcmp(def->defname, "sslcert") == 0 || + strcmp(def->defname, "sslkey") == 0) + { + /* + * Same rule as postgres_fdw: these name files on this server, + * such as the server's own key. + */ + if (!superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("sslcert and sslkey are superuser-only"), + errhint("User mappings with the sslcert or sslkey options " + "set may only be created or modified by the " + "superuser."))); + } + else if (strcmp(def->defname, "table_name") == 0 || + strcmp(def->defname, "schema_name") == 0) + { + /* + * DuckDB reads a table name that is not in its catalog as a file + * or URL, with the engine's own access to the file system and + * object storage, so the name decides what any reader of the + * table can read. + */ + if (!superuser()) + ereport(ERROR, + (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), + errmsg("table_name and schema_name are superuser-only"), + errdetail("A query engine may read a table name that " + "it does not know as a file or URL."), + errhint("Foreign tables of pg_lake_remote servers may " + "only be created or modified by the superuser."))); + + if (strcmp(def->defname, "table_name") == 0) + foundTableName = true; + } + } + + if (catalog == ForeignServerRelationId && !foundConninfo) + ereport(ERROR, + (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND), + errmsg("\"conninfo\" option is required for pg_lake_remote servers"))); + + /* + * The table name is not taken from the name of the foreign table, which + * its owner can rename. + */ + if (catalog == ForeignTableRelationId && !foundTableName) + ereport(ERROR, + (errcode(ERRCODE_FDW_OPTION_NAME_NOT_FOUND), + errmsg("\"table_name\" option is required for pg_lake_remote tables"))); + + PG_RETURN_VOID(); +} + + +/* + * IsValidRemoteOption returns whether the given option is valid for the + * given catalog of a pg_lake_remote object. + */ +static bool +IsValidRemoteOption(const char *keyword, Oid context) +{ + for (int i = 0; pg_lake_remote_options[i].keyword != NULL; i++) + { + if (context == pg_lake_remote_options[i].optcontext && + strcmp(pg_lake_remote_options[i].keyword, keyword) == 0) + return true; + } + + return context == UserMappingRelationId && IsSecretLibpqOption(keyword); +} + + +/* + * IsSecretLibpqOption returns whether libpq marks the given connection option + * as secret, as it does password, sslpassword and, since PostgreSQL 18, + * oauth_client_secret. Like postgres_fdw, we only accept these in user + * mappings, which only their user and the server owner can read. + */ +static bool +IsSecretLibpqOption(const char *keyword) +{ + PQconninfoOption *connOptions = PQconninfoParse("", NULL); + bool isSecret = false; + + if (connOptions == NULL) + ereport(ERROR, + (errcode(ERRCODE_OUT_OF_MEMORY), + errmsg("out of memory"))); + + for (PQconninfoOption *connOption = connOptions; connOption->keyword != NULL; connOption++) + { + if (strcmp(connOption->keyword, keyword) == 0) + { + isSecret = strchr(connOption->dispchar, '*') != NULL; + break; + } + } + + PQconninfoFree(connOptions); + + return isSecret; +} + + +/* + * ValidateRemoteConninfo checks that the conninfo of a pg_lake_remote server + * parses, and that it leaves the user and secrets to the user mappings. + * + * Like postgres_fdw, we also refuse the options that libpq marks as debug + * options, such as replication and sslkeylogfile. + */ +static void +ValidateRemoteConninfo(const char *conninfo) +{ + char *errorMessage = NULL; + PQconninfoOption *connOptions = PQconninfoParse(conninfo, &errorMessage); + + if (connOptions == NULL) + { + char *detail = errorMessage != NULL ? pchomp(errorMessage) : "out of memory"; + + PQfreemem(errorMessage); + ereport(ERROR, + (errcode(ERRCODE_FDW_INVALID_ATTRIBUTE_VALUE), + errmsg("invalid \"conninfo\" option"), + errdetail_internal("%s", detail))); + } + + char *userMappingKeyword = NULL; + char *debugKeyword = NULL; + + for (PQconninfoOption *connOption = connOptions; connOption->keyword != NULL; connOption++) + { + if (connOption->val == NULL) + continue; + + if (strcmp(connOption->keyword, "user") == 0 || + strchr(connOption->dispchar, '*') != NULL) + userMappingKeyword = pstrdup(connOption->keyword); + else if (strchr(connOption->dispchar, 'D') != NULL) + debugKeyword = pstrdup(connOption->keyword); + } + + PQconninfoFree(connOptions); + + if (userMappingKeyword != NULL) + ereport(ERROR, + (errcode(ERRCODE_FDW_INVALID_OPTION_NAME), + errmsg("\"conninfo\" option cannot contain \"%s\"", userMappingKeyword), + errdetail("The options of a server are visible to all users."), + errhint("Set the user and secrets such as passwords in a user mapping."))); + + if (debugKeyword != NULL) + ereport(ERROR, + (errcode(ERRCODE_FDW_INVALID_OPTION_NAME), + errmsg("\"conninfo\" option cannot contain \"%s\"", debugKeyword))); +} diff --git a/pg_lake_table/src/fdw/pg_lake_table.c b/pg_lake_table/src/fdw/pg_lake_table.c index 26f1c00f5..a59c8b554 100644 --- a/pg_lake_table/src/fdw/pg_lake_table.c +++ b/pg_lake_table/src/fdw/pg_lake_table.c @@ -3200,7 +3200,11 @@ postgresExplainForeignScan(ForeignScanState *node, ExplainState *es) ExplainPropertyText("Engine", "DuckDB", es); - if (es->verbose) + if (!QueryEnginesEqual(fsstate->queryEngine, PGDUCK_QUERY_ENGINE)) + ExplainPropertyText("Server", GetQueryEngineName(fsstate->queryEngine), es); + + /* an external query engine reads no files that we know of */ + if (es->verbose && QueryEnginesEqual(fsstate->queryEngine, PGDUCK_QUERY_ENGINE)) { int dataFileScans = 0; int deleteFileScans = 0; @@ -4722,6 +4726,13 @@ postgresExecForeignTruncate(List *relations, Relation relation = lfirst(relationCell); Oid relationId = RelationGetRelid(relation); + if (IsExternalEngineTable(relationId)) + ereport(ERROR, + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), + errmsg("cannot truncate foreign table \"%s\"", + RelationGetRelationName(relation)), + errdetail("Tables of an external query engine are read-only."))); + ErrorIfReadOnlyIcebergTable(relationId); /* extra checks */ diff --git a/pg_lake_table/src/fdw/snapshot.c b/pg_lake_table/src/fdw/snapshot.c index 0b74c69e7..4cabfdb7a 100644 --- a/pg_lake_table/src/fdw/snapshot.c +++ b/pg_lake_table/src/fdw/snapshot.c @@ -40,6 +40,7 @@ #include "pg_lake/pgduck/map.h" #include "pg_lake/parsetree/options.h" #include "pg_extension_base/pg_compat.h" +#include "pg_lake/pgduck/query_engine.h" #include "pg_lake/pgduck/remote_storage.h" #include "pg_lake/planner/restriction_collector.h" #include "pg_lake/storage/storage_credentials.h" @@ -139,12 +140,21 @@ CreatePgLakeScanSnapshot(List *rteList, PrettyPrintBaseRestrictInfo(DEBUG2, rte, baseRestrictInfoList); } - PgLakeTableScan *tableScan = - CreateTableScanForRelation(relationId, postgresSnapshot, - uniqueRelationIdentifier, - baseRestrictInfoList, - includeChildren && rte->inh, - isResultRelation); + PgLakeTableScan *tableScan = NULL; + + if (IsExternalEngineTable(relationId)) + { + /* an external query engine reads its own data, there are no files */ + tableScan = palloc0(sizeof(PgLakeTableScan)); + tableScan->relationId = relationId; + tableScan->uniqueRelationIdentifier = uniqueRelationIdentifier; + } + else + tableScan = CreateTableScanForRelation(relationId, postgresSnapshot, + uniqueRelationIdentifier, + baseRestrictInfoList, + includeChildren && rte->inh, + isResultRelation); tableScans = lappend(tableScans, tableScan); } diff --git a/pg_lake_table/src/planner/explain.c b/pg_lake_table/src/planner/explain.c index c9c933d25..b3c7517b0 100644 --- a/pg_lake_table/src/planner/explain.c +++ b/pg_lake_table/src/planner/explain.c @@ -157,6 +157,12 @@ NotShippableObjectToString(const NotShippableObject * notShippableObject) case NOT_SHIPPABLE_TABLE: appendStringInfo(message, "\tTable\n"); break; + case NOT_SHIPPABLE_MIXED_QUERY_ENGINES: + appendStringInfo(message, "\tTable on another query engine\n"); + break; + case NOT_SHIPPABLE_MIXED_QUERY_ENGINE_USERS: + appendStringInfo(message, "\tTable read as another user\n"); + break; case NOT_SHIPPABLE_TYPE: appendStringInfo(message, "\tType\n"); break; diff --git a/pg_lake_table/src/planner/insert_select.c b/pg_lake_table/src/planner/insert_select.c index faa9fc305..612006273 100644 --- a/pg_lake_table/src/planner/insert_select.c +++ b/pg_lake_table/src/planner/insert_select.c @@ -31,6 +31,7 @@ #include "pg_lake/pgduck/iceberg_validation.h" #include "pg_lake/pgduck/map.h" #include "pg_lake/pgduck/numeric.h" +#include "pg_lake/pgduck/query_engine.h" #include "pg_lake/util/rel_utils.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" @@ -45,6 +46,7 @@ static RangeTblEntry *GetSelectRteFromInsertSelect(Query *query); static RangeTblEntry *GetInsertRteFromInsertSelect(Query *query); static bool TypeContainsUnsuitableForPushdown(Oid typeId, int32 typmod); static bool QueryIntroducesNanNumeric(Node *node, void *context); +static bool QueryReadsExternalEngineTable(Node *node, void *context); /* pg_lake_table.enable_insert_select_pushdown setting */ bool EnableInsertSelectPushdown = true; @@ -163,6 +165,15 @@ IsPushdownableInsertSelectQuery(Query *query) return false; } + /* pgduck_server writes the rows, so it also has to run the SELECT */ + if (QueryReadsExternalEngineTable((Node *) query, NULL)) + { + ereport(DEBUG4, + (errmsg("INSERT..SELECT from a table of an external query " + "engine is not pushdownable"))); + return false; + } + /* check whether SELECT is pushdownable */ RangeTblEntry *selectRte = GetSelectRteFromInsertSelect(query); @@ -455,6 +466,31 @@ QueryIntroducesNanNumeric(Node *node, void *context) } +/* + * QueryReadsExternalEngineTable returns whether the query reads a table of an + * external query engine, including in its CTEs and subqueries. + */ +static bool +QueryReadsExternalEngineTable(Node *node, void *context) +{ + if (node == NULL) + return false; + + if (IsA(node, Query)) + return query_tree_walker((Query *) node, QueryReadsExternalEngineTable, + context, QTW_EXAMINE_RTES_BEFORE); + + if (IsA(node, RangeTblEntry)) + { + RangeTblEntry *rte = (RangeTblEntry *) node; + + return rte->rtekind == RTE_RELATION && IsExternalEngineTable(rte->relid); + } + + return expression_tree_walker(node, QueryReadsExternalEngineTable, context); +} + + /* * TypeContainsUnsuitableForPushdown recursively checks whether the given type * (or any type nested within it) is unsuitable for pushdown. diff --git a/pg_lake_table/src/planner/query_pushdown.c b/pg_lake_table/src/planner/query_pushdown.c index f277ed7c9..460111dba 100644 --- a/pg_lake_table/src/planner/query_pushdown.c +++ b/pg_lake_table/src/planner/query_pushdown.c @@ -100,6 +100,16 @@ typedef struct IsShippableContext /* range table of the query currently being walked, NIL outside a query */ List *rtable; + + /* permission infos of the query currently being walked */ + List *rteperminfos; + + /* + * query engine of the first table we found, with the user it is read as, + * which all tables must share + */ + QueryEngine queryEngine; + bool hasQueryEngine; } IsShippableContext; @@ -399,7 +409,8 @@ AddMissingRTEAliasaes(Node *node, void *context) /* * HasLakeRTE recursively walks the node tree to determine - * whether there is a pg_lake_table RangeTblEntry. + * whether there is a pg_lake_table RangeTblEntry, which is a table + * that is served by a query engine. */ bool HasLakeRTE(Node *node, void *context) @@ -420,7 +431,7 @@ HasLakeRTE(Node *node, void *context) { RangeTblEntry *rte = (RangeTblEntry *) node; - if (IsAnyLakeForeignTable(rte)) + if (IsQueryEngineTable(rte)) return true; /* query_tree_walker descends into RTEs */ @@ -650,10 +661,12 @@ ProcessNotShippableExpressionWalker(Node *node, IsShippableContext * context) { bool prevHasUnnest = context->hasUnnest; List *prevRtable = context->rtable; + List *prevRtePermInfos = context->rteperminfos; Query *query = (Query *) node; /* so that a Var below can be resolved to the relation it comes from */ context->rtable = query->rtable; + context->rteperminfos = query->rteperminfos; if (query->hasForUpdate) { @@ -699,6 +712,7 @@ ProcessNotShippableExpressionWalker(Node *node, IsShippableContext * context) context->hasUnnest = prevHasUnnest; context->rtable = prevRtable; + context->rteperminfos = prevRtePermInfos; return false; } @@ -735,13 +749,45 @@ ProcessNotShippableExpressionWalker(Node *node, IsShippableContext * context) } /* we only support pg_lake relations for the moment */ - if (rte->rtekind == RTE_RELATION && !IsAnyLakeForeignTable(rte)) + if (rte->rtekind == RTE_RELATION && !IsQueryEngineTable(rte)) { if (context->stopAtFirstNotShippable) return true; RecordNotShippableObject(context, rte->relid, RelationRelationId, NOT_SHIPPABLE_TABLE); } + else if (rte->rtekind == RTE_RELATION) + { + /* + * The query is sent to one engine, which has to serve all tables. + * An external engine is reached with one user's user mapping, so + * its tables also have to be read as the same user, which differs + * for a table read through a view. + */ + QueryEngine queryEngine = GetRteQueryEngine(rte, context->rteperminfos); + + if (!context->hasQueryEngine) + { + context->queryEngine = queryEngine; + context->hasQueryEngine = true; + } + else if (queryEngine.serverId != context->queryEngine.serverId) + { + if (context->stopAtFirstNotShippable) + return true; + + RecordNotShippableObject(context, rte->relid, RelationRelationId, + NOT_SHIPPABLE_MIXED_QUERY_ENGINES); + } + else if (queryEngine.userId != context->queryEngine.userId) + { + if (context->stopAtFirstNotShippable) + return true; + + RecordNotShippableObject(context, rte->relid, RelationRelationId, + NOT_SHIPPABLE_MIXED_QUERY_ENGINE_USERS); + } + } if (rte->rtekind == RTE_RELATION && has_subclass(rte->relid) && !AllInheritorsAreLakeTable(rte->relid)) @@ -1852,7 +1898,11 @@ QueryPushdownExplainScan(CustomScanState *node, List *ancestors, ExplainPropertyText("Engine", "DuckDB", es); - if (es->verbose) + if (!QueryEnginesEqual(scanState->queryEngine, PGDUCK_QUERY_ENGINE)) + ExplainPropertyText("Server", GetQueryEngineName(scanState->queryEngine), es); + + /* an external query engine reads no files that we know of */ + if (es->verbose && QueryEnginesEqual(scanState->queryEngine, PGDUCK_QUERY_ENGINE)) { int dataFileScans = 0; int deleteFileScans = 0; @@ -1864,7 +1914,10 @@ QueryPushdownExplainScan(CustomScanState *node, List *ancestors, ExplainPropertyText("Data Files Scanned", dataFileScansString, es); ExplainPropertyText("Deletion Files Scanned", deleteFileScansString, es); + } + if (es->verbose) + { if (scanState->insertIntoRelid != InvalidOid) { IcebergOutOfRangePolicy outOfRangePolicy = diff --git a/pg_lake_table/tests/pytests/test_external_engine_table.py b/pg_lake_table/tests/pytests/test_external_engine_table.py new file mode 100644 index 000000000..cbabf5842 --- /dev/null +++ b/pg_lake_table/tests/pytests/test_external_engine_table.py @@ -0,0 +1,1714 @@ +import io +import re +import socket +import subprocess +import threading +import time + +import psycopg2 +import pytest +from utils_pytest import * + +# Tables of the pg_lake_remote foreign data wrapper are served by an external +# query engine: any server that speaks the PostgreSQL wire protocol and runs +# DuckDB SQL. Most tests use the test pgduck_server itself as that engine, and +# create the remote tables in this schema of its DuckDB database. +ENGINE_SCHEMA = "ext_engine_remote" + + +def engine_conninfo(): + # Read at run time: installcheck moves pgduck_server to another port after + # this module is imported. + return ( + f"host={server_params.PGDUCK_UNIX_DOMAIN_PATH} port={server_params.PGDUCK_PORT}" + ) + + +# Other tests use the test PostgreSQL server as the engine, which runs the +# simple queries they send, and which makes these remote users authenticate +# with a password. +PG_ENGINE_SCHEMA = "ext_engine_pg_remote" +PG_ENGINE_READER = "ext_engine_reader" +PG_ENGINE_OWNER = "ext_engine_owner" +PG_ENGINE_PASSWORD = "it's a back\\slash" + + +def quote_literal(value): + return "'" + value.replace("'", "''") + "'" + + +@pytest.fixture(scope="module") +def engine_tables(pgduck_conn): + run_command( + f""" + CREATE SCHEMA {ENGINE_SCHEMA}; + + -- the columns are in a different order than in the foreign table + CREATE TABLE {ENGINE_SCHEMA}.events (label varchar, id integer, amount double); + INSERT INTO {ENGINE_SCHEMA}.events + SELECT 'event ' || i, i, i * 1.5 FROM range(1, 101) t(i); + + CREATE TABLE {ENGINE_SCHEMA}.users (id integer, name varchar); + INSERT INTO {ENGINE_SCHEMA}.users SELECT i, 'user ' || i FROM range(1, 11) t(i); + + -- two columns of the same type, swapped compared to the foreign table + CREATE TABLE {ENGINE_SCHEMA}.swapped (b integer, extra varchar, a integer); + INSERT INTO {ENGINE_SCHEMA}.swapped SELECT i * 10, 'x', i FROM range(1, 4) t(i); + + -- takes minutes unless the engine cancels it, in constant memory + CREATE VIEW {ENGINE_SCHEMA}.slow AS SELECT range AS x FROM range(1000000000000); + """, + pgduck_conn, + ) + pgduck_conn.commit() + + yield + + run_command(f"DROP SCHEMA {ENGINE_SCHEMA} CASCADE", pgduck_conn) + pgduck_conn.commit() + + +@pytest.fixture(scope="module") +def engine_server(superuser_conn, extension, engine_tables, app_user): + run_command( + f""" + CREATE SERVER ext_engine FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}'); + + -- the engine uses trust authentication + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine + OPTIONS (password_required 'false'); + + CREATE SCHEMA ext_engine; + GRANT USAGE ON SCHEMA ext_engine TO {app_user}; + + CREATE FOREIGN TABLE ext_engine.events (id int, amount float8, label text) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'events'); + + CREATE FOREIGN TABLE ext_engine.users (id int, name text) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + + CREATE FOREIGN TABLE ext_engine.slow (x bigint) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'slow'); + + -- writes are refused by the table, not by missing privileges + GRANT ALL ON ALL TABLES IN SCHEMA ext_engine TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + yield + + run_command( + "DROP SCHEMA ext_engine CASCADE; DROP SERVER ext_engine CASCADE;", + superuser_conn, + ) + superuser_conn.commit() + + +@pytest.fixture(scope="module") +def pg_engine(installcheck, superuser_conn, engine_server, app_user): + """ + The test PostgreSQL server as an external engine. Its remote users have to + authenticate with a password, so a query returns the remote user only if + the user and password of the user mapping reached the engine intact. + """ + if installcheck: + pytest.skip("Changes pg_hba.conf of the test server") + + hba_file = run_query("SHOW hba_file", superuser_conn)[0][0] + with open(hba_file) as f: + original_hba = f.read() + + with open(hba_file, "w") as f: + f.write( + f"host all {PG_ENGINE_READER},{PG_ENGINE_OWNER} 127.0.0.1/32 scram-sha-256\n" + + original_hba + ) + + password = quote_literal(PG_ENGINE_PASSWORD) + + try: + run_command( + f""" + SELECT pg_reload_conf(); + + CREATE ROLE {PG_ENGINE_READER} LOGIN PASSWORD {password}; + CREATE ROLE {PG_ENGINE_OWNER} LOGIN PASSWORD {password}; + + CREATE SCHEMA {PG_ENGINE_SCHEMA}; + CREATE VIEW {PG_ENGINE_SCHEMA}.whoami AS SELECT current_user::text AS name; + CREATE VIEW {PG_ENGINE_SCHEMA}.slow AS SELECT 1 AS x FROM pg_sleep(600); + GRANT USAGE ON SCHEMA {PG_ENGINE_SCHEMA} TO {PG_ENGINE_READER}, {PG_ENGINE_OWNER}; + GRANT SELECT ON ALL TABLES IN SCHEMA {PG_ENGINE_SCHEMA} + TO {PG_ENGINE_READER}, {PG_ENGINE_OWNER}; + + CREATE SERVER ext_engine_pg FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=127.0.0.1 port={server_params.PG_PORT} dbname={server_params.PG_DATABASE}'); + + -- no password_required 'false', the engine asks for the password + CREATE USER MAPPING FOR {app_user} SERVER ext_engine_pg + OPTIONS (user '{PG_ENGINE_READER}', password {password}); + + CREATE FOREIGN TABLE ext_engine.whoami (name text) + SERVER ext_engine_pg OPTIONS (schema_name '{PG_ENGINE_SCHEMA}', table_name 'whoami'); + CREATE FOREIGN TABLE ext_engine.pg_slow (x int) + SERVER ext_engine_pg OPTIONS (schema_name '{PG_ENGINE_SCHEMA}', table_name 'slow'); + GRANT SELECT ON ext_engine.whoami, ext_engine.pg_slow TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + wait_for_password_authentication(PG_ENGINE_READER) + + yield + finally: + superuser_conn.rollback() + + with open(hba_file, "w") as f: + f.write(original_hba) + + run_command( + f""" + SELECT pg_reload_conf(); + DROP SERVER IF EXISTS ext_engine_pg CASCADE; + DROP SCHEMA IF EXISTS {PG_ENGINE_SCHEMA} CASCADE; + DROP ROLE IF EXISTS {PG_ENGINE_READER}, {PG_ENGINE_OWNER}; + """, + superuser_conn, + ) + superuser_conn.commit() + + +@pytest.fixture(autouse=True) +def fresh_transactions(superuser_conn, pg_conn): + """Start each test outside a transaction, also after a failed test.""" + rollback(pg_conn, superuser_conn) + yield + + +def wait_for_password_authentication(user): + """Wait until the server has reloaded pg_hba.conf and asks the user for a password.""" + + def asks_for_password(): + try: + psycopg2.connect( + host="127.0.0.1", + port=server_params.PG_PORT, + dbname=server_params.PG_DATABASE, + user=user, + password="", + ).close() + return False + except psycopg2.OperationalError as error: + assert "password" in str(error), error + return True + + wait_for(asks_for_password, "pg_hba.conf to be reloaded") + + +def rollback(*conns): + """End the transactions of connections, which hold locks after a failed test.""" + for conn in conns: + conn.rollback() + + +def wait_for(condition, what, timeout=30): + deadline = time.monotonic() + timeout + while not condition(): + if time.monotonic() > deadline: + raise AssertionError(f"timed out waiting for {what}") + time.sleep(0.1) + + +def current_count(query, conn): + """Run a count query in a new transaction, so that it sees fresh statistics.""" + conn.rollback() + count = run_query(query, conn)[0][0] + conn.rollback() + return count + + +def explain(query, conn): + result = run_query(f"EXPLAIN (VERBOSE, COSTS OFF) {query}", conn) + return "\n".join(row[0] for row in result) + + +def explain_servers(plan): + return [ + line.strip().removeprefix("Server: ") + for line in plan.splitlines() + if line.strip().startswith("Server: ") + ] + + +def set_full_pushdown(full_pushdown, conn): + run_command( + f"SET pg_lake_table.enable_full_query_pushdown TO {full_pushdown}", conn + ) + + +def test_server_options(superuser_conn, engine_server): + error = run_command( + "CREATE SERVER ext_bad FOREIGN DATA WRAPPER pg_lake_remote", + superuser_conn, + raise_error=False, + ) + assert '"conninfo" option is required' in error + superuser_conn.rollback() + + error = run_command( + "CREATE SERVER ext_bad FOREIGN DATA WRAPPER pg_lake_remote OPTIONS (conninfo '')", + superuser_conn, + raise_error=False, + ) + assert 'option "conninfo" cannot be empty' in error + superuser_conn.rollback() + + # anyone can read the options of a server, so the user and the secrets + # go into user mappings, and debug options are not offered at all + server_version = int(run_query("SHOW server_version_num", superuser_conn)[0][0]) + refused = ["user", "password", "sslpassword", "replication"] + if server_version >= 180000: + refused += ["oauth_client_secret", "sslkeylogfile"] + + for keyword in refused: + error = run_command( + f"""CREATE SERVER ext_bad FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=/tmp {keyword}=value')""", + superuser_conn, + raise_error=False, + ) + assert f'"conninfo" option cannot contain "{keyword}"' in error, keyword + superuser_conn.rollback() + + # client certificates of the server's own + run_command( + """CREATE SERVER ext_tls FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=/tmp sslmode=verify-full sslcert=/certs/c.crt sslkey=/certs/c.key')""", + superuser_conn, + ) + superuser_conn.rollback() + + error = run_command( + """CREATE SERVER ext_bad FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'not a conninfo')""", + superuser_conn, + raise_error=False, + ) + assert 'invalid "conninfo" option' in error + superuser_conn.rollback() + + error = run_command( + """CREATE SERVER ext_bad FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (connifo 'host=/tmp')""", + superuser_conn, + raise_error=False, + ) + assert 'Perhaps you meant the option "conninfo"' in error + superuser_conn.rollback() + + error = run_command( + "ALTER SERVER ext_engine OPTIONS (DROP conninfo)", + superuser_conn, + raise_error=False, + ) + assert '"conninfo" option is required' in error + superuser_conn.rollback() + + +def test_table_options(superuser_conn, engine_server): + error = run_command( + """CREATE FOREIGN TABLE ext_engine.bad (a int) SERVER ext_engine + OPTIONS (table_name 'users', path 's3://bucket/file.parquet')""", + superuser_conn, + raise_error=False, + ) + assert 'invalid option "path"' in error + superuser_conn.rollback() + + error = run_command( + """CREATE FOREIGN TABLE ext_engine.bad (a int) SERVER ext_engine + OPTIONS (table_name '')""", + superuser_conn, + raise_error=False, + ) + assert 'option "table_name" cannot be empty' in error + superuser_conn.rollback() + + # the remote table is never named after the foreign table + error = run_command( + "CREATE FOREIGN TABLE ext_engine.users_2 (a int) SERVER ext_engine", + superuser_conn, + raise_error=False, + ) + assert '"table_name" option is required for pg_lake_remote tables' in error + superuser_conn.rollback() + + error = run_command( + "ALTER FOREIGN TABLE ext_engine.users OPTIONS (DROP table_name)", + superuser_conn, + raise_error=False, + ) + assert '"table_name" option is required for pg_lake_remote tables' in error + superuser_conn.rollback() + + +def test_user_mapping_options(superuser_conn, pg_conn, engine_server, app_user): + error = run_command( + """CREATE USER MAPPING FOR CURRENT_USER SERVER ext_engine + OPTIONS (passwd 'secret')""", + superuser_conn, + raise_error=False, + ) + assert 'Perhaps you meant the option "password"' in error + superuser_conn.rollback() + + error = run_command( + """CREATE USER MAPPING FOR CURRENT_USER SERVER ext_engine + OPTIONS (sslmode 'require')""", + superuser_conn, + raise_error=False, + ) + assert 'invalid option "sslmode"' in error + superuser_conn.rollback() + + run_command( + f""" + CREATE SERVER ext_engine_tls FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()} sslmode=prefer'); + GRANT USAGE ON FOREIGN SERVER ext_engine_tls TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + # users set their own credentials, including the passphrase of the + # client key that a superuser set up for them + run_command( + """CREATE USER MAPPING FOR CURRENT_USER SERVER ext_engine_tls + OPTIONS (user 'me', password 'secret', sslpassword 'passphrase')""", + pg_conn, + ) + pg_conn.rollback() + + # client certificate and key files of this server are superuser-only + for option in ["sslcert '/certs/me.crt'", "sslkey '/certs/me.key'"]: + error = run_command( + f"""CREATE USER MAPPING FOR CURRENT_USER SERVER ext_engine_tls + OPTIONS (user 'me', {option})""", + pg_conn, + raise_error=False, + ) + assert "sslcert and sslkey are superuser-only" in error + pg_conn.rollback() + + run_command( + f"""CREATE USER MAPPING FOR {app_user} SERVER ext_engine_tls + OPTIONS (user 'me', sslcert '/certs/me.crt', sslkey '/certs/me.key')""", + superuser_conn, + ) + superuser_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command("DROP SERVER ext_engine_tls CASCADE", superuser_conn) + superuser_conn.commit() + + +def test_non_superuser_cannot_create_server(pg_conn, engine_server): + error = run_command( + f"""CREATE SERVER ext_mine FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}')""", + pg_conn, + raise_error=False, + ) + assert "permission denied for foreign-data wrapper pg_lake_remote" in error + pg_conn.rollback() + + +def test_non_superuser_cannot_choose_the_remote_table( + superuser_conn, pg_conn, engine_server, app_user +): + # DuckDB reads a name it does not find in its catalog as a file or URL, + # with the engine's access to the file system and object storage + run_command( + f""" + GRANT USAGE ON FOREIGN SERVER ext_engine TO {app_user}; + + CREATE FOREIGN TABLE ext_engine_owned (id int, name text) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + ALTER FOREIGN TABLE ext_engine_owned OWNER TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + for options in [ + "table_name '/tmp/secret.csv'", + f"table_name 's3://{TEST_BUCKET}/secret.parquet'", + "schema_name '/tmp/secret', table_name 'csv'", + "table_name 'users'", + ]: + error = run_command( + f"""CREATE FOREIGN TABLE mine (a text) SERVER ext_engine + OPTIONS ({options})""", + pg_conn, + raise_error=False, + ) + assert "table_name and schema_name are superuser-only" in error, options + pg_conn.rollback() + + # nor is the name of the foreign table used instead + error = run_command( + 'CREATE FOREIGN TABLE "/tmp/secret.csv" (a text) SERVER ext_engine', + pg_conn, + raise_error=False, + ) + assert '"table_name" option is required' in error + pg_conn.rollback() + + # the owner of a table can rename it, which does not change what it reads + run_command( + 'ALTER FOREIGN TABLE ext_engine_owned RENAME TO "/tmp/secret.csv"', pg_conn + ) + assert run_query('SELECT count(*) FROM "/tmp/secret.csv"', pg_conn) == [[10]] + + for alter in [ + "SET table_name '/tmp/secret.csv'", + "DROP schema_name", + "SET schema_name '/tmp/secret'", + ]: + run_command("SAVEPOINT alter_options", pg_conn) + error = run_command( + f'ALTER FOREIGN TABLE "/tmp/secret.csv" OPTIONS ({alter})', + pg_conn, + raise_error=False, + ) + assert "table_name and schema_name are superuser-only" in error, alter + run_command("ROLLBACK TO SAVEPOINT alter_options", pg_conn) + + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + f""" + DROP FOREIGN TABLE ext_engine_owned; + REVOKE USAGE ON FOREIGN SERVER ext_engine FROM {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_scan_and_filter(pg_conn, engine_server, full_pushdown): + set_full_pushdown(full_pushdown, pg_conn) + + result = run_query( + "SELECT id, amount, label FROM ext_engine.events WHERE id IN (3, 42) ORDER BY id", + pg_conn, + ) + assert result == [[3, 4.5, "event 3"], [42, 63.0, "event 42"]] + + result = run_query("SELECT count(*), sum(id) FROM ext_engine.events", pg_conn) + assert result == [[100, 5050]] + + query = "SELECT label FROM ext_engine.events WHERE id = 7" + plan = explain(query, pg_conn) + scan = "Custom Scan (Query Pushdown)" if full_pushdown else "Foreign Scan" + assert scan in plan + assert "Server: ext_engine" in plan + assert f"FROM {ENGINE_SCHEMA}.events" in plan + assert '("id" = 7)' in plan + assert run_query(query, pg_conn) == [["event 7"]] + + pg_conn.rollback() + + +def test_aggregates_and_joins_pushed_down_whole(pg_conn, engine_server): + query = """ + SELECT u.name, count(*), sum(e.amount) + FROM ext_engine.events e JOIN ext_engine.users u ON (e.id % 10 + 1 = u.id) + WHERE e.id <= 50 + GROUP BY u.name + ORDER BY u.name + LIMIT 3 + """ + plan = explain(query, pg_conn) + assert plan.count("Custom Scan (Query Pushdown)") == 1 + assert "Foreign Scan" not in plan + assert f"FROM {ENGINE_SCHEMA}.events" in plan + assert f"FROM {ENGINE_SCHEMA}.users" in plan + assert "JOIN" in plan and "GROUP BY" in plan + + result = run_query(query, pg_conn) + assert result == [["user 1", 5, 225.0], ["user 10", 5, 217.5], ["user 2", 5, 157.5]] + + # functions that pg_lake rewrites into its DuckDB functions run on the engine + query = "SELECT initcap(label) FROM ext_engine.events WHERE id = 1" + assert_query_pushdownable(query, pg_conn) + assert run_query(query, pg_conn) == [["Event 1"]] + + # the FDW path pushes the join and aggregate down too + set_full_pushdown(False, pg_conn) + plan = explain( + "SELECT count(*) FROM ext_engine.events e JOIN ext_engine.users u USING (id)", + pg_conn, + ) + assert plan.count("Foreign Scan") == 1 + assert "JOIN" in plan and "count(*)" in plan + assert run_query( + "SELECT count(*) FROM ext_engine.events e JOIN ext_engine.users u USING (id)", + pg_conn, + ) == [[10]] + + pg_conn.rollback() + + +def test_set_operations(pg_conn, engine_server, with_default_location): + # tables of one engine are pushed down whole + queries = [ + ( + "SELECT id FROM ext_engine.events WHERE id <= 2 UNION ALL " + "SELECT id FROM ext_engine.users WHERE id <= 2 ORDER BY 1", + [[1], [1], [2], [2]], + ), + ( + "SELECT id FROM ext_engine.events INTERSECT " + "SELECT id + 95 FROM ext_engine.users ORDER BY 1", + [[96], [97], [98], [99], [100]], + ), + ( + "SELECT id FROM ext_engine.users EXCEPT " + "SELECT id FROM ext_engine.events WHERE id > 3 ORDER BY 1", + [[1], [2], [3]], + ), + ] + + for query, expected in queries: + plan = explain(query, pg_conn) + assert plan.count("Custom Scan (Query Pushdown)") == 1, query + assert "Foreign Scan" not in plan, query + assert run_query(query, pg_conn) == expected, query + + # with a table of another engine, each side is scanned by its own engine + run_command( + """ + CREATE TABLE ext_engine_lake_ids (id int) USING iceberg; + INSERT INTO ext_engine_lake_ids VALUES (2), (1000); + """, + pg_conn, + ) + + query = """ + SELECT id FROM ext_engine.users WHERE id <= 3 + UNION SELECT id FROM ext_engine_lake_ids ORDER BY 1 + """ + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan + assert "Foreign Scan on ext_engine.users" in plan + assert "Table on another query engine" in plan + assert run_query(query, pg_conn) == [[1], [2], [3], [1000]] + + pg_conn.rollback() + + +def test_join_with_heap_table(pg_conn, engine_server): + run_command( + """ + CREATE TABLE ext_engine_heap (id int, city text); + INSERT INTO ext_engine_heap VALUES (2, 'Ankara'), (5, 'Izmir'), (500, 'nowhere'); + """, + pg_conn, + ) + + query = """ + SELECT e.id, e.label, h.city + FROM ext_engine.events e JOIN ext_engine_heap h USING (id) + ORDER BY e.id + """ + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan + assert "Foreign Scan on ext_engine.events" in plan + assert "Server: ext_engine" in plan + + result = run_query(query, pg_conn) + assert result == [[2, "event 2", "Ankara"], [5, "event 5", "Izmir"]] + + pg_conn.rollback() + + +def test_join_with_lake_table(pg_conn, engine_server, with_default_location): + run_command( + """ + CREATE TABLE ext_engine_lake (id int, city text) USING iceberg; + INSERT INTO ext_engine_lake VALUES (3, 'Paris'), (4, 'Berlin'), (400, 'nowhere'); + """, + pg_conn, + ) + + queries = [ + "SELECT e.id, e.label, l.city FROM ext_engine.events e JOIN ext_engine_lake l USING (id) ORDER BY 1", + # the engines also have to match across subqueries + "SELECT e.id, e.label, (SELECT city FROM ext_engine_lake l WHERE l.id = e.id) FROM ext_engine.events e WHERE e.id IN (3, 4) ORDER BY 1", + ] + + for query in queries: + # each table is scanned by its own engine + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan + assert "Foreign Scan on ext_engine.events" in plan + assert "Foreign Scan on public.ext_engine_lake" in plan + assert "Table on another query engine" in plan + + result = run_query(query, pg_conn) + assert result == [[3, "event 3", "Paris"], [4, "event 4", "Berlin"]] + + # the lake table alone is still pushed down to pgduck_server + plan = explain("SELECT count(*) FROM ext_engine_lake", pg_conn) + assert "Custom Scan (Query Pushdown)" in plan + assert "Server:" not in plan + + pg_conn.rollback() + + +def test_partitions_and_inheritance(superuser_conn, pg_conn, engine_server, app_user): + run_command( + f""" + -- a partitioned table with a partition on the engine + CREATE TABLE ext_engine.parted (id int, name text) PARTITION BY RANGE (id); + CREATE FOREIGN TABLE ext_engine.parted_remote PARTITION OF ext_engine.parted + FOR VALUES FROM (1) TO (11) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + CREATE TABLE ext_engine.parted_local PARTITION OF ext_engine.parted + FOR VALUES FROM (11) TO (MAXVALUE); + INSERT INTO ext_engine.parted_local VALUES (11, 'local 11'), (12, 'local 12'); + + -- a heap table with a child on the engine + CREATE TABLE ext_engine.heap_parent (id int, name text); + INSERT INTO ext_engine.heap_parent VALUES (100, 'parent'); + CREATE FOREIGN TABLE ext_engine.remote_child () INHERITS (ext_engine.heap_parent) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + + -- a table on the engine with a heap child + CREATE FOREIGN TABLE ext_engine.remote_parent (id int, name text) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + CREATE TABLE ext_engine.heap_child () INHERITS (ext_engine.remote_parent); + INSERT INTO ext_engine.heap_child VALUES (200, 'child'); + + GRANT SELECT ON ext_engine.parted, ext_engine.heap_parent, + ext_engine.remote_parent TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + + for table, expected in [ + ("parted", [[12, 78]]), + ("heap_parent", [[11, 155]]), + ("remote_parent", [[11, 255]]), + ]: + query = f"SELECT count(*), sum(id) FROM ext_engine.{table}" + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan, query + assert "Foreign Scan on ext_engine." in plan, query + assert run_query(query, pg_conn) == expected, query + + # partition pruning leaves only the engine + query = "SELECT name FROM ext_engine.parted WHERE id = 3" + plan = explain(query, pg_conn) + assert "parted_local" not in plan + assert run_query(query, pg_conn) == [["user 3"]] + + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + """ + DROP TABLE ext_engine.parted; + DROP TABLE ext_engine.heap_parent CASCADE; + DROP FOREIGN TABLE ext_engine.remote_parent CASCADE; + """, + superuser_conn, + ) + superuser_conn.commit() + + +def test_views(superuser_conn, pg_conn, engine_server, app_user): + run_command( + f""" + CREATE ROLE ext_engine_view_owner; + GRANT USAGE ON SCHEMA ext_engine TO ext_engine_view_owner; + GRANT SELECT ON ext_engine.events, ext_engine.users TO ext_engine_view_owner; + + CREATE VIEW ext_engine.event_users AS + SELECT e.id, e.label, u.name + FROM ext_engine.events e JOIN ext_engine.users u USING (id); + ALTER VIEW ext_engine.event_users OWNER TO ext_engine_view_owner; + GRANT SELECT ON ext_engine.event_users TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + # the tables of the view are read as its owner, so the view alone is + # pushed down whole + query = "SELECT count(*), min(label), max(name) FROM ext_engine.event_users" + plan = explain(query, pg_conn) + assert plan.count("Custom Scan (Query Pushdown)") == 1 + assert "Foreign Scan" not in plan + assert run_query(query, pg_conn) == [[10, "event 1", "user 9"]] + + # a query engine gets a query as one user, while here one table is + # read as the owner of the view and the other as the current user + query = """ + SELECT v.id, u.name FROM ext_engine.event_users v + JOIN ext_engine.users u ON (u.id = v.id + 1) + WHERE v.id <= 2 ORDER BY 1 + """ + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan + if full_pushdown: + assert "Table read as another user" in plan + + # the join in the view is still pushed down to the engine + assert plan.count("Foreign Scan") == 2 + assert run_query(query, pg_conn) == [[1, "user 2"], [2, "user 3"]] + + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + """ + DROP VIEW ext_engine.event_users; + DROP OWNED BY ext_engine_view_owner; + DROP ROLE ext_engine_view_owner; + """, + superuser_conn, + ) + superuser_conn.commit() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_cursors(pg_conn, engine_server, full_pushdown): + pg_conn.notices.clear() + + try: + check_cursors(pg_conn, full_pushdown) + finally: + pg_conn.rollback() + run_command("RESET pg_lake_table.enable_full_query_pushdown", pg_conn) + pg_conn.commit() + + # every scan released its connection + assert not any("released" in notice for notice in pg_conn.notices), pg_conn.notices + + +def check_cursors(pg_conn, full_pushdown): + set_full_pushdown(full_pushdown, pg_conn) + + run_command( + "DECLARE c CURSOR FOR SELECT id FROM ext_engine.events ORDER BY id", pg_conn + ) + assert run_query("FETCH 3 FROM c", pg_conn) == [[1], [2], [3]] + assert run_query("FETCH 2 FROM c", pg_conn) == [[4], [5]] + run_command("CLOSE c", pg_conn) + + # scrollable cursors are never pushed down whole + run_command( + """DECLARE s SCROLL CURSOR FOR + SELECT id FROM ext_engine.events WHERE id <= 5 ORDER BY id""", + pg_conn, + ) + assert run_query("FETCH LAST FROM s", pg_conn) == [[5]] + assert run_query("FETCH BACKWARD 2 FROM s", pg_conn) == [[4], [3]] + assert run_query("FETCH ABSOLUTE 1 FROM s", pg_conn) == [[1]] + run_command("CLOSE s", pg_conn) + pg_conn.commit() + + # a holdable cursor reads the whole result when the transaction commits + run_command( + """DECLARE h CURSOR WITH HOLD FOR + SELECT id, name FROM ext_engine.users WHERE id <= 3 ORDER BY id""", + pg_conn, + ) + pg_conn.commit() + assert run_query("FETCH ALL FROM h", pg_conn) == [ + [1, "user 1"], + [2, "user 2"], + [3, "user 3"], + ] + run_command("CLOSE h", pg_conn) + pg_conn.commit() + + +def test_tables_on_different_servers(superuser_conn, pg_conn, engine_server, app_user): + run_command( + f""" + CREATE SERVER ext_engine_other FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}'); + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine_other + OPTIONS (password_required 'false'); + CREATE FOREIGN TABLE ext_engine.other_users (id int, name text) + SERVER ext_engine_other OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + GRANT SELECT ON ext_engine.other_users TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + query = """ + SELECT e.label, u.name + FROM ext_engine.events e JOIN ext_engine.other_users u USING (id) + WHERE e.id <= 2 ORDER BY 1 + """ + + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan + assert plan.count("Foreign Scan") == 2 + assert sorted(explain_servers(plan)) == ["ext_engine", "ext_engine_other"] + + result = run_query(query, pg_conn) + assert result == [["event 1", "user 1"], ["event 2", "user 2"]] + + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command("DROP SERVER ext_engine_other CASCADE", superuser_conn) + superuser_conn.commit() + + +def test_columns_are_matched_by_name(superuser_conn, pg_conn, engine_server, app_user): + # the engine has (b, extra, a), the foreign table (a, b) + run_command( + f""" + CREATE FOREIGN TABLE ext_engine.swapped (a int, b int) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'swapped'); + GRANT SELECT ON ext_engine.swapped TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + assert run_query( + "SELECT a, b FROM ext_engine.swapped ORDER BY a", pg_conn + ) == [[1, 10], [2, 20], [3, 30]] + assert run_query( + "SELECT b FROM ext_engine.swapped WHERE a = 2", pg_conn + ) == [[20]] + assert run_query( + "SELECT sum(a), sum(b) FROM ext_engine.swapped", pg_conn + ) == [[6, 60]] + pg_conn.rollback() + + # dropped columns and columns added later are matched by name too, + # now (a, dropped b, extra, b) against (b, extra, a) + run_command( + """ + ALTER FOREIGN TABLE ext_engine.swapped DROP COLUMN b; + ALTER FOREIGN TABLE ext_engine.swapped ADD COLUMN extra text; + ALTER FOREIGN TABLE ext_engine.swapped ADD COLUMN b int; + """, + superuser_conn, + ) + superuser_conn.commit() + + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + assert run_query( + "SELECT * FROM ext_engine.swapped ORDER BY a", pg_conn + ) == [[1, "x", 10], [2, "x", 20], [3, "x", 30]] + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command("DROP FOREIGN TABLE ext_engine.swapped", superuser_conn) + superuser_conn.commit() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_columns_are_cast_to_declared_types( + superuser_conn, pg_conn, engine_server, app_user, full_pushdown +): + # the engine has (label varchar, id integer, amount double) + run_command( + f""" + CREATE FOREIGN TABLE ext_engine.retyped (id text, amount numeric(10,2), label text) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'events'); + CREATE FOREIGN TABLE ext_engine.unbounded (id int, amount numeric) + SERVER ext_engine OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'events'); + GRANT SELECT ON ext_engine.retyped, ext_engine.unbounded TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + set_full_pushdown(full_pushdown, pg_conn) + + # the engine compares and sorts the integers as text + assert run_query("SELECT max(id) FROM ext_engine.retyped", pg_conn) == [["99"]] + assert run_query( + "SELECT id FROM ext_engine.retyped ORDER BY id LIMIT 3", pg_conn + ) == [["1"], ["10"], ["100"]] + assert run_query( + "SELECT count(*) FROM ext_engine.retyped WHERE id < '2'", pg_conn + ) == [[12]] + + # and rounds the doubles to the declared scale + result = run_query( + "SELECT amount FROM ext_engine.retyped WHERE id = '3'", pg_conn + ) + assert str(result[0][0]) == "4.50" + + plan = explain("SELECT id FROM ext_engine.retyped WHERE id = '7'", pg_conn) + assert "CAST(id AS VARCHAR) AS id" in plan + assert "CAST(amount AS DECIMAL(10,2)) AS amount" in plan + + # a cast to the type the engine column already has is dropped by + # DuckDB, so the filter is applied by the scan of the engine table + plan = explain("SELECT label FROM ext_engine.events WHERE id = 7", pg_conn) + assert "CAST(id AS INTEGER) AS id" in plan + assert "Filters: id=7" in plan + + # numeric without a precision has no exact DuckDB type and is not cast + plan = explain("SELECT amount FROM ext_engine.unbounded WHERE id = 3", pg_conn) + assert "CAST(id AS INTEGER) AS id, amount FROM" in plan + assert run_query( + "SELECT amount FROM ext_engine.unbounded WHERE id = 3", pg_conn + ) == [[4.5]] + + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + "DROP FOREIGN TABLE ext_engine.retyped, ext_engine.unbounded", + superuser_conn, + ) + superuser_conn.commit() + + +def test_read_only(pg_conn, engine_server, with_default_location): + parquet_url = f"s3://{TEST_BUCKET}/test_external_engine_table/rows.parquet" + run_command( + f"COPY (SELECT 1000 AS id, 1.0::float8 AS amount, 'new' AS label) TO '{parquet_url}'", + pg_conn, + ) + pg_conn.commit() + + statements = [ + ( + "INSERT INTO ext_engine.events VALUES (1000, 1.0, 'new')", + "does not allow inserts", + ), + ("UPDATE ext_engine.events SET label = 'changed'", "does not allow updates"), + ("DELETE FROM ext_engine.events", "does not allow deletes"), + (f"COPY ext_engine.events FROM '{parquet_url}'", "does not allow inserts"), + ("TRUNCATE ext_engine.events", 'cannot truncate foreign table "events"'), + ] + + for statement, expected_error in statements: + error = run_command(statement, pg_conn, raise_error=False) + assert expected_error in error, statement + pg_conn.rollback() + + with pg_conn.cursor() as cursor: + with pytest.raises(psycopg2.Error, match="does not allow inserts"): + cursor.copy_expert("COPY ext_engine.events FROM STDIN", io.StringIO("")) + pg_conn.rollback() + + assert run_query("SELECT count(*) FROM ext_engine.events", pg_conn) == [[100]] + pg_conn.rollback() + + +def test_insert_select_into_lake_table(pg_conn, engine_server, with_default_location): + run_command( + """ + CREATE TABLE ext_engine_target (id int, label text) USING iceberg; + CREATE TABLE ext_engine_ids (id int) USING iceberg; + INSERT INTO ext_engine_ids VALUES (1), (2), (3), (4), (5); + """, + pg_conn, + ) + + # pgduck_server, which writes the lake table, cannot read the engine's + # table, so these read from the engine through the FDW, wherever the + # engine table is in the statement + queries = [ + "INSERT INTO ext_engine_target SELECT id, label FROM ext_engine.events WHERE id <= 5", + """WITH src AS (SELECT id, label FROM ext_engine.events WHERE id <= 5) + INSERT INTO ext_engine_target SELECT * FROM src""", + """INSERT INTO ext_engine_target + WITH src AS (SELECT id, label FROM ext_engine.events WHERE id <= 5) + SELECT * FROM src""", + """INSERT INTO ext_engine_target + SELECT id, 'event ' || id FROM ext_engine_ids + WHERE id IN (SELECT id FROM ext_engine.events)""", + ] + + for count, query in enumerate(queries, start=1): + plan = explain(query, pg_conn) + assert "Custom Scan (Query Pushdown)" not in plan, query + assert "Insert on public.ext_engine_target" in plan, query + assert "Foreign Scan on ext_engine.events" in plan, query + + run_command(query, pg_conn) + assert run_query( + "SELECT count(*), min(label), max(id) FROM ext_engine_target", pg_conn + ) == [[5 * count, "event 1", 5]], query + + # INSERT..SELECT from a lake table is still pushed down + plan = explain( + "INSERT INTO ext_engine_target SELECT * FROM ext_engine_target", pg_conn + ) + assert "Custom Scan (Query Pushdown)" in plan + + pg_conn.rollback() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_prepared_generic_plan(pg_conn, engine_server, full_pushdown): + run_command( + f""" + SET pg_lake_table.enable_full_query_pushdown TO {full_pushdown}; + SET plan_cache_mode TO force_generic_plan; + PREPARE ext_label(int) AS SELECT label FROM ext_engine.events WHERE id = $1; + PREPARE ext_count(int, text) AS + SELECT count(*) FROM ext_engine.events WHERE id <= $1 AND label <> $2; + """, + pg_conn, + ) + + # more executions than it takes to cache a plan + for i in range(1, 8): + assert run_query(f"EXECUTE ext_label({i * 3})", pg_conn) == [[f"event {i * 3}"]] + assert run_query(f"EXECUTE ext_count({i * 10}, 'event 1')", pg_conn) == [ + [i * 10 - 1] + ] + + plan = explain("EXECUTE ext_label(5)", pg_conn) + assert "$1" in plan + assert "Server: ext_engine" in plan + + run_command("DEALLOCATE ext_label; DEALLOCATE ext_count", pg_conn) + pg_conn.rollback() + + +def run_query_in_thread(query, conn): + """Start running a query in a thread, and return the thread and its errors.""" + errors = [] + + def run(): + try: + run_query(query, conn) + except psycopg2.Error as error: + errors.append(error) + + thread = threading.Thread(target=run) + thread.start() + return thread, errors + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_cancellation(superuser_conn, pg_conn, engine_server, full_pushdown): + set_full_pushdown(full_pushdown, pg_conn) + pg_conn.notices.clear() + + backend_pid = pg_conn.get_backend_pid() + thread, errors = run_query_in_thread("SELECT sum(x) FROM ext_engine.slow", pg_conn) + + try: + # cancelling before the query started would leave it running + wait_for( + lambda: current_count( + f"""SELECT count(*) FROM pg_stat_activity + WHERE pid = {backend_pid} AND state = 'active' + AND wait_event_type = 'Extension'""", + superuser_conn, + ) + == 1, + "the query to wait for the engine", + ) + # connecting takes milliseconds, after which it waits for the query + time.sleep(0.5) + + cancelled_at = time.monotonic() + pg_conn.cancel() + thread.join(timeout=30) + finally: + # keep the engine from running the query for minutes + while thread.is_alive(): + pg_conn.cancel() + thread.join(timeout=5) + + assert len(errors) == 1 + assert isinstance(errors[0], psycopg2.errors.QueryCanceled) + + # the engine stopped the query when it got the cancel request, instead of + # us giving up on it after the cleanup timeout + assert time.monotonic() - cancelled_at < 15 + assert not any("cancel request" in notice for notice in pg_conn.notices) + pg_conn.rollback() + + # the session can query the engine again + start = time.time() + assert run_query("SELECT count(*) FROM ext_engine.events", pg_conn) == [[100]] + assert time.time() - start < 10 + pg_conn.rollback() + + +def test_connecting_can_be_interrupted( + superuser_conn, pg_conn, engine_server, app_user +): + # a server that accepts the connection but never answers, like a host + # whose network drops the packets + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + listener.listen(16) + port = listener.getsockname()[1] + + try: + # without an interruptible connection, connect_timeout would end it + run_command( + f""" + CREATE SERVER ext_engine_hang FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=127.0.0.1 port={port} connect_timeout=30'); + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine_hang + OPTIONS (password_required 'false'); + CREATE FOREIGN TABLE ext_engine.hang (id int) + SERVER ext_engine_hang OPTIONS (table_name 'hang'); + GRANT SELECT ON ext_engine.hang TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + run_command("SET statement_timeout TO '1s'", pg_conn) + + start = time.monotonic() + error = run_command( + "SELECT * FROM ext_engine.hang", pg_conn, raise_error=False + ) + assert "canceling statement due to statement timeout" in error + assert time.monotonic() - start < 15 + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + listener.close() + run_command("DROP SERVER ext_engine_hang CASCADE", superuser_conn) + superuser_conn.commit() + + +def recv_exactly(sock, size): + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise OSError("connection closed") + data += chunk + return data + + +def test_abort_with_an_engine_that_ignores_cancel_requests( + superuser_conn, pg_conn, engine_server, app_user +): + if int(run_query("SHOW server_version_num", superuser_conn)[0][0]) < 170000: + pytest.skip("cancel requests only wait with a timeout from PostgreSQL 17") + + # a proxy in front of the engine that passes connections through, but + # accepts cancel requests and never answers them + engine_socket = ( + f"{server_params.PGDUCK_UNIX_DOMAIN_PATH}/.s.PGSQL.{server_params.PGDUCK_PORT}" + ) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + listener.listen(16) + port = listener.getsockname()[1] + ignored_cancel_requests = [] + + def forward(source, target): + try: + while data := source.recv(65536): + target.sendall(data) + except OSError: + pass + finally: + for sock in (source, target): + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + def serve(): + while True: + try: + client, _ = listener.accept() + startup = recv_exactly(client, 8) + except OSError: + return + + if startup[4:8] == (80877102).to_bytes(4, "big"): + ignored_cancel_requests.append(client) + continue + + engine = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + engine.connect(engine_socket) + engine.sendall(startup) + for source, target in [(client, engine), (engine, client)]: + threading.Thread( + target=forward, args=(source, target), daemon=True + ).start() + + threading.Thread(target=serve, daemon=True).start() + + try: + run_command( + f""" + CREATE SERVER ext_engine_proxy FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo 'host=127.0.0.1 port={port} sslmode=disable'); + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine_proxy + OPTIONS (password_required 'false'); + CREATE FOREIGN TABLE ext_engine.slow_proxy (x bigint) + SERVER ext_engine_proxy OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'slow'); + GRANT SELECT ON ext_engine.slow_proxy TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + # the engine still runs the query when the transaction aborts + run_command( + "DECLARE slow CURSOR FOR SELECT x FROM ext_engine.slow_proxy", pg_conn + ) + assert run_query("FETCH 1 FROM slow", pg_conn) == [[0]] + pg_conn.notices.clear() + + start = time.monotonic() + thread = threading.Thread(target=pg_conn.rollback, daemon=True) + thread.start() + thread.join(timeout=120) + + # the cancel request gives up after the cleanup timeout + assert not thread.is_alive(), "ROLLBACK waits for the cancel request" + assert time.monotonic() - start < 90 + assert len(ignored_cancel_requests) == 1 + assert any("could not send cancel request" in n for n in pg_conn.notices) + + # the session can query the engine again + assert run_query("SELECT count(*) FROM ext_engine.events", pg_conn) == [[100]] + pg_conn.rollback() + finally: + listener.close() + for sock in ignored_cancel_requests: + sock.close() + rollback(superuser_conn) + run_command("DROP SERVER ext_engine_proxy CASCADE", superuser_conn) + superuser_conn.commit() + + +def test_explain(pg_conn, engine_server): + query = "SELECT id, label FROM ext_engine.events WHERE amount > 140" + + plan = explain(query, pg_conn) + assert "Engine: DuckDB" in plan + assert "Server: ext_engine" in plan + assert ( + "FROM (SELECT CAST(id AS INTEGER) AS id, CAST(amount AS DOUBLE) AS amount, " + f"CAST(label AS VARCHAR) AS label FROM {ENGINE_SCHEMA}.events)" in plan + ), plan + # there are no files that pg_lake knows of + assert "Data Files Scanned" not in plan + + # the engine explains its part of the query + assert "SEQ_SCAN" in plan + assert "Filters: amount>140.0" in plan + + result = run_query(f"EXPLAIN (ANALYZE, VERBOSE, FORMAT JSON) {query}", pg_conn) + assert find_key_in_json(result[0][0], "Server") == "ext_engine" + assert ENGINE_SCHEMA in fetch_remote_sql(result) + + pg_conn.rollback() + + +def test_user_mapping(superuser_conn, pg_conn, engine_server, app_user): + run_command( + f""" + CREATE SERVER ext_engine_auth FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}'); + GRANT USAGE ON FOREIGN SERVER ext_engine_auth TO {app_user}; + CREATE FOREIGN TABLE ext_engine.auth_users (id int, name text) + SERVER ext_engine_auth OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + GRANT SELECT ON ext_engine.auth_users TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + query = "SELECT count(*) FROM ext_engine.auth_users" + + try: + # a superuser needs no user mapping + assert run_query(query, superuser_conn) == [[10]] + superuser_conn.commit() + + # a non-superuser needs a password + error = run_command(query, pg_conn, raise_error=False) + assert "password is required" in error + assert "Non-superusers must provide a password in the user mapping" in error + pg_conn.rollback() + + # which the engine has to ask for + run_command( + f"""CREATE USER MAPPING FOR {app_user} SERVER ext_engine_auth + OPTIONS (user 'remote_user', password 'secret')""", + superuser_conn, + ) + superuser_conn.commit() + + error = run_command(query, pg_conn, raise_error=False) + assert "password is required" in error + assert "does not request a password" in error + pg_conn.rollback() + + # only a superuser can lift that requirement + error = run_command( + f"""ALTER USER MAPPING FOR {app_user} SERVER ext_engine_auth + OPTIONS (ADD password_required 'false')""", + pg_conn, + raise_error=False, + ) + assert "password_required=false is superuser-only" in error + pg_conn.rollback() + + run_command( + f"""ALTER USER MAPPING FOR {app_user} SERVER ext_engine_auth + OPTIONS (ADD password_required 'false')""", + superuser_conn, + ) + superuser_conn.commit() + + assert run_query(query, pg_conn) == [[10]] + pg_conn.rollback() + + # credentials with quotes and backslashes still form a valid + # conninfo, also when the server conninfo is a URI (the engine does + # not check them, test_engine_credentials does) + run_command( + f""" + ALTER SERVER ext_engine_auth OPTIONS (SET conninfo + 'postgresql:///?host={server_params.PGDUCK_UNIX_DOMAIN_PATH}&port={server_params.PGDUCK_PORT}'); + CREATE USER MAPPING FOR CURRENT_USER SERVER ext_engine_auth + OPTIONS (user 'o''brien', password 'back\\slash ''quoted'''); + """, + superuser_conn, + ) + superuser_conn.commit() + + assert run_query(query, superuser_conn) == [[10]] + assert run_query(query, pg_conn) == [[10]] + superuser_conn.commit() + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command("DROP SERVER ext_engine_auth CASCADE", superuser_conn) + superuser_conn.commit() + + +def test_drop_server_and_table(superuser_conn, pgduck_conn, engine_server): + run_command( + f""" + CREATE TABLE {ENGINE_SCHEMA}.dropme (id integer); + INSERT INTO {ENGINE_SCHEMA}.dropme VALUES (1), (2); + """, + pgduck_conn, + ) + pgduck_conn.commit() + + run_command( + f""" + CREATE SERVER ext_engine_drop FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}'); + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine_drop; + CREATE FOREIGN TABLE ext_engine.dropme_1 (id int) + SERVER ext_engine_drop OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'dropme'); + CREATE FOREIGN TABLE ext_engine.dropme_2 (id int) + SERVER ext_engine_drop OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'dropme'); + """, + superuser_conn, + ) + superuser_conn.commit() + + assert run_query("SELECT sum(id) FROM ext_engine.dropme_1", superuser_conn) == [[3]] + + # dropping a foreign table leaves the remote table alone + run_command("DROP FOREIGN TABLE ext_engine.dropme_1", superuser_conn) + superuser_conn.commit() + assert run_query(f"SELECT count(*) FROM {ENGINE_SCHEMA}.dropme", pgduck_conn) == [ + [2] + ] + pgduck_conn.commit() + + # the server has a dependent table + error = run_command( + "DROP SERVER ext_engine_drop", superuser_conn, raise_error=False + ) + assert ( + "cannot drop server ext_engine_drop because other objects depend on it" in error + ) + superuser_conn.rollback() + + # a server that cannot be reached reports why + run_command( + "ALTER SERVER ext_engine_drop OPTIONS (SET conninfo 'host=/nonexistent port=1')", + superuser_conn, + ) + error = run_command( + "SELECT * FROM ext_engine.dropme_2", superuser_conn, raise_error=False + ) + assert 'could not connect to server "ext_engine_drop"' in error + superuser_conn.rollback() + + # a dropped remote table is reported by the engine, for the server + run_command(f"DROP TABLE {ENGINE_SCHEMA}.dropme", pgduck_conn) + pgduck_conn.commit() + + error = run_command( + "SELECT * FROM ext_engine.dropme_2", superuser_conn, raise_error=False + ) + assert "dropme does not exist" in error + assert 'remote query on server "ext_engine_drop"' in error + superuser_conn.rollback() + + run_command("DROP SERVER ext_engine_drop CASCADE", superuser_conn) + superuser_conn.commit() + + result = run_query( + """SELECT count(*) FROM pg_class + WHERE relname = 'dropme_2' AND relnamespace = 'ext_engine'::regnamespace""", + superuser_conn, + ) + assert result == [[0]] + superuser_conn.commit() + + +def test_pg_dump_and_restore(installcheck, superuser_conn, engine_server, app_user): + if installcheck: + pytest.skip("Requires an isolated test cluster") + + run_command( + f""" + CREATE SERVER ext_engine_dump FOREIGN DATA WRAPPER pg_lake_remote + OPTIONS (conninfo '{engine_conninfo()}'); + CREATE USER MAPPING FOR PUBLIC SERVER ext_engine_dump + OPTIONS (password_required 'false'); + CREATE USER MAPPING FOR {app_user} SERVER ext_engine_dump + OPTIONS (user 'o''brien', password 'back\\slash ''quoted'''); + CREATE FOREIGN TABLE ext_engine.dumped (id int, name text) + SERVER ext_engine_dump OPTIONS (schema_name '{ENGINE_SCHEMA}', table_name 'users'); + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + dump = subprocess.check_output( + ["pg_dump", "--dbname", superuser_conn.dsn, "--schema-only"], text=True + ) + statements = [ + statement + for pattern in [ + r"CREATE SERVER ext_engine_dump .*?;\n", + r"CREATE USER MAPPING FOR \S+ SERVER ext_engine_dump .*?;\n", + r"CREATE FOREIGN TABLE ext_engine\.dumped .*?;\n", + ] + for statement in re.findall(pattern, dump, re.DOTALL) + ] + assert len(statements) == 4, dump + + run_command("DROP SERVER ext_engine_dump CASCADE", superuser_conn) + superuser_conn.commit() + + for statement in statements: + run_command(statement, superuser_conn) + superuser_conn.commit() + + assert run_query( + "SELECT count(*), max(name) FROM ext_engine.dumped", superuser_conn + ) == [[10, "user 9"]] + options = run_query( + f"""SELECT umoptions FROM pg_user_mapping m JOIN pg_roles r ON (r.oid = m.umuser) + WHERE rolname = '{app_user}'""", + superuser_conn, + )[0][0] + assert sorted(options) == ["password=back\\slash 'quoted'", "user=o'brien"] + superuser_conn.commit() + finally: + rollback(superuser_conn) + run_command("DROP SERVER IF EXISTS ext_engine_dump CASCADE", superuser_conn) + superuser_conn.commit() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_engine_credentials( + superuser_conn, pg_conn, pg_engine, app_user, full_pushdown +): + set_full_pushdown(full_pushdown, pg_conn) + + # the engine checked the user and password of the user mapping + assert run_query("SELECT name FROM ext_engine.whoami", pg_conn) == [ + [PG_ENGINE_READER] + ] + pg_conn.rollback() + + run_command( + f"""ALTER USER MAPPING FOR {app_user} SERVER ext_engine_pg + OPTIONS (SET password 'wrong')""", + superuser_conn, + ) + superuser_conn.commit() + + try: + error = run_command( + "SELECT name FROM ext_engine.whoami", pg_conn, raise_error=False + ) + assert 'could not connect to server "ext_engine_pg"' in error + assert f'password authentication failed for user "{PG_ENGINE_READER}"' in error + pg_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + f"""ALTER USER MAPPING FOR {app_user} SERVER ext_engine_pg + OPTIONS (SET password {quote_literal(PG_ENGINE_PASSWORD)})""", + superuser_conn, + ) + superuser_conn.commit() + + +def test_view_uses_owner_user_mapping(superuser_conn, pg_conn, pg_engine, app_user): + password = quote_literal(PG_ENGINE_PASSWORD) + run_command( + f""" + CREATE ROLE ext_engine_pg_view_owner; + GRANT USAGE ON SCHEMA ext_engine TO ext_engine_pg_view_owner; + GRANT SELECT ON ext_engine.whoami TO ext_engine_pg_view_owner; + CREATE USER MAPPING FOR ext_engine_pg_view_owner SERVER ext_engine_pg + OPTIONS (user '{PG_ENGINE_OWNER}', password {password}); + + CREATE VIEW ext_engine.whoami_owner AS SELECT name FROM ext_engine.whoami; + ALTER VIEW ext_engine.whoami_owner OWNER TO ext_engine_pg_view_owner; + CREATE VIEW ext_engine.whoami_invoker WITH (security_invoker) + AS SELECT name FROM ext_engine.whoami; + GRANT SELECT ON ext_engine.whoami_owner, ext_engine.whoami_invoker TO {app_user}; + """, + superuser_conn, + ) + superuser_conn.commit() + + try: + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + set_full_pushdown(full_pushdown, superuser_conn) + + # like other tables, the engine's tables in a view are read as + # the owner of the view, with the owner's user mapping + for query, expected in [ + ("SELECT name FROM ext_engine.whoami", [[PG_ENGINE_READER]]), + ("SELECT name FROM ext_engine.whoami_owner", [[PG_ENGINE_OWNER]]), + ("SELECT name FROM ext_engine.whoami_invoker", [[PG_ENGINE_READER]]), + ( + """SELECT o.name, r.name FROM ext_engine.whoami_owner o, + ext_engine.whoami r""", + [[PG_ENGINE_OWNER, PG_ENGINE_READER]], + ), + ]: + assert run_query(query, pg_conn) == expected, query + pg_conn.rollback() + + # also for a superuser, who could connect without a password + assert run_query( + "SELECT name FROM ext_engine.whoami_owner", superuser_conn + ) == [[PG_ENGINE_OWNER]] + superuser_conn.rollback() + finally: + rollback(pg_conn, superuser_conn) + run_command( + """ + DROP VIEW ext_engine.whoami_owner, ext_engine.whoami_invoker; + DROP OWNED BY ext_engine_pg_view_owner; + DROP ROLE ext_engine_pg_view_owner; + """, + superuser_conn, + ) + superuser_conn.commit() + + +def test_engine_errors_name_the_server(pg_conn, pg_engine): + # PostgreSQL lacks the DuckDB functions that pg_lake pushes down + error = run_command( + "SELECT initcap(name) FROM ext_engine.whoami", pg_conn, raise_error=False + ) + assert "function initcap_pg(" in error and "does not exist" in error + assert 'remote query on server "ext_engine_pg"' in error + pg_conn.rollback() + + # and returns another query plan than DuckDB + for full_pushdown in [True, False]: + set_full_pushdown(full_pushdown, pg_conn) + error = run_command( + "EXPLAIN SELECT name FROM ext_engine.whoami", pg_conn, raise_error=False + ) + assert 'server "ext_engine_pg" did not return a DuckDB query plan' in error + pg_conn.rollback() + + +@pytest.mark.parametrize("full_pushdown", [True, False], ids=["pushdown", "fdw"]) +def test_cancellation_reaches_the_engine( + superuser_conn, pg_conn, pg_engine, full_pushdown +): + set_full_pushdown(full_pushdown, pg_conn) + + remote_query = f""" + SELECT count(*) FROM pg_stat_activity + WHERE usename = '{PG_ENGINE_READER}' AND wait_event = 'PgSleep' + """ + thread, errors = run_query_in_thread("SELECT x FROM ext_engine.pg_slow", pg_conn) + + try: + wait_for( + lambda: current_count(remote_query, superuser_conn) == 1, + "the query to run on the engine", + ) + pg_conn.cancel() + thread.join(timeout=30) + finally: + while thread.is_alive(): + pg_conn.cancel() + thread.join(timeout=5) + + assert len(errors) == 1 + assert isinstance(errors[0], psycopg2.errors.QueryCanceled) + pg_conn.rollback() + + # the engine stopped running it + wait_for( + lambda: current_count(remote_query, superuser_conn) == 0, + "the engine to cancel the query", + )