The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(db): let a plugin call only an allowlist of Postgres's catalog functions
Maurice2edf5f807aa4
diff --git a/plugin-sdk/README.md b/plugin-sdk/README.mdindex 2cf7efdda..633a32f6c 100644--- a/plugin-sdk/README.md+++ b/plugin-sdk/README.md@@ -210,6 +210,27 @@ What changes on Postgres:`regconfig`, `regdictionary`, `regnamespace`, `regrole`, `regcollation` and their arrays(`'x'::regtype`, `CAST('x' AS regtype)`, `regtype 'x'`). An alias that shares a schema'sname is refused too, so pick another.+- **Postgres's own functions: an allowlist.** You may call the functions that work only on+ their arguments: strings and bytes (`lower`, `substring`, `regexp_replace`, `format`,+ `md5`, `sha256`, ...), numbers (`round`, `abs`, `random`, ...), dates and times (`now`,+ `date_trunc`, `extract`, `to_char`, `make_date`, ...), the conversions (`numeric(10, 2)`,+ `varchar(20)`, `int8`, ...), JSON and JSONB (`jsonb_build_object`, `jsonb_set`,+ `jsonb_path_query`, ...), arrays (`unnest`, `array_agg`, `generate_series`, ...),+ aggregates and window functions (`count`, `sum`, `string_agg`, `row_number`, `lag`, ...),+ UUIDs (`gen_random_uuid`), ranges, geometry, network addresses and full text search+ (`to_tsvector`, `ts_rank`, ...). Any other function of Postgres's catalog is refused+ however you spell the call (`f(...)`, `"f"(...)`, the column notation `(x).f`): the ones+ that read the catalogs or the server rather than their arguments (`obj_description`,+ `col_description`, `format_type`, `version`, `current_database`, `inet_server_addr`,+ `txid_current`, ...), and so is every new function a later Postgres adds until TREK has+ decided about it. The keywords `current_user`, `session_user`, `current_role`, `user`,+ `system_user`, `current_catalog` and `current_schema` are refused too. `coalesce`,+ `nullif`, `greatest`, `least`, `CASE` and `CAST` are syntax and always work. The complete+ list is `PLUGIN_FUNCTIONS` in TREK's+ [`plugin-sql-functions.ts`](https://github.com/liketrek/TREK/blob/main/server/src/db/engine/postgres/plugin-sql-functions.ts).+ A table or type of yours may still share a refused function's name where it cannot be a+ call (`INSERT INTO version (...)`, `CREATE TABLE version (...)`, `REFERENCES version (id)`);+ as the table of `CREATE INDEX ... ON` it cannot, so name it differently.- **You change your own objects only.** Right before an `ALTER`, `DROP`, `REFRESH`,`TRUNCATE` or `CREATE INDEX ... ON` runs, Postgres resolves the object it names (and thetables a `CREATE`/`ALTER TABLE` ties to with `REFERENCES`, `INHERITS`, `PARTITION OF`,diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex b178fdb2c..b41a2a88a 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -79,7 +79,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c- **Realtime**: `/ws` is a Nest gateway in `src/nest/realtime/`. Inject `RealtimeService`; tests hand in a `FakeRealtimeService` (`tests/helpers/fake-realtime.ts`) or spy on the container's instance instead of mocking the transport module. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.- **MCP**: `src/nest-mcp/` is the decorator/registry layer (`@McpController`/`@Tool`/`@Resource`/`@Prompt`; see its `README.md`); tools live in `<domain>.mcp.ts` files beside each module; the HTTP transport is `src/nest/mcp-transport/`; `src/mcp/` holds process-wide state only (scopes, session manager, boot policy). Every tool invocation writes an audit row through the registry's `onInvoke` seam. The demo-mode write block is the registry's `toolGate` (`trekDemoToolGate`): every tool not annotated read-only refuses a demo account there (except the write tools in `DEMO_UNGATED_WRITE_TOOLS`, which never had a demo check), so a tool never checks demo mode itself (ESLint refuses it in `*.mcp.ts`). MCP tools are adapters over the same services and permission checks as REST — a change on one side lands on the other in the same change.- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator**: it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire`, one conditional upsert that decides the race), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.-- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL (`host/plugin-data.service.ts`) is held to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed). Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`, `src/db/engine/postgres/plugin-data-store.ts`) whose SQL is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types and the functions that look an object up by name; the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). A plugin argument holding NUL is refused there, since Postgres text cannot hold it, while the plugin's SQLite file binds it exactly; the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.+- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL (`host/plugin-data.service.ts`) is held to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed). Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`, `src/db/engine/postgres/plugin-data-store.ts`) whose SQL is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, and every function of `pg_catalog` outside the allowlist in `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). A plugin argument holding NUL is refused there, since Postgres text cannot hold it, while the plugin's SQLite file binds it exactly; the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; a provider that reads one injects `DataPathsService`, plain helper modules shared with code outside the container call `resolveDataPaths()` (the list is in `src/app-config/README.md`), and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character it drops, as every write does), copies each plugin's `plugin.db` into its schema, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.diff --git a/server/assets/postgres/catalog-functions.txt b/server/assets/postgres/catalog-functions.txtnew file mode 100644index 000000000..56e006dae--- /dev/null+++ b/server/assets/postgres/catalog-functions.txt@@ -0,0 +1,2810 @@+RI_FKey_cascade_del+RI_FKey_cascade_upd+RI_FKey_check_ins+RI_FKey_check_upd+RI_FKey_noaction_del+RI_FKey_noaction_upd+RI_FKey_restrict_del+RI_FKey_restrict_upd+RI_FKey_setdefault_del+RI_FKey_setdefault_upd+RI_FKey_setnull_del+RI_FKey_setnull_upd+abbrev+abs+aclcontains+acldefault+aclexplode+aclinsert+aclitemeq+aclitemin+aclitemout+aclremove+acos+acosd+acosh+age+amvalidate+any_in+any_out+any_value+any_value_transfn+anyarray_in+anyarray_out+anyarray_recv+anyarray_send+anycompatible_in+anycompatible_out+anycompatiblearray_in+anycompatiblearray_out+anycompatiblearray_recv+anycompatiblearray_send+anycompatiblemultirange_in+anycompatiblemultirange_out+anycompatiblenonarray_in+anycompatiblenonarray_out+anycompatiblerange_in+anycompatiblerange_out+anyelement_in+anyelement_out+anyenum_in+anyenum_out+anymultirange_in+anymultirange_out+anynonarray_in+anynonarray_out+anyrange_in+anyrange_out+anytextcat+area+areajoinsel+areasel+array_agg+array_agg_array_combine+array_agg_array_deserialize+array_agg_array_finalfn+array_agg_array_serialize+array_agg_array_transfn+array_agg_combine+array_agg_deserialize+array_agg_finalfn+array_agg_serialize+array_agg_transfn+array_append+array_append_support+array_cat+array_dims+array_eq+array_fill+array_ge+array_gt+array_in+array_larger+array_le+array_length+array_lower+array_lt+array_ndims+array_ne+array_out+array_position+array_positions+array_prepend+array_prepend_support+array_recv+array_remove+array_replace+array_reverse+array_sample+array_send+array_shuffle+array_smaller+array_sort+array_subscript_handler+array_subscript_handler_support+array_to_json+array_to_string+array_to_tsvector+array_typanalyze+array_unnest_support+array_upper+arraycontained+arraycontains+arraycontjoinsel+arraycontsel+arrayoverlap+ascii+asin+asind+asinh+atan+atan2+atan2d+atand+atanh+avg+bernoulli+big5_to_euc_tw+big5_to_mic+big5_to_utf8+binary_upgrade_add_sub_rel_state+binary_upgrade_create_empty_extension+binary_upgrade_logical_slot_has_caught_up+binary_upgrade_replorigin_advance+binary_upgrade_set_missing_value+binary_upgrade_set_next_array_pg_type_oid+binary_upgrade_set_next_attribute_versions+binary_upgrade_set_next_heap_pg_class_oid+binary_upgrade_set_next_heap_relfilenode+binary_upgrade_set_next_index_pg_class_oid+binary_upgrade_set_next_index_relfilenode+binary_upgrade_set_next_multirange_array_pg_type_oid+binary_upgrade_set_next_multirange_pg_type_oid+binary_upgrade_set_next_pg_authid_oid+binary_upgrade_set_next_pg_enum_oid+binary_upgrade_set_next_pg_tablespace_oid+binary_upgrade_set_next_pg_type_oid+binary_upgrade_set_next_toast_pg_class_oid+binary_upgrade_set_next_toast_relfilenode+binary_upgrade_set_record_init_privs+bit+bit_and+bit_count+bit_in+bit_length+bit_or+bit_out+bit_recv+bit_send+bit_xor+bitand+bitcat+bitcmp+biteq+bitge+bitgt+bitle+bitlt+bitne+bitnot+bitor+bitshiftleft+bitshiftright+bittypmodin+bittypmodout+bitxor+bool+bool_accum+bool_accum_inv+bool_alltrue+bool_and+bool_anytrue+bool_or+booland_statefunc+booleq+boolge+boolgt+boolin+boolle+boollt+boolne+boolor_statefunc+boolout+boolrecv+boolsend+bound_box+box+box_above+box_above_eq+box_add+box_below+box_below_eq+box_center+box_contain+box_contain_pt+box_contained+box_distance+box_div+box_eq+box_ge+box_gt+box_in+box_intersect+box_le+box_left+box_lt+box_mul+box_out+box_overabove+box_overbelow+box_overlap+box_overleft+box_overright+box_recv+box_right+box_same+box_send+box_sub+bpchar+bpchar_larger+bpchar_pattern_ge+bpchar_pattern_gt+bpchar_pattern_le+bpchar_pattern_lt+bpchar_smaller+bpchar_sortsupport+bpcharcmp+bpchareq+bpcharge+bpchargt+bpchariclike+bpcharicnlike+bpcharicregexeq+bpcharicregexne+bpcharin+bpcharle+bpcharlike+bpcharlt+bpcharne+bpcharnlike+bpcharout+bpcharrecv+bpcharregexeq+bpcharregexne+bpcharsend+bpchartypmodin+bpchartypmodout+brin_bloom_add_value+brin_bloom_consistent+brin_bloom_opcinfo+brin_bloom_options+brin_bloom_summary_in+brin_bloom_summary_out+brin_bloom_summary_recv+brin_bloom_summary_send+brin_bloom_union+brin_desummarize_range+brin_inclusion_add_value+brin_inclusion_consistent+brin_inclusion_opcinfo+brin_inclusion_union+brin_minmax_add_value+brin_minmax_consistent+brin_minmax_multi_add_value+brin_minmax_multi_consistent+brin_minmax_multi_distance_date+brin_minmax_multi_distance_float4+brin_minmax_multi_distance_float8+brin_minmax_multi_distance_inet+brin_minmax_multi_distance_int2+brin_minmax_multi_distance_int4+brin_minmax_multi_distance_int8+brin_minmax_multi_distance_interval+brin_minmax_multi_distance_macaddr+brin_minmax_multi_distance_macaddr8+brin_minmax_multi_distance_numeric+brin_minmax_multi_distance_pg_lsn+brin_minmax_multi_distance_tid+brin_minmax_multi_distance_time+brin_minmax_multi_distance_timestamp+brin_minmax_multi_distance_timetz+brin_minmax_multi_distance_uuid+brin_minmax_multi_opcinfo+brin_minmax_multi_options+brin_minmax_multi_summary_in+brin_minmax_multi_summary_out+brin_minmax_multi_summary_recv+brin_minmax_multi_summary_send+brin_minmax_multi_union+brin_minmax_opcinfo+brin_minmax_union+brin_summarize_new_values+brin_summarize_range+brinhandler+broadcast+btarraycmp+btboolcmp+btboolskipsupport+btbpchar_pattern_cmp+btbpchar_pattern_sortsupport+btcharcmp+btcharskipsupport+btequalimage+btfloat48cmp+btfloat4cmp+btfloat4sortsupport+btfloat84cmp+btfloat8cmp+btfloat8sortsupport+bthandler+btint24cmp+btint28cmp+btint2cmp+btint2skipsupport+btint2sortsupport+btint42cmp+btint48cmp+btint4cmp+btint4skipsupport+btint4sortsupport+btint82cmp+btint84cmp+btint8cmp+btint8skipsupport+btint8sortsupport+btnamecmp+btnamesortsupport+btnametextcmp+btoidcmp+btoidskipsupport+btoidsortsupport+btoidvectorcmp+btrecordcmp+btrecordimagecmp+btrim+bttext_pattern_cmp+bttext_pattern_sortsupport+bttextcmp+bttextnamecmp+bttextsortsupport+bttidcmp+btvarstrequalimage+bytea+bytea_larger+bytea_smaller+bytea_sortsupport+bytea_string_agg_finalfn+bytea_string_agg_transfn+byteacat+byteacmp+byteaeq+byteage+byteagt+byteain+byteale+bytealike+bytealt+byteane+byteanlike+byteaout+bytearecv+byteasend+cardinality+casefold+cash_cmp+cash_div_cash+cash_div_flt4+cash_div_flt8+cash_div_int2+cash_div_int4+cash_div_int8+cash_eq+cash_ge+cash_gt+cash_in+cash_le+cash_lt+cash_mi+cash_mul_flt4+cash_mul_flt8+cash_mul_int2+cash_mul_int4+cash_mul_int8+cash_ne+cash_out+cash_pl+cash_recv+cash_send+cash_words+cashlarger+cashsmaller+cbrt+ceil+ceiling+center+char+char_length+character_length+chareq+charge+chargt+charin+charle+charlt+charne+charout+charrecv+charsend+chr+cideq+cidin+cidout+cidr+cidr_in+cidr_out+cidr_recv+cidr_send+cidrecv+cidsend+circle+circle_above+circle_add_pt+circle_below+circle_center+circle_contain+circle_contain_pt+circle_contained+circle_distance+circle_div_pt+circle_eq+circle_ge+circle_gt+circle_in+circle_le+circle_left+circle_lt+circle_mul_pt+circle_ne+circle_out+circle_overabove+circle_overbelow+circle_overlap+circle_overleft+circle_overright+circle_recv+circle_right+circle_same+circle_send+circle_sub_pt+clock_timestamp+close_lb+close_ls+close_lseg+close_pb+close_pl+close_ps+close_sb+close_sl+col_description+concat+concat_ws+contjoinsel+contsel+convert+convert_from+convert_to+corr+cos+cosd+cosh+cot+cotd+count+covar_pop+covar_samp+crc32+crc32c+cstring_in+cstring_out+cstring_recv+cstring_send+cume_dist+cume_dist_final+current_database+current_query+current_schema+current_schemas+current_setting+current_user+currtid2+currval+cursor_to_xml+cursor_to_xmlschema+database_to_xml+database_to_xml_and_xmlschema+database_to_xmlschema+date+date_add+date_bin+date_cmp+date_cmp_timestamp+date_cmp_timestamptz+date_eq+date_eq_timestamp+date_eq_timestamptz+date_ge+date_ge_timestamp+date_ge_timestamptz+date_gt+date_gt_timestamp+date_gt_timestamptz+date_in+date_larger+date_le+date_le_timestamp+date_le_timestamptz+date_lt+date_lt_timestamp+date_lt_timestamptz+date_mi+date_mi_interval+date_mii+date_ne+date_ne_timestamp+date_ne_timestamptz+date_out+date_part+date_pl_interval+date_pli+date_recv+date_send+date_skipsupport+date_smaller+date_sortsupport+date_subtract+date_trunc+datemultirange+daterange+daterange_canonical+daterange_subdiff+datetime_pl+datetimetz_pl+dcbrt+decode+degrees+dense_rank+dense_rank_final+dexp+diagonal+diameter+dispell_init+dispell_lexize+dist_bl+dist_bp+dist_bs+dist_cpoint+dist_cpoly+dist_lb+dist_lp+dist_ls+dist_pathp+dist_pb+dist_pc+dist_pl+dist_polyc+dist_polyp+dist_ppath+dist_ppoly+dist_ps+dist_sb+dist_sl+dist_sp+div+dlog1+dlog10+domain_in+domain_recv+dpow+dround+dsimple_init+dsimple_lexize+dsnowball_init+dsnowball_lexize+dsqrt+dsynonym_init+dsynonym_lexize+dtrunc+elem_contained_by_multirange+elem_contained_by_range+elem_contained_by_range_support+encode+enum_cmp+enum_eq+enum_first+enum_ge+enum_gt+enum_in+enum_larger+enum_last+enum_le+enum_lt+enum_ne+enum_out+enum_range+enum_recv+enum_send+enum_smaller+eqjoinsel+eqsel+erf+erfc+euc_cn_to_mic+euc_cn_to_utf8+euc_jis_2004_to_shift_jis_2004+euc_jis_2004_to_utf8+euc_jp_to_mic+euc_jp_to_sjis+euc_jp_to_utf8+euc_kr_to_mic+euc_kr_to_utf8+euc_tw_to_big5+euc_tw_to_mic+euc_tw_to_utf8+event_trigger_in+event_trigger_out+every+exp+extract+factorial+family+fdw_handler_in+fdw_handler_out+first_value+float4+float48div+float48eq+float48ge+float48gt+float48le+float48lt+float48mi+float48mul+float48ne+float48pl+float4_accum+float4abs+float4div+float4eq+float4ge+float4gt+float4in+float4larger+float4le+float4lt+float4mi+float4mul+float4ne+float4out+float4pl+float4recv+float4send+float4smaller+float4um+float4up+float8+float84div+float84eq+float84ge+float84gt+float84le+float84lt+float84mi+float84mul+float84ne+float84pl+float8_accum+float8_avg+float8_combine+float8_corr+float8_covar_pop+float8_covar_samp+float8_regr_accum+float8_regr_avgx+float8_regr_avgy+float8_regr_combine+float8_regr_intercept+float8_regr_r2+float8_regr_slope+float8_regr_sxx+float8_regr_sxy+float8_regr_syy+float8_stddev_pop+float8_stddev_samp+float8_var_pop+float8_var_samp+float8abs+float8div+float8eq+float8ge+float8gt+float8in+float8larger+float8le+float8lt+float8mi+float8mul+float8ne+float8out+float8pl+float8recv+float8send+float8smaller+float8um+float8up+floor+flt4_mul_cash+flt8_mul_cash+fmgr_c_validator+fmgr_internal_validator+fmgr_sql_validator+format+format_type+gamma+gb18030_to_utf8+gbk_to_utf8+gcd+gen_random_uuid+generate_series+generate_series_int4_support+generate_series_int8_support+generate_series_numeric_support+generate_series_timestamp_support+generate_subscripts+get_bit+get_byte+get_current_ts_config+getdatabaseencoding+getpgusername+gin_clean_pending_list+gin_cmp_prefix+gin_cmp_tslexeme+gin_compare_jsonb+gin_consistent_jsonb+gin_consistent_jsonb_path+gin_extract_jsonb+gin_extract_jsonb_path+gin_extract_jsonb_query+gin_extract_jsonb_query_path+gin_extract_tsquery+gin_extract_tsvector+gin_triconsistent_jsonb+gin_triconsistent_jsonb_path+gin_tsquery_consistent+gin_tsquery_triconsistent+ginarrayconsistent+ginarrayextract+ginarraytriconsistent+ginhandler+ginqueryarrayextract+gist_box_consistent+gist_box_distance+gist_box_penalty+gist_box_picksplit+gist_box_same+gist_box_union+gist_circle_compress+gist_circle_consistent+gist_circle_distance+gist_point_compress+gist_point_consistent+gist_point_distance+gist_point_fetch+gist_point_sortsupport+gist_poly_compress+gist_poly_consistent+gist_poly_distance+gist_translate_cmptype_common+gisthandler+gtsquery_compress+gtsquery_consistent+gtsquery_penalty+gtsquery_picksplit+gtsquery_same+gtsquery_union+gtsvector_compress+gtsvector_consistent+gtsvector_decompress+gtsvector_options+gtsvector_penalty+gtsvector_picksplit+gtsvector_same+gtsvector_union+gtsvectorin+gtsvectorout+has_any_column_privilege+has_column_privilege+has_database_privilege+has_foreign_data_wrapper_privilege+has_function_privilege+has_language_privilege+has_largeobject_privilege+has_parameter_privilege+has_schema_privilege+has_sequence_privilege+has_server_privilege+has_table_privilege+has_tablespace_privilege+has_type_privilege+hash_aclitem+hash_aclitem_extended+hash_array+hash_array_extended+hash_multirange+hash_multirange_extended+hash_numeric+hash_numeric_extended+hash_range+hash_range_extended+hash_record+hash_record_extended+hashbool+hashboolextended+hashbpchar+hashbpcharextended+hashbytea+hashbyteaextended+hashchar+hashcharextended+hashcid+hashcidextended+hashdate+hashdateextended+hashenum+hashenumextended+hashfloat4+hashfloat4extended+hashfloat8+hashfloat8extended+hashhandler+hashinet+hashinetextended+hashint2+hashint2extended+hashint4+hashint4extended+hashint8+hashint8extended+hashmacaddr+hashmacaddr8+hashmacaddr8extended+hashmacaddrextended+hashname+hashnameextended+hashoid+hashoidextended+hashoidvector+hashoidvectorextended+hashtext+hashtextextended+hashtid+hashtidextended+hashvarlena+hashvarlenaextended+hashxid+hashxid8+hashxid8extended+hashxidextended+heap_tableam_handler+height+host+hostmask+iclikejoinsel+iclikesel+icnlikejoinsel+icnlikesel+icregexeqjoinsel+icregexeqsel+icregexnejoinsel+icregexnesel+icu_unicode_version+in_range+index_am_handler_in+index_am_handler_out+inet_client_addr+inet_client_port+inet_gist_compress+inet_gist_consistent+inet_gist_fetch+inet_gist_penalty+inet_gist_picksplit+inet_gist_same+inet_gist_union+inet_in+inet_merge+inet_out+inet_recv+inet_same_family+inet_send+inet_server_addr+inet_server_port+inet_spg_choose+inet_spg_config+inet_spg_inner_consistent+inet_spg_leaf_consistent+inet_spg_picksplit+inetand+inetmi+inetmi_int8+inetnot+inetor+inetpl+initcap+int2+int24div+int24eq+int24ge+int24gt+int24le+int24lt+int24mi+int24mul+int24ne+int24pl+int28div+int28eq+int28ge+int28gt+int28le+int28lt+int28mi+int28mul+int28ne+int28pl+int2_accum+int2_accum_inv+int2_avg_accum+int2_avg_accum_inv+int2_mul_cash+int2_sum+int2abs+int2and+int2div+int2eq+int2ge+int2gt+int2in+int2int4_sum+int2larger+int2le+int2lt+int2mi+int2mod+int2mul+int2ne+int2not+int2or+int2out+int2pl+int2recv+int2send+int2shl+int2shr+int2smaller+int2um+int2up+int2vectorin+int2vectorout+int2vectorrecv+int2vectorsend+int2xor+int4+int42div+int42eq+int42ge+int42gt+int42le+int42lt+int42mi+int42mul+int42ne+int42pl+int48div+int48eq+int48ge+int48gt+int48le+int48lt+int48mi+int48mul+int48ne+int48pl+int4_accum+int4_accum_inv+int4_avg_accum+int4_avg_accum_inv+int4_avg_combine+int4_mul_cash+int4_sum+int4abs+int4and+int4div+int4eq+int4ge+int4gt+int4in+int4inc+int4larger+int4le+int4lt+int4mi+int4mod+int4mul+int4multirange+int4ne+int4not+int4or+int4out+int4pl+int4range+int4range_canonical+int4range_subdiff+int4recv+int4send+int4shl+int4shr+int4smaller+int4um+int4up+int4xor+int8+int82div+int82eq+int82ge+int82gt+int82le+int82lt+int82mi+int82mul+int82ne+int82pl+int84div+int84eq+int84ge+int84gt+int84le+int84lt+int84mi+int84mul+int84ne+int84pl+int8_accum+int8_accum_inv+int8_avg+int8_avg_accum+int8_avg_accum_inv+int8_avg_combine+int8_avg_deserialize+int8_avg_serialize+int8_mul_cash+int8_sum+int8abs+int8and+int8dec+int8dec_any+int8div+int8eq+int8ge+int8gt+int8in+int8inc+int8inc_any+int8inc_float8_float8+int8inc_support+int8larger+int8le+int8lt+int8mi+int8mod+int8mul+int8multirange+int8ne+int8not+int8or+int8out+int8pl+int8pl_inet+int8range+int8range_canonical+int8range_subdiff+int8recv+int8send+int8shl+int8shr+int8smaller+int8um+int8up+int8xor+integer_pl_date+inter_lb+inter_sb+inter_sl+internal_in+internal_out+interval+interval_accum+interval_accum_inv+interval_avg+interval_avg_accum+interval_avg_accum_inv+interval_avg_combine+interval_avg_deserialize+interval_avg_serialize+interval_cmp+interval_combine+interval_div+interval_eq+interval_ge+interval_gt+interval_hash+interval_hash_extended+interval_in+interval_larger+interval_le+interval_lt+interval_mi+interval_mul+interval_ne+interval_out+interval_pl+interval_pl_date+interval_pl_time+interval_pl_timestamp+interval_pl_timestamptz+interval_pl_timetz+interval_recv+interval_send+interval_smaller+interval_sum+interval_support+interval_um+intervaltypmodin+intervaltypmodout+is_normalized+isclosed+isempty+isfinite+ishorizontal+iso8859_1_to_utf8+iso8859_to_utf8+iso_to_koi8r+iso_to_mic+iso_to_win1251+iso_to_win866+isopen+isparallel+isperp+isvertical+johab_to_utf8+json_agg+json_agg_finalfn+json_agg_strict+json_agg_strict_transfn+json_agg_transfn+json_array_element+json_array_element_text+json_array_elements+json_array_elements_text+json_array_length+json_build_array+json_build_object+json_each+json_each_text+json_extract_path+json_extract_path_text+json_in+json_object+json_object_agg+json_object_agg_finalfn+json_object_agg_strict+json_object_agg_strict_transfn+json_object_agg_transfn+json_object_agg_unique+json_object_agg_unique_strict+json_object_agg_unique_strict_transfn+json_object_agg_unique_transfn+json_object_field+json_object_field_text+json_object_keys+json_out+json_populate_record+json_populate_recordset+json_recv+json_send+json_strip_nulls+json_to_record+json_to_recordset+json_to_tsvector+json_typeof+jsonb_agg+jsonb_agg_finalfn+jsonb_agg_strict+jsonb_agg_strict_transfn+jsonb_agg_transfn+jsonb_array_element+jsonb_array_element_text+jsonb_array_elements+jsonb_array_elements_text+jsonb_array_length+jsonb_build_array+jsonb_build_object+jsonb_cmp+jsonb_concat+jsonb_contained+jsonb_contains+jsonb_delete+jsonb_delete_path+jsonb_each+jsonb_each_text+jsonb_eq+jsonb_exists+jsonb_exists_all+jsonb_exists_any+jsonb_extract_path+jsonb_extract_path_text+jsonb_ge+jsonb_gt+jsonb_hash+jsonb_hash_extended+jsonb_in+jsonb_insert+jsonb_le+jsonb_lt+jsonb_ne+jsonb_object+jsonb_object_agg+jsonb_object_agg_finalfn+jsonb_object_agg_strict+jsonb_object_agg_strict_transfn+jsonb_object_agg_transfn+jsonb_object_agg_unique+jsonb_object_agg_unique_strict+jsonb_object_agg_unique_strict_transfn+jsonb_object_agg_unique_transfn+jsonb_object_field+jsonb_object_field_text+jsonb_object_keys+jsonb_out+jsonb_path_exists+jsonb_path_exists_opr+jsonb_path_exists_tz+jsonb_path_match+jsonb_path_match_opr+jsonb_path_match_tz+jsonb_path_query+jsonb_path_query_array+jsonb_path_query_array_tz+jsonb_path_query_first+jsonb_path_query_first_tz+jsonb_path_query_tz+jsonb_populate_record+jsonb_populate_record_valid+jsonb_populate_recordset+jsonb_pretty+jsonb_recv+jsonb_send+jsonb_set+jsonb_set_lax+jsonb_strip_nulls+jsonb_subscript_handler+jsonb_to_record+jsonb_to_recordset+jsonb_to_tsvector+jsonb_typeof+jsonpath_in+jsonpath_out+jsonpath_recv+jsonpath_send+justify_days+justify_hours+justify_interval+koi8r_to_iso+koi8r_to_mic+koi8r_to_utf8+koi8r_to_win1251+koi8r_to_win866+koi8u_to_utf8+lag+language_handler_in+language_handler_out+last_value+lastval+latin1_to_mic+latin2_to_mic+latin2_to_win1250+latin3_to_mic+latin4_to_mic+lcm+lead+left+length+lgamma+like+like_escape+likejoinsel+likesel+line+line_distance+line_eq+line_horizontal+line_in+line_interpt+line_intersect+line_out+line_parallel+line_perp+line_recv+line_send+line_vertical+ln+lo_close+lo_creat+lo_create+lo_export+lo_from_bytea+lo_get+lo_import+lo_lseek+lo_lseek64+lo_open+lo_put+lo_tell+lo_tell64+lo_truncate+lo_truncate64+lo_unlink+log+log10+loread+lower+lower_inc+lower_inf+lowrite+lpad+lseg+lseg_center+lseg_distance+lseg_eq+lseg_ge+lseg_gt+lseg_horizontal+lseg_in+lseg_interpt+lseg_intersect+lseg_le+lseg_length+lseg_lt+lseg_ne+lseg_out+lseg_parallel+lseg_perp+lseg_recv+lseg_send+lseg_vertical+ltrim+macaddr+macaddr8+macaddr8_and+macaddr8_cmp+macaddr8_eq+macaddr8_ge+macaddr8_gt+macaddr8_in+macaddr8_le+macaddr8_lt+macaddr8_ne+macaddr8_not+macaddr8_or+macaddr8_out+macaddr8_recv+macaddr8_send+macaddr8_set7bit+macaddr_and+macaddr_cmp+macaddr_eq+macaddr_ge+macaddr_gt+macaddr_in+macaddr_le+macaddr_lt+macaddr_ne+macaddr_not+macaddr_or+macaddr_out+macaddr_recv+macaddr_send+macaddr_sortsupport+make_date+make_interval+make_time+make_timestamp+make_timestamptz+makeaclitem+masklen+matchingjoinsel+matchingsel+max+md5+mic_to_big5+mic_to_euc_cn+mic_to_euc_jp+mic_to_euc_kr+mic_to_euc_tw+mic_to_iso+mic_to_koi8r+mic_to_latin1+mic_to_latin2+mic_to_latin3+mic_to_latin4+mic_to_sjis+mic_to_win1250+mic_to_win1251+mic_to_win866+min+min_scale+mod+mode+mode_final+money+mul_d_interval+multirange+multirange_adjacent_multirange+multirange_adjacent_range+multirange_after_multirange+multirange_after_range+multirange_agg_finalfn+multirange_agg_transfn+multirange_before_multirange+multirange_before_range+multirange_cmp+multirange_contained_by_multirange+multirange_contained_by_range+multirange_contains_elem+multirange_contains_multirange+multirange_contains_range+multirange_eq+multirange_ge+multirange_gist_compress+multirange_gist_consistent+multirange_gt+multirange_in+multirange_intersect+multirange_intersect_agg_transfn+multirange_le+multirange_lt+multirange_minus+multirange_ne+multirange_out+multirange_overlaps_multirange+multirange_overlaps_range+multirange_overleft_multirange+multirange_overleft_range+multirange_overright_multirange+multirange_overright_range+multirange_recv+multirange_send+multirange_typanalyze+multirange_union+multirangesel+mxid_age+name+nameconcatoid+nameeq+nameeqtext+namege+namegetext+namegt+namegttext+nameiclike+nameicnlike+nameicregexeq+nameicregexne+namein+namele+nameletext+namelike+namelt+namelttext+namene+namenetext+namenlike+nameout+namerecv+nameregexeq+nameregexne+namesend+neqjoinsel+neqsel+netmask+network+network_cmp+network_eq+network_ge+network_gt+network_larger+network_le+network_lt+network_ne+network_overlap+network_smaller+network_sortsupport+network_sub+network_subeq+network_subset_support+network_sup+network_supeq+networkjoinsel+networksel+nextval+nlikejoinsel+nlikesel+normalize+notlike+now+npoints+nth_value+ntile+num_nonnulls+num_nulls+numeric+numeric_abs+numeric_accum+numeric_accum_inv+numeric_add+numeric_avg+numeric_avg_accum+numeric_avg_combine+numeric_avg_deserialize+numeric_avg_serialize+numeric_cmp+numeric_combine+numeric_deserialize+numeric_div+numeric_div_trunc+numeric_eq+numeric_exp+numeric_ge+numeric_gt+numeric_in+numeric_inc+numeric_larger+numeric_le+numeric_ln+numeric_log+numeric_lt+numeric_mod+numeric_mul+numeric_ne+numeric_out+numeric_pl_pg_lsn+numeric_poly_avg+numeric_poly_combine+numeric_poly_deserialize+numeric_poly_serialize+numeric_poly_stddev_pop+numeric_poly_stddev_samp+numeric_poly_sum+numeric_poly_var_pop+numeric_poly_var_samp+numeric_power+numeric_recv+numeric_send+numeric_serialize+numeric_smaller+numeric_sortsupport+numeric_sqrt+numeric_stddev_pop+numeric_stddev_samp+numeric_sub+numeric_sum+numeric_support+numeric_uminus+numeric_uplus+numeric_var_pop+numeric_var_samp+numerictypmodin+numerictypmodout+nummultirange+numnode+numrange+numrange_subdiff+obj_description+octet_length+oid+oideq+oidge+oidgt+oidin+oidlarger+oidle+oidlt+oidne+oidout+oidrecv+oidsend+oidsmaller+oidvectoreq+oidvectorge+oidvectorgt+oidvectorin+oidvectorle+oidvectorlt+oidvectorne+oidvectorout+oidvectorrecv+oidvectorsend+oidvectortypes+on_pb+on_pl+on_ppath+on_ps+on_sb+on_sl+ordered_set_transition+ordered_set_transition_multi+overlaps+overlay+parse_ident+path+path_add+path_add_pt+path_center+path_contain_pt+path_distance+path_div_pt+path_in+path_inter+path_length+path_mul_pt+path_n_eq+path_n_ge+path_n_gt+path_n_le+path_n_lt+path_npoints+path_out+path_recv+path_send+path_sub_pt+pclose+percent_rank+percent_rank_final+percentile_cont+percentile_cont_float8_final+percentile_cont_float8_multi_final+percentile_cont_interval_final+percentile_cont_interval_multi_final+percentile_disc+percentile_disc_final+percentile_disc_multi_final+pg_advisory_lock+pg_advisory_lock_shared+pg_advisory_unlock+pg_advisory_unlock_all+pg_advisory_unlock_shared+pg_advisory_xact_lock+pg_advisory_xact_lock_shared+pg_available_extension_versions+pg_available_extensions+pg_available_wal_summaries+pg_backend_pid+pg_backup_start+pg_backup_start_time+pg_backup_stop+pg_basetype+pg_blocking_pids+pg_cancel_backend+pg_char_to_encoding+pg_clear_attribute_stats+pg_clear_relation_stats+pg_client_encoding+pg_collation_actual_version+pg_collation_for+pg_collation_is_visible+pg_column_compression+pg_column_is_updatable+pg_column_size+pg_column_toast_chunk_id+pg_conf_load_time+pg_config+pg_control_checkpoint+pg_control_init+pg_control_recovery+pg_control_system+pg_conversion_is_visible+pg_copy_logical_replication_slot+pg_copy_physical_replication_slot+pg_create_logical_replication_slot+pg_create_physical_replication_slot+pg_create_restore_point+pg_current_logfile+pg_current_snapshot+pg_current_wal_flush_lsn+pg_current_wal_insert_lsn+pg_current_wal_lsn+pg_current_xact_id+pg_current_xact_id_if_assigned+pg_cursor+pg_database_collation_actual_version+pg_database_size+pg_ddl_command_in+pg_ddl_command_out+pg_ddl_command_recv+pg_ddl_command_send+pg_dependencies_in+pg_dependencies_out+pg_dependencies_recv+pg_dependencies_send+pg_describe_object+pg_drop_replication_slot+pg_encoding_max_length+pg_encoding_to_char+pg_event_trigger_ddl_commands+pg_event_trigger_dropped_objects+pg_event_trigger_table_rewrite_oid+pg_event_trigger_table_rewrite_reason+pg_export_snapshot+pg_extension_config_dump+pg_extension_update_paths+pg_filenode_relation+pg_function_is_visible+pg_get_acl+pg_get_aios+pg_get_backend_memory_contexts+pg_get_catalog_foreign_keys+pg_get_constraintdef+pg_get_expr+pg_get_function_arg_default+pg_get_function_arguments+pg_get_function_identity_arguments+pg_get_function_result+pg_get_function_sqlbody+pg_get_functiondef+pg_get_indexdef+pg_get_keywords+pg_get_loaded_modules+pg_get_multixact_members+pg_get_object_address+pg_get_partition_constraintdef+pg_get_partkeydef+pg_get_publication_tables+pg_get_replica_identity_index+pg_get_replication_slots+pg_get_ruledef+pg_get_sequence_data+pg_get_serial_sequence+pg_get_shmem_allocations+pg_get_shmem_allocations_numa+pg_get_statisticsobjdef+pg_get_statisticsobjdef_columns+pg_get_statisticsobjdef_expressions+pg_get_triggerdef+pg_get_userbyid+pg_get_viewdef+pg_get_wait_events+pg_get_wal_replay_pause_state+pg_get_wal_resource_managers+pg_get_wal_summarizer_state+pg_has_role+pg_hba_file_rules+pg_ident_file_mappings+pg_identify_object+pg_identify_object_as_address+pg_import_system_collations+pg_index_column_has_property+pg_index_has_property+pg_indexam_has_property+pg_indexam_progress_phasename+pg_indexes_size+pg_input_error_info+pg_input_is_valid+pg_is_in_backup+pg_is_in_recovery+pg_is_other_temp_schema+pg_is_wal_replay_paused+pg_isolation_test_session_is_blocked+pg_jit_available+pg_last_committed_xact+pg_last_wal_receive_lsn+pg_last_wal_replay_lsn+pg_last_xact_replay_timestamp+pg_listening_channels+pg_lock_status+pg_log_backend_memory_contexts+pg_log_standby_snapshot+pg_logical_emit_message+pg_logical_slot_get_binary_changes+pg_logical_slot_get_changes+pg_logical_slot_peek_binary_changes+pg_logical_slot_peek_changes+pg_ls_archive_statusdir+pg_ls_dir+pg_ls_logdir+pg_ls_logicalmapdir+pg_ls_logicalsnapdir+pg_ls_replslotdir+pg_ls_summariesdir+pg_ls_tmpdir+pg_ls_waldir+pg_lsn+pg_lsn_cmp+pg_lsn_eq+pg_lsn_ge+pg_lsn_gt+pg_lsn_hash+pg_lsn_hash_extended+pg_lsn_in+pg_lsn_larger+pg_lsn_le+pg_lsn_lt+pg_lsn_mi+pg_lsn_mii+pg_lsn_ne+pg_lsn_out+pg_lsn_pli+pg_lsn_recv+pg_lsn_send+pg_lsn_smaller+pg_mcv_list_in+pg_mcv_list_items+pg_mcv_list_out+pg_mcv_list_recv+pg_mcv_list_send+pg_my_temp_schema+pg_ndistinct_in+pg_ndistinct_out+pg_ndistinct_recv+pg_ndistinct_send+pg_nextoid+pg_node_tree_in+pg_node_tree_out+pg_node_tree_recv+pg_node_tree_send+pg_notification_queue_usage+pg_notify+pg_numa_available+pg_opclass_is_visible+pg_operator_is_visible+pg_opfamily_is_visible+pg_options_to_table+pg_partition_ancestors+pg_partition_root+pg_partition_tree+pg_postmaster_start_time+pg_prepared_statement+pg_prepared_xact+pg_promote+pg_read_binary_file+pg_read_file+pg_read_file_old+pg_relation_filenode+pg_relation_filepath+pg_relation_is_publishable+pg_relation_is_updatable+pg_relation_size+pg_reload_conf+pg_replication_origin_advance+pg_replication_origin_create+pg_replication_origin_drop+pg_replication_origin_oid+pg_replication_origin_progress+pg_replication_origin_session_is_setup+pg_replication_origin_session_progress+pg_replication_origin_session_reset+pg_replication_origin_session_setup+pg_replication_origin_xact_reset+pg_replication_origin_xact_setup+pg_replication_slot_advance+pg_restore_attribute_stats+pg_restore_relation_stats+pg_rotate_logfile+pg_rotate_logfile_old+pg_safe_snapshot_blocking_pids+pg_sequence_last_value+pg_sequence_parameters+pg_settings_get_flags+pg_show_all_file_settings+pg_show_all_settings+pg_show_replication_origin_status+pg_size_bytes+pg_size_pretty+pg_sleep+pg_sleep_for+pg_sleep_until+pg_snapshot_in+pg_snapshot_out+pg_snapshot_recv+pg_snapshot_send+pg_snapshot_xip+pg_snapshot_xmax+pg_snapshot_xmin+pg_split_walfile_name+pg_start_backup+pg_stat_clear_snapshot+pg_stat_file+pg_stat_force_next_flush+pg_stat_get_activity+pg_stat_get_analyze_count+pg_stat_get_archiver+pg_stat_get_autoanalyze_count+pg_stat_get_autovacuum_count+pg_stat_get_backend_activity+pg_stat_get_backend_activity_start+pg_stat_get_backend_client_addr+pg_stat_get_backend_client_port+pg_stat_get_backend_dbid+pg_stat_get_backend_idset+pg_stat_get_backend_io+pg_stat_get_backend_pid+pg_stat_get_backend_start+pg_stat_get_backend_subxact+pg_stat_get_backend_userid+pg_stat_get_backend_wait_event+pg_stat_get_backend_wait_event_type+pg_stat_get_backend_wal+pg_stat_get_backend_xact_start+pg_stat_get_bgwriter_buf_written_checkpoints+pg_stat_get_bgwriter_buf_written_clean+pg_stat_get_bgwriter_maxwritten_clean+pg_stat_get_bgwriter_requested_checkpoints+pg_stat_get_bgwriter_stat_reset_time+pg_stat_get_bgwriter_timed_checkpoints+pg_stat_get_blocks_fetched+pg_stat_get_blocks_hit+pg_stat_get_buf_alloc+pg_stat_get_buf_fsync_backend+pg_stat_get_buf_written_backend+pg_stat_get_checkpoint_sync_time+pg_stat_get_checkpoint_write_time+pg_stat_get_checkpointer_buffers_written+pg_stat_get_checkpointer_num_performed+pg_stat_get_checkpointer_num_requested+pg_stat_get_checkpointer_num_timed+pg_stat_get_checkpointer_restartpoints_performed+pg_stat_get_checkpointer_restartpoints_requested+pg_stat_get_checkpointer_restartpoints_timed+pg_stat_get_checkpointer_slru_written+pg_stat_get_checkpointer_stat_reset_time+pg_stat_get_checkpointer_sync_time+pg_stat_get_checkpointer_write_time+pg_stat_get_db_active_time+pg_stat_get_db_blk_read_time+pg_stat_get_db_blk_write_time+pg_stat_get_db_blocks_fetched+pg_stat_get_db_blocks_hit+pg_stat_get_db_checksum_failures+pg_stat_get_db_checksum_last_failure+pg_stat_get_db_conflict_all+pg_stat_get_db_conflict_bufferpin+pg_stat_get_db_conflict_lock+pg_stat_get_db_conflict_logicalslot+pg_stat_get_db_conflict_snapshot+pg_stat_get_db_conflict_startup_deadlock+pg_stat_get_db_conflict_tablespace+pg_stat_get_db_deadlocks+pg_stat_get_db_idle_in_transaction_time+pg_stat_get_db_numbackends+pg_stat_get_db_parallel_workers_launched+pg_stat_get_db_parallel_workers_to_launch+pg_stat_get_db_session_time+pg_stat_get_db_sessions+pg_stat_get_db_sessions_abandoned+pg_stat_get_db_sessions_fatal+pg_stat_get_db_sessions_killed+pg_stat_get_db_stat_reset_time+pg_stat_get_db_temp_bytes+pg_stat_get_db_temp_files+pg_stat_get_db_tuples_deleted+pg_stat_get_db_tuples_fetched+pg_stat_get_db_tuples_inserted+pg_stat_get_db_tuples_returned+pg_stat_get_db_tuples_updated+pg_stat_get_db_xact_commit+pg_stat_get_db_xact_rollback+pg_stat_get_dead_tuples+pg_stat_get_function_calls+pg_stat_get_function_self_time+pg_stat_get_function_total_time+pg_stat_get_ins_since_vacuum+pg_stat_get_io+pg_stat_get_last_analyze_time+pg_stat_get_last_autoanalyze_time+pg_stat_get_last_autovacuum_time+pg_stat_get_last_vacuum_time+pg_stat_get_lastscan+pg_stat_get_live_tuples+pg_stat_get_mod_since_analyze+pg_stat_get_numscans+pg_stat_get_progress_info+pg_stat_get_recovery_prefetch+pg_stat_get_replication_slot+pg_stat_get_slru+pg_stat_get_snapshot_timestamp+pg_stat_get_subscription+pg_stat_get_subscription_stats+pg_stat_get_total_analyze_time+pg_stat_get_total_autoanalyze_time+pg_stat_get_total_autovacuum_time+pg_stat_get_total_vacuum_time+pg_stat_get_tuples_deleted+pg_stat_get_tuples_fetched+pg_stat_get_tuples_hot_updated+pg_stat_get_tuples_inserted+pg_stat_get_tuples_newpage_updated+pg_stat_get_tuples_returned+pg_stat_get_tuples_updated+pg_stat_get_vacuum_count+pg_stat_get_wal+pg_stat_get_wal_receiver+pg_stat_get_wal_senders+pg_stat_get_xact_blocks_fetched+pg_stat_get_xact_blocks_hit+pg_stat_get_xact_function_calls+pg_stat_get_xact_function_self_time+pg_stat_get_xact_function_total_time+pg_stat_get_xact_numscans+pg_stat_get_xact_tuples_deleted+pg_stat_get_xact_tuples_fetched+pg_stat_get_xact_tuples_hot_updated+pg_stat_get_xact_tuples_inserted+pg_stat_get_xact_tuples_newpage_updated+pg_stat_get_xact_tuples_returned+pg_stat_get_xact_tuples_updated+pg_stat_have_stats+pg_stat_reset+pg_stat_reset_backend_stats+pg_stat_reset_replication_slot+pg_stat_reset_shared+pg_stat_reset_single_function_counters+pg_stat_reset_single_table_counters+pg_stat_reset_slru+pg_stat_reset_subscription_stats+pg_statistics_obj_is_visible+pg_stop_backup+pg_stop_making_pinned_objects+pg_switch_wal+pg_sync_replication_slots+pg_table_is_visible+pg_table_size+pg_tablespace_databases+pg_tablespace_location+pg_tablespace_size+pg_terminate_backend+pg_timezone_abbrevs+pg_timezone_abbrevs_abbrevs+pg_timezone_abbrevs_zone+pg_timezone_names+pg_total_relation_size+pg_trigger_depth+pg_try_advisory_lock+pg_try_advisory_lock_shared+pg_try_advisory_xact_lock+pg_try_advisory_xact_lock_shared+pg_ts_config_is_visible+pg_ts_dict_is_visible+pg_ts_parser_is_visible+pg_ts_template_is_visible+pg_type_is_visible+pg_typeof+pg_visible_in_snapshot+pg_wal_lsn_diff+pg_wal_replay_pause+pg_wal_replay_resume+pg_wal_summary_contents+pg_walfile_name+pg_walfile_name_offset+pg_xact_commit_timestamp+pg_xact_commit_timestamp_origin+pg_xact_status+phraseto_tsquery+pi+plainto_tsquery+plpgsql_call_handler+plpgsql_inline_handler+plpgsql_validator+point+point_above+point_add+point_below+point_distance+point_div+point_eq+point_horiz+point_in+point_left+point_mul+point_ne+point_out+point_recv+point_right+point_send+point_sub+point_vert+poly_above+poly_below+poly_center+poly_contain+poly_contain_pt+poly_contained+poly_distance+poly_in+poly_left+poly_npoints+poly_out+poly_overabove+poly_overbelow+poly_overlap+poly_overleft+poly_overright+poly_recv+poly_right+poly_same+poly_send+polygon+popen+position+positionjoinsel+positionsel+postgresql_fdw_validator+pow+power+prefixjoinsel+prefixsel+prsd_end+prsd_headline+prsd_lextype+prsd_nexttoken+prsd_start+pt_contained_circle+pt_contained_poly+query_to_xml+query_to_xml_and_xmlschema+query_to_xmlschema+querytree+quote_ident+quote_literal+quote_nullable+radians+radius+random+random_normal+range_adjacent+range_adjacent_multirange+range_after+range_after_multirange+range_agg+range_agg_finalfn+range_agg_transfn+range_before+range_before_multirange+range_cmp+range_contained_by+range_contained_by_multirange+range_contains+range_contains_elem+range_contains_elem_support+range_contains_multirange+range_eq+range_ge+range_gist_consistent+range_gist_penalty+range_gist_picksplit+range_gist_same+range_gist_union+range_gt+range_in+range_intersect+range_intersect_agg+range_intersect_agg_transfn+range_le+range_lt+range_merge+range_minus+range_ne+range_out+range_overlaps+range_overlaps_multirange+range_overleft+range_overleft_multirange+range_overright+range_overright_multirange+range_recv+range_send+range_sortsupport+range_typanalyze+range_union+rangesel+rank+rank_final+raw_array_subscript_handler+record_eq+record_ge+record_gt+record_image_eq+record_image_ge+record_image_gt+record_image_le+record_image_lt+record_image_ne+record_in+record_larger+record_le+record_lt+record_ne+record_out+record_recv+record_send+record_smaller+regclass+regclassin+regclassout+regclassrecv+regclasssend+regcollationin+regcollationout+regcollationrecv+regcollationsend+regconfigin+regconfigout+regconfigrecv+regconfigsend+regdictionaryin+regdictionaryout+regdictionaryrecv+regdictionarysend+regexeqjoinsel+regexeqsel+regexnejoinsel+regexnesel+regexp_count+regexp_instr+regexp_like+regexp_match+regexp_matches+regexp_replace+regexp_split_to_array+regexp_split_to_table+regexp_substr+regnamespacein+regnamespaceout+regnamespacerecv+regnamespacesend+regoperatorin+regoperatorout+regoperatorrecv+regoperatorsend+regoperin+regoperout+regoperrecv+regopersend+regprocedurein+regprocedureout+regprocedurerecv+regproceduresend+regprocin+regprocout+regprocrecv+regprocsend+regr_avgx+regr_avgy+regr_count+regr_intercept+regr_r2+regr_slope+regr_sxx+regr_sxy+regr_syy+regrolein+regroleout+regrolerecv+regrolesend+regtypein+regtypeout+regtyperecv+regtypesend+repeat+replace+reverse+right+round+row_number+row_security_active+row_to_json+rpad+rtrim+satisfies_hash_partition+scalargejoinsel+scalargesel+scalargtjoinsel+scalargtsel+scalarlejoinsel+scalarlesel+scalarltjoinsel+scalarltsel+scale+schema_to_xml+schema_to_xml_and_xmlschema+schema_to_xmlschema+session_user+set_bit+set_byte+set_config+set_masklen+setseed+setval+setweight+sha224+sha256+sha384+sha512+shell_in+shell_out+shift_jis_2004_to_euc_jis_2004+shift_jis_2004_to_utf8+shobj_description+sign+similar_escape+similar_to_escape+sin+sind+sinh+sjis_to_euc_jp+sjis_to_mic+sjis_to_utf8+slope+spg_bbox_quad_config+spg_box_quad_choose+spg_box_quad_config+spg_box_quad_inner_consistent+spg_box_quad_leaf_consistent+spg_box_quad_picksplit+spg_kd_choose+spg_kd_config+spg_kd_inner_consistent+spg_kd_picksplit+spg_poly_quad_compress+spg_quad_choose+spg_quad_config+spg_quad_inner_consistent+spg_quad_leaf_consistent+spg_quad_picksplit+spg_range_quad_choose+spg_range_quad_config+spg_range_quad_inner_consistent+spg_range_quad_leaf_consistent+spg_range_quad_picksplit+spg_text_choose+spg_text_config+spg_text_inner_consistent+spg_text_leaf_consistent+spg_text_picksplit+spghandler+split_part+sqrt+starts_with+statement_timestamp+stddev+stddev_pop+stddev_samp+string_agg+string_agg_combine+string_agg_deserialize+string_agg_finalfn+string_agg_serialize+string_agg_transfn+string_to_array+string_to_table+strip+strpos+substr+substring+sum+suppress_redundant_updates_trigger+system+system_user+table_am_handler_in+table_am_handler_out+table_to_xml+table_to_xml_and_xmlschema+table_to_xmlschema+tan+tand+tanh+text+text_ge+text_gt+text_larger+text_le+text_lt+text_pattern_ge+text_pattern_gt+text_pattern_le+text_pattern_lt+text_smaller+text_starts_with_support+textanycat+textcat+texteq+texteqname+textgename+textgtname+texticlike+texticlike_support+texticnlike+texticregexeq+texticregexeq_support+texticregexne+textin+textlen+textlename+textlike+textlike_support+textltname+textne+textnename+textnlike+textout+textrecv+textregexeq+textregexeq_support+textregexne+textsend+thesaurus_init+thesaurus_lexize+tideq+tidge+tidgt+tidin+tidlarger+tidle+tidlt+tidne+tidout+tidrecv+tidsend+tidsmaller+time+time_cmp+time_eq+time_ge+time_gt+time_hash+time_hash_extended+time_in+time_larger+time_le+time_lt+time_mi_interval+time_mi_time+time_ne+time_out+time_pl_interval+time_recv+time_send+time_smaller+time_support+timedate_pl+timeofday+timestamp+timestamp_cmp+timestamp_cmp_date+timestamp_cmp_timestamptz+timestamp_eq+timestamp_eq_date+timestamp_eq_timestamptz+timestamp_ge+timestamp_ge_date+timestamp_ge_timestamptz+timestamp_gt+timestamp_gt_date+timestamp_gt_timestamptz+timestamp_hash+timestamp_hash_extended+timestamp_in+timestamp_larger+timestamp_le+timestamp_le_date+timestamp_le_timestamptz+timestamp_lt+timestamp_lt_date+timestamp_lt_timestamptz+timestamp_mi+timestamp_mi_interval+timestamp_ne+timestamp_ne_date+timestamp_ne_timestamptz+timestamp_out+timestamp_pl_interval+timestamp_recv+timestamp_send+timestamp_skipsupport+timestamp_smaller+timestamp_sortsupport+timestamp_support+timestamptypmodin+timestamptypmodout+timestamptz+timestamptz_cmp+timestamptz_cmp_date+timestamptz_cmp_timestamp+timestamptz_eq+timestamptz_eq_date+timestamptz_eq_timestamp+timestamptz_ge+timestamptz_ge_date+timestamptz_ge_timestamp+timestamptz_gt+timestamptz_gt_date+timestamptz_gt_timestamp+timestamptz_hash+timestamptz_hash_extended+timestamptz_in+timestamptz_larger+timestamptz_le+timestamptz_le_date+timestamptz_le_timestamp+timestamptz_lt+timestamptz_lt_date+timestamptz_lt_timestamp+timestamptz_mi+timestamptz_mi_interval+timestamptz_ne+timestamptz_ne_date+timestamptz_ne_timestamp+timestamptz_out+timestamptz_pl_interval+timestamptz_recv+timestamptz_send+timestamptz_smaller+timestamptztypmodin+timestamptztypmodout+timetypmodin+timetypmodout+timetz+timetz_cmp+timetz_eq+timetz_ge+timetz_gt+timetz_hash+timetz_hash_extended+timetz_in+timetz_larger+timetz_le+timetz_lt+timetz_mi_interval+timetz_ne+timetz_out+timetz_pl_interval+timetz_recv+timetz_send+timetz_smaller+timetzdate_pl+timetztypmodin+timetztypmodout+timezone+to_ascii+to_bin+to_char+to_date+to_hex+to_json+to_jsonb+to_number+to_oct+to_regclass+to_regcollation+to_regnamespace+to_regoper+to_regoperator+to_regproc+to_regprocedure+to_regrole+to_regtype+to_regtypemod+to_timestamp+to_tsquery+to_tsvector+transaction_timestamp+translate+trigger_in+trigger_out+trim_array+trim_scale+trunc+ts_debug+ts_delete+ts_filter+ts_headline+ts_lexize+ts_match_qv+ts_match_tq+ts_match_tt+ts_match_vq+ts_parse+ts_rank+ts_rank_cd+ts_rewrite+ts_stat+ts_token_type+ts_typanalyze+tsm_handler_in+tsm_handler_out+tsmatchjoinsel+tsmatchsel+tsmultirange+tsq_mcontained+tsq_mcontains+tsquery_and+tsquery_cmp+tsquery_eq+tsquery_ge+tsquery_gt+tsquery_le+tsquery_lt+tsquery_ne+tsquery_not+tsquery_or+tsquery_phrase+tsqueryin+tsqueryout+tsqueryrecv+tsquerysend+tsrange+tsrange_subdiff+tstzmultirange+tstzrange+tstzrange_subdiff+tsvector_cmp+tsvector_concat+tsvector_eq+tsvector_ge+tsvector_gt+tsvector_le+tsvector_lt+tsvector_ne+tsvector_to_array+tsvector_update_trigger+tsvector_update_trigger_column+tsvectorin+tsvectorout+tsvectorrecv+tsvectorsend+txid_current+txid_current_if_assigned+txid_current_snapshot+txid_snapshot_in+txid_snapshot_out+txid_snapshot_recv+txid_snapshot_send+txid_snapshot_xip+txid_snapshot_xmax+txid_snapshot_xmin+txid_status+txid_visible_in_snapshot+uhc_to_utf8+unicode_assigned+unicode_version+unique_key_recheck+unistr+unknownin+unknownout+unknownrecv+unknownsend+unnest+upper+upper_inc+upper_inf+utf8_to_big5+utf8_to_euc_cn+utf8_to_euc_jis_2004+utf8_to_euc_jp+utf8_to_euc_kr+utf8_to_euc_tw+utf8_to_gb18030+utf8_to_gbk+utf8_to_iso8859+utf8_to_iso8859_1+utf8_to_johab+utf8_to_koi8r+utf8_to_koi8u+utf8_to_shift_jis_2004+utf8_to_sjis+utf8_to_uhc+utf8_to_win+uuid_cmp+uuid_eq+uuid_extract_timestamp+uuid_extract_version+uuid_ge+uuid_gt+uuid_hash+uuid_hash_extended+uuid_in+uuid_le+uuid_lt+uuid_ne+uuid_out+uuid_recv+uuid_send+uuid_skipsupport+uuid_sortsupport+uuidv4+uuidv7+var_pop+var_samp+varbit+varbit_in+varbit_out+varbit_recv+varbit_send+varbit_support+varbitcmp+varbiteq+varbitge+varbitgt+varbitle+varbitlt+varbitne+varbittypmodin+varbittypmodout+varchar+varchar_support+varcharin+varcharout+varcharrecv+varcharsend+varchartypmodin+varchartypmodout+variance+version+void_in+void_out+void_recv+void_send+websearch_to_tsquery+width+width_bucket+win1250_to_latin2+win1250_to_mic+win1251_to_iso+win1251_to_koi8r+win1251_to_mic+win1251_to_win866+win866_to_iso+win866_to_koi8r+win866_to_mic+win866_to_win1251+win_to_utf8+window_cume_dist_support+window_dense_rank_support+window_ntile_support+window_percent_rank_support+window_rank_support+window_row_number_support+xid+xid8_larger+xid8_smaller+xid8cmp+xid8eq+xid8ge+xid8gt+xid8in+xid8le+xid8lt+xid8ne+xid8out+xid8recv+xid8send+xideq+xideqint4+xidin+xidneq+xidneqint4+xidout+xidrecv+xidsend+xml+xml_in+xml_is_well_formed+xml_is_well_formed_content+xml_is_well_formed_document+xml_out+xml_recv+xml_send+xmlagg+xmlcomment+xmlconcat2+xmlexists+xmltext+xmlvalidate+xpath+xpath_existsdiff --git a/server/src/db/engine/postgres/plugin-sql-functions.ts b/server/src/db/engine/postgres/plugin-sql-functions.tsnew file mode 100644index 000000000..068cd8e54--- /dev/null+++ b/server/src/db/engine/postgres/plugin-sql-functions.ts@@ -0,0 +1,496 @@+import fs from 'node:fs';+import path from 'node:path';++/**+ * Which of Postgres's own functions a plugin's SQL may call.+ *+ * A plugin's statements run on the plugin's `search_path`, its schema and+ * `pg_temp`, and a plugin cannot create a function (the guard refuses CREATE+ * FUNCTION). So an unqualified call either finds nothing, finds one of the+ * functions its range types bring along, or finds a function of `pg_catalog`,+ * which Postgres searches first. Many of those read the catalogs or the+ * server rather than the values handed to them: `obj_description` and+ * `col_description` return the comment on any object by its OID,+ * `format_type` names a type by its OID, `version()`, `current_database()` and+ * `inet_server_addr()` describe the server, `txid_current()` the cluster's+ * activity. Listing those one by one would miss the next one Postgres adds.+ *+ * So the rule is an allowlist: a call to a function of `pg_catalog` is+ * refused unless its name is in {@link PLUGIN_FUNCTIONS}, the string, math,+ * date and time, JSON, array, range, aggregate, window, UUID and text search+ * functions a data plugin plausibly needs, each of which works only on its+ * arguments. A name counts as called when `(` follows it (`version()`,+ * `"version" ()`) or when it follows `).`, Postgres's column notation for a+ * call (`(16386::oid).obj_description`). A plugin's own table or type may+ * still carry such a name where it cannot be a call: after INTO, TABLE, VIEW,+ * REFERENCES or IF NOT EXISTS (`INSERT INTO version (...)`).+ *+ * Which names are functions of `pg_catalog` is read from+ * `assets/postgres/catalog-functions.txt`: every function name of every+ * supported major (14 to 18; the boot refuses any other server). The Postgres+ * lane compares it with `pg_proc` on the server it runs on and fails on a+ * name missing there (PGPLUG-021), so a new major cannot add a function a+ * plugin may call without someone deciding whether it belongs here.+ *+ * The SQL keywords that call a function without parentheses+ * ({@link SESSION_KEYWORDS}: `current_user`, `current_catalog`, ...) are+ * refused unquoted wherever they appear; quoted they are plain names. A+ * name starting with `pg_` is refused anywhere by the guard itself.+ */++/** The functions of `pg_catalog` a plugin may call. Each must exist in the catalog list (a unit test checks). */+export const PLUGIN_FUNCTIONS: ReadonlySet<string> = new Set([+ // Strings and bytes.+ 'ascii',+ 'bit_count',+ 'bit_length',+ 'btrim',+ 'casefold',+ 'char_length',+ 'character_length',+ 'chr',+ 'concat',+ 'concat_ws',+ 'convert',+ 'convert_from',+ 'convert_to',+ 'crc32',+ 'crc32c',+ 'decode',+ 'encode',+ 'format',+ 'get_bit',+ 'get_byte',+ 'initcap',+ 'is_normalized',+ 'left',+ 'length',+ 'like',+ 'lower',+ 'lpad',+ 'ltrim',+ 'md5',+ 'normalize',+ 'octet_length',+ 'overlay',+ 'position',+ 'quote_ident',+ 'quote_literal',+ 'quote_nullable',+ 'regexp_count',+ 'regexp_instr',+ 'regexp_like',+ 'regexp_match',+ 'regexp_matches',+ 'regexp_replace',+ 'regexp_split_to_array',+ 'regexp_split_to_table',+ 'regexp_substr',+ 'repeat',+ 'replace',+ 'reverse',+ 'right',+ 'rpad',+ 'rtrim',+ 'set_bit',+ 'set_byte',+ 'sha224',+ 'sha256',+ 'sha384',+ 'sha512',+ 'split_part',+ 'starts_with',+ 'string_to_array',+ 'string_to_table',+ 'strpos',+ 'substr',+ 'substring',+ 'to_ascii',+ 'to_bin',+ 'to_hex',+ 'to_oct',+ 'translate',+ 'unistr',+ 'upper',+ // Numbers.+ 'abs',+ 'acos',+ 'acosd',+ 'acosh',+ 'asin',+ 'asind',+ 'asinh',+ 'atan',+ 'atan2',+ 'atan2d',+ 'atand',+ 'atanh',+ 'cbrt',+ 'ceil',+ 'ceiling',+ 'cos',+ 'cosd',+ 'cosh',+ 'cot',+ 'cotd',+ 'degrees',+ 'div',+ 'erf',+ 'erfc',+ 'exp',+ 'factorial',+ 'floor',+ 'gamma',+ 'gcd',+ 'lcm',+ 'lgamma',+ 'ln',+ 'log',+ 'log10',+ 'min_scale',+ 'mod',+ 'pi',+ 'pow',+ 'power',+ 'radians',+ 'random',+ 'random_normal',+ 'round',+ 'scale',+ 'sign',+ 'sin',+ 'sind',+ 'sinh',+ 'sqrt',+ 'tan',+ 'tand',+ 'tanh',+ 'trim_scale',+ 'trunc',+ 'width_bucket',+ // Dates and times.+ 'age',+ 'clock_timestamp',+ 'date_add',+ 'date_bin',+ 'date_part',+ 'date_subtract',+ 'date_trunc',+ 'extract',+ 'isfinite',+ 'justify_days',+ 'justify_hours',+ 'justify_interval',+ 'make_date',+ 'make_interval',+ 'make_time',+ 'make_timestamp',+ 'make_timestamptz',+ 'now',+ 'overlaps',+ 'statement_timestamp',+ 'timeofday',+ 'timezone',+ 'to_char',+ 'to_date',+ 'to_number',+ 'to_timestamp',+ 'transaction_timestamp',+ // Conversions, also the type names written with a modifier (`varchar(20)`, `numeric(10, 2)`).+ 'bit',+ 'bool',+ 'bpchar',+ 'bytea',+ 'char',+ 'date',+ 'float4',+ 'float8',+ 'int2',+ 'int4',+ 'int8',+ 'interval',+ 'numeric',+ 'text',+ 'time',+ 'timestamp',+ 'timestamptz',+ 'timetz',+ 'varbit',+ 'varchar',+ // JSON.+ 'array_to_json',+ 'json_agg',+ 'json_agg_strict',+ 'json_array_elements',+ 'json_array_elements_text',+ 'json_array_length',+ 'json_build_array',+ 'json_build_object',+ 'json_each',+ 'json_each_text',+ 'json_extract_path',+ 'json_extract_path_text',+ 'json_object',+ 'json_object_agg',+ 'json_object_agg_strict',+ 'json_object_agg_unique',+ 'json_object_agg_unique_strict',+ 'json_object_keys',+ 'json_populate_record',+ 'json_populate_recordset',+ 'json_strip_nulls',+ 'json_to_record',+ 'json_to_recordset',+ 'json_typeof',+ 'jsonb_agg',+ 'jsonb_agg_strict',+ 'jsonb_array_elements',+ 'jsonb_array_elements_text',+ 'jsonb_array_length',+ 'jsonb_build_array',+ 'jsonb_build_object',+ 'jsonb_each',+ 'jsonb_each_text',+ 'jsonb_extract_path',+ 'jsonb_extract_path_text',+ 'jsonb_insert',+ 'jsonb_object',+ 'jsonb_object_agg',+ 'jsonb_object_agg_strict',+ 'jsonb_object_agg_unique',+ 'jsonb_object_agg_unique_strict',+ 'jsonb_object_keys',+ 'jsonb_path_exists',+ 'jsonb_path_exists_tz',+ 'jsonb_path_match',+ 'jsonb_path_match_tz',+ 'jsonb_path_query',+ 'jsonb_path_query_array',+ 'jsonb_path_query_array_tz',+ 'jsonb_path_query_first',+ 'jsonb_path_query_first_tz',+ 'jsonb_path_query_tz',+ 'jsonb_populate_record',+ 'jsonb_populate_record_valid',+ 'jsonb_populate_recordset',+ 'jsonb_pretty',+ 'jsonb_set',+ 'jsonb_set_lax',+ 'jsonb_strip_nulls',+ 'jsonb_to_record',+ 'jsonb_to_recordset',+ 'jsonb_typeof',+ 'row_to_json',+ 'to_json',+ 'to_jsonb',+ // Arrays and sets.+ 'array_append',+ 'array_cat',+ 'array_dims',+ 'array_fill',+ 'array_length',+ 'array_lower',+ 'array_ndims',+ 'array_position',+ 'array_positions',+ 'array_prepend',+ 'array_remove',+ 'array_replace',+ 'array_reverse',+ 'array_sample',+ 'array_shuffle',+ 'array_sort',+ 'array_to_string',+ 'array_upper',+ 'cardinality',+ 'generate_series',+ 'generate_subscripts',+ 'trim_array',+ 'unnest',+ 'num_nonnulls',+ 'num_nulls',+ // Aggregates.+ 'any_value',+ 'array_agg',+ 'avg',+ 'bit_and',+ 'bit_or',+ 'bit_xor',+ 'bool_and',+ 'bool_or',+ 'corr',+ 'count',+ 'covar_pop',+ 'covar_samp',+ 'every',+ 'max',+ 'min',+ 'mode',+ 'percentile_cont',+ 'percentile_disc',+ 'range_agg',+ 'range_intersect_agg',+ 'regr_avgx',+ 'regr_avgy',+ 'regr_count',+ 'regr_intercept',+ 'regr_r2',+ 'regr_slope',+ 'regr_sxx',+ 'regr_sxy',+ 'regr_syy',+ 'stddev',+ 'stddev_pop',+ 'stddev_samp',+ 'string_agg',+ 'sum',+ 'var_pop',+ 'var_samp',+ 'variance',+ // Window functions.+ 'cume_dist',+ 'dense_rank',+ 'first_value',+ 'lag',+ 'last_value',+ 'lead',+ 'nth_value',+ 'ntile',+ 'percent_rank',+ 'rank',+ 'row_number',+ // UUIDs.+ 'gen_random_uuid',+ 'uuid_extract_timestamp',+ 'uuid_extract_version',+ 'uuidv4',+ 'uuidv7',+ // Ranges and the plugin's own enum types.+ 'datemultirange',+ 'daterange',+ 'enum_first',+ 'enum_last',+ 'enum_range',+ 'int4multirange',+ 'int4range',+ 'int8multirange',+ 'int8range',+ 'isempty',+ 'lower_inc',+ 'lower_inf',+ 'multirange',+ 'nummultirange',+ 'numrange',+ 'range_merge',+ 'tsmultirange',+ 'tsrange',+ 'tstzmultirange',+ 'tstzrange',+ 'upper_inc',+ 'upper_inf',+ // Geometry.+ 'area',+ 'bound_box',+ 'box',+ 'center',+ 'circle',+ 'diagonal',+ 'diameter',+ 'height',+ 'isclosed',+ 'isopen',+ 'line',+ 'lseg',+ 'npoints',+ 'path',+ 'pclose',+ 'point',+ 'polygon',+ 'popen',+ 'radius',+ 'slope',+ 'width',+ // Network addresses.+ 'abbrev',+ 'broadcast',+ 'cidr',+ 'family',+ 'host',+ 'hostmask',+ 'inet_merge',+ 'inet_same_family',+ 'macaddr',+ 'macaddr8',+ 'masklen',+ 'netmask',+ 'network',+ 'set_masklen',+ // Full text search. ts_stat and ts_rewrite run SQL handed to them as text and stay refused.+ 'array_to_tsvector',+ 'json_to_tsvector',+ 'jsonb_to_tsvector',+ 'numnode',+ 'phraseto_tsquery',+ 'plainto_tsquery',+ 'querytree',+ 'setweight',+ 'strip',+ 'to_tsquery',+ 'to_tsvector',+ 'ts_delete',+ 'ts_filter',+ 'ts_headline',+ 'ts_rank',+ 'ts_rank_cd',+ 'tsvector_to_array',+ 'websearch_to_tsquery',+ // The TABLESAMPLE methods (`TABLESAMPLE SYSTEM (10)`).+ 'bernoulli',+ 'system',+]);++/**+ * The SQL keywords that call a catalog function without parentheses and+ * describe the session or the server: the role names, the database and the+ * schema. Refused unquoted anywhere; a quoted `"user"` is a column.+ */+export const SESSION_KEYWORDS: ReadonlySet<string> = new Set([+ 'current_catalog',+ 'current_role',+ 'current_schema',+ 'current_user',+ 'session_user',+ 'system_user',+ 'user',+]);++/** The function names of `pg_catalog` on every supported major, one per line, sorted. */+export const CATALOG_FUNCTIONS_FILE = path.join(+ __dirname,+ '..',+ '..',+ '..',+ '..',+ 'assets',+ 'postgres',+ 'catalog-functions.txt',+);++let catalog: ReadonlySet<string> | undefined;++/** The names in {@link CATALOG_FUNCTIONS_FILE}, read once. */+export function catalogFunctionNames(): ReadonlySet<string> {+ catalog ??= new Set(+ fs+ .readFileSync(CATALOG_FUNCTIONS_FILE, 'utf8')+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line !== ''),+ );+ return catalog;+}++/** Whether calling `name` reaches a function of `pg_catalog` a plugin may not call. */+export function refusedCatalogCall(name: string): boolean {+ return !PLUGIN_FUNCTIONS.has(name) && catalogFunctionNames().has(name);+}diff --git a/server/src/db/engine/postgres/plugin-sql-guard.ts b/server/src/db/engine/postgres/plugin-sql-guard.tsindex e12b1797a..8742f7953 100644--- a/server/src/db/engine/postgres/plugin-sql-guard.ts+++ b/server/src/db/engine/postgres/plugin-sql-guard.ts@@ -1,4 +1,5 @@import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';+import { refusedCatalogCall, SESSION_KEYWORDS } from './plugin-sql-functions';/*** What keeps a plugin's own SQL on Postgres inside its own schema.@@ -69,6 +70,12 @@ import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';* `setval`, `has_table_privilege` and its siblings, `currtid2`, the BRIN* and GIN maintenance functions, `to_reg*`), large objects (`lo_*`) or* `dblink`;+ * - a call to a function of `pg_catalog` that is not on the allowlist in+ * `plugin-sql-functions.ts` (`obj_description`, `format_type`, `version`,+ * `current_database`, ...: whatever reads the catalogs or the server rather+ * than its arguments), in either spelling of a call (`f(...)`, or the+ * column notation `(x).f`), and the keywords that name the session's roles,+ * database or schema (`current_user`, `session_user`, `current_catalog`, ...);* - the object identifier types that look an object up by name* (`regclass`, `regtype`, `regproc`, `regprocedure`, `regoper`,* `regoperator`, `regconfig`, `regdictionary`, `regnamespace`, `regrole`,@@ -472,6 +479,7 @@ function describe(text: string, tokens: Token[]): PluginStatement {if (token.kind === 'punct' && token.value === ')') depth--;if (token.kind !== 'word') continue;checkName(token.value);+ checkCall(tokens, index);const after = tokens[index + 1];if (after?.kind === 'punct' && after.value === '.') qualifies = true;if (token.quoted) continue;@@ -538,6 +546,39 @@ function checkObject(verb: string, tokens: readonly Token[]): void {function checkKeyword(word: string): void {if (word === 'recursive') throw new PluginSqlRefused('WITH RECURSIVE is not allowed');if (word === 'tablespace') throw new PluginSqlRefused('a tablespace may not be named');+ if (SESSION_KEYWORDS.has(word)) {+ throw new PluginSqlRefused(`${word.toUpperCase()} describes the session, which a plugin may not read`);+ }+}++/** The keywords after which a name followed by `(` is an object's, not a call: `INSERT INTO version (...)`. */+const NAME_BEFORE = new Set(['into', 'table', 'view', 'references', 'exists']);++/**+ * Refuses the word at `index` when it calls a function of `pg_catalog` a+ * plugin may not call (`plugin-sql-functions.ts`): followed by `(`, unless+ * it names an object after one of {@link NAME_BEFORE}, or in Postgres's+ * column notation for a call, right after `).` or `].` (`(16386::oid).obj_description`).+ */+function checkCall(tokens: readonly Token[], index: number): void {+ const token = tokens[index];+ if (token.kind !== 'word') return;+ const before = tokens[index - 2];+ const columnNotation = isPunct(tokens[index - 1], '.') && (isPunct(before, ')') || isPunct(before, ']'));+ const called = columnNotation || (isPunct(tokens[index + 1], '(') && !namesObject(tokens, index));+ if (called && refusedCatalogCall(token.value)) {+ throw new PluginSqlRefused(+ `"${token.value}" is a function of the Postgres catalog that a plugin may not call; ` ++ "the plugin SDK's README lists the functions a plugin may call",+ );+ }+}++/** Whether the (possibly qualified) name ending at `index` follows one of {@link NAME_BEFORE}. */+function namesObject(tokens: readonly Token[], index: number): boolean {+ let start = index;+ while (isPunct(tokens[start - 1], '.') && tokens[start - 2]?.kind === 'word') start -= 2;+ return NAME_BEFORE.has(keyword(tokens[start - 1]) ?? '');}/**diff --git a/server/tests/postgres/plugin-data.test.ts b/server/tests/postgres/plugin-data.test.tsindex 76a1769a5..ad1b8b458 100644--- a/server/tests/postgres/plugin-data.test.ts+++ b/server/tests/postgres/plugin-data.test.ts@@ -1,5 +1,5 @@/**- * PGPLUG-001..020 — a plugin's own data (`db:own`) on Postgres, against the+ * PGPLUG-001..021 — a plugin's own data (`db:own`) on Postgres, against the* real app on the lane's database: each plugin gets a schema of its own and no* SQLite file, its SQL keeps the SQLite store's semantics (migrate once per* id, a script's statements committed one by one, an atomic tx, the row cap,@@ -24,6 +24,7 @@ import {poolClients,PostgresPluginDataStore,} from '../../src/db/engine/postgres/plugin-data-store';+import { catalogFunctionNames } from '../../src/db/engine/postgres/plugin-sql-functions';import { TrekPostgreSqlDriver } from '../../src/db/engine/postgres/postgres-driver';import { putTempSchemaLast } from '../../src/db/engine/postgres/session-search-path';import { DATABASE_SETTINGS } from '../../src/nest/database/database-engine.module';@@ -687,4 +688,53 @@ describe('plugin data on Postgres', () => {await store.exec('INSERT INTO raw VALUES ($1)', [Buffer.from([1, 0, 2])]);expect(await store.query('SELECT length(b) AS n FROM raw')).toEqual([{ n: 3 }]);});++ it("PGPLUG-021: a plugin calls only the catalog's functions on the allowlist, and every function of this server is listed", async () => {+ const rows = await asSuper<{ proname: string }>(+ "select distinct proname from pg_proc where pronamespace = 'pg_catalog'::regnamespace",+ );+ const unlisted = rows.map((row) => row.proname).filter((name) => !catalogFunctionNames().has(name));+ expect(+ unlisted,+ 'These functions of this Postgres are missing from server/assets/postgres/catalog-functions.txt. ' ++ 'Add each name there (one per line, keep it sorted), and to PLUGIN_FUNCTIONS in ' ++ 'src/db/engine/postgres/plugin-sql-functions.ts only if it works on its arguments alone ' ++ 'and reads neither the catalogs nor the server.',+ ).toEqual([]);++ await asSuper("comment on table users is 'catalog comment the plugin must not read'");+ const [{ oid }] = await asSuper<{ oid: number }>("select 'public.users'::regclass::oid::int8 as oid");+ const store = data.open('pg-catalog');+ await store.migrate('001', 'CREATE TABLE version (id bigserial PRIMARY KEY, body text NOT NULL)');+ await Promise.all(+ [+ `select obj_description(${oid})`,+ `select obj_description(${oid}, 'pg_class')`,+ `select col_description(${oid}, 1)`,+ `select (${oid}::oid).obj_description`,+ `select "obj_description"(${oid})`,+ "select shobj_description(10, 'pg_authid')",+ `select format_type(${oid}, null)`,+ 'select version()',+ 'select current_database()',+ 'select inet_server_addr()',+ 'select current_user',+ 'select session_user',+ 'select current_catalog',+ ].map((sql) => expect(store.query(sql), sql).rejects.toThrow(/a plugin may not (call|read)/)),+ );+ // A table named like a refused function, and the functions a plugin needs, still work.+ await store.exec('INSERT INTO version (body) VALUES ($1), ($2)', ['Alpha', 'beta']);+ expect(+ await store.query(+ "SELECT lower(body) AS b, length(body) AS n, jsonb_build_object('k', id)->>'k' AS k, " ++ "to_char(date_trunc('day', now()), 'YYYY') <> '' AS d, gen_random_uuid() IS NOT NULL AS u " ++ 'FROM version ORDER BY id',+ ),+ ).toEqual([+ { b: 'alpha', n: 5, k: '1', d: true, u: true },+ { b: 'beta', n: 4, k: '2', d: true, u: true },+ ]);+ await asSuper('comment on table users is null');+ });});diff --git a/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.ts b/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.tsnew file mode 100644index 000000000..e1d1fed33--- /dev/null+++ b/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.ts@@ -0,0 +1,102 @@+/**+ * Which of Postgres's own functions a plugin's SQL may call+ * (src/db/engine/postgres/plugin-sql-functions.ts), as the guard applies it+ * without a database: the catalog's functions outside the allowlist are+ * refused in every spelling of a call, the allowed ones and a plugin's own+ * names pass. PGPLUG-021 in the Postgres lane holds the catalog list to the+ * real `pg_proc` and runs the same payloads against a database.+ */+import {+ catalogFunctionNames,+ CATALOG_FUNCTIONS_FILE,+ PLUGIN_FUNCTIONS,+} from '../../../../../src/db/engine/postgres/plugin-sql-functions';+import { parsePluginSql } from '../../../../../src/db/engine/postgres/plugin-sql-guard';++import fs from 'node:fs';+import { describe, expect, it } from 'vitest';++describe('functions a plugin may call on Postgres', () => {+ it('lists the catalog functions one per line, sorted and without duplicates', () => {+ const lines = fs.readFileSync(CATALOG_FUNCTIONS_FILE, 'utf8').trimEnd().split(/\r?\n/);+ expect(lines.length).toBeGreaterThan(2000);+ expect(lines).toEqual([...new Set(lines)].sort());+ expect(lines.every((line) => /^[A-Za-z0-9_]+$/.test(line))).toBe(true);+ });++ it('allows only functions the catalog has, so a typo cannot stand in for one', () => {+ const missing = [...PLUGIN_FUNCTIONS].filter((name) => !catalogFunctionNames().has(name));+ expect(missing).toEqual([]);+ });++ it.each([+ // The catalog lookups by OID the review found, and their siblings.+ 'select obj_description(16386)',+ "select obj_description(16386, 'pg_class')",+ 'select col_description(16386, 2)',+ "select shobj_description(16384, 'pg_authid')",+ 'select format_type(16388, null)',+ // Server and session information.+ 'select version()',+ 'select current_database()',+ 'select inet_server_addr(), inet_server_port()',+ 'select inet_client_addr()',+ 'select current_query()',+ 'select current_schemas(true)',+ 'select txid_current()',+ 'select getdatabaseencoding()',+ "select has_largeobject_privilege(1, 'select')",+ 'select acldefault(1, 10)',+ 'select setseed(0.5)',+ // Every spelling of the call.+ 'SELECT OBJ_DESCRIPTION(16386)',+ 'select "obj_description"(16386)',+ 'select obj_description /* x */ (16386)',+ 'select (16386::oid).obj_description',+ 'select (16386::oid)."obj_description"',+ 'select (array[16386::oid])[1].obj_description',+ 'select n.x from notes n where n.body = (select version())',+ 'create table t (v text default version())',+ 'insert into notes (body) values (current_database())',+ // The keywords that call one without parentheses.+ 'select current_user',+ 'select session_user',+ 'select current_role',+ 'select user',+ 'select system_user',+ 'select current_catalog',+ 'select current_schema',+ 'select CURRENT_USER',+ ])('refuses %s', (sql) => {+ expect(() => parsePluginSql(sql)).toThrow(/a plugin may not (call|read)/);+ });++ it.each([+ "select lower(body), substring(body from 2 for 3), regexp_replace(body, 'a', 'b') from notes",+ "select now(), date_trunc('day', now()), extract(epoch from now()), to_char(now(), 'YYYY')",+ "select jsonb_build_object('a', 1), jsonb_set('{}'::jsonb, '{a}', '1'), json_agg(body) from notes",+ 'select count(*), sum(n), string_agg(body, $1), row_number() over (order by id) from notes',+ 'select gen_random_uuid(), md5(body), sha256(body::bytea) from notes',+ 'select x from generate_series(1, 5) as g(x)',+ 'select unnest(array[1, 2]), cardinality(array[1])',+ "select to_tsvector('english', body) @@ plainto_tsquery('english', $1) from notes",+ 'select coalesce(a, b), nullif(a, 0), greatest(a, b), least(a, b) from notes',+ "select cast(n as numeric(10, 2)), body::varchar(20), 'now'::timestamp(3) from notes",+ 'select current_date, current_timestamp, localtimestamp',+ "select a from notes where body like ('%' || $1)",+ 'select * from notes tablesample system (10)',+ // A plugin's own names, even where they share a refused function's name.+ 'CREATE TABLE version (id bigserial PRIMARY KEY, format_type text)',+ 'CREATE TABLE IF NOT EXISTS version (id bigint)',+ 'INSERT INTO version (id) VALUES (1)',+ 'INSERT INTO trek_plugin_notes.version (id) VALUES (1)',+ 'CREATE TABLE notes (id bigint, v bigint REFERENCES version (id))',+ 'CREATE VIEW version (a) AS SELECT 1',+ 'select n.version, n.user_id, "user", "current_user" from notes n',+ 'select version from notes',+ 'select mine(1, 2)',+ "select '[1,2)'::span",+ ])('allows %s', (sql) => {+ expect(() => parsePluginSql(sql)).not.toThrow();+ });+});diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.mdindex 1a0c87361..0367615ab 100644--- a/wiki/Database-Postgres.md+++ b/wiki/Database-Postgres.md@@ -189,7 +189,7 @@ A plugin with the `db:own` permission keeps its own database. On SQLite that is- **TREK's role creates the schemas**, so it needs the `CREATE` privilege on the database, which the role that owns the database has.- **No plugin SQL on a privileged role.** While `TREK_DB_URL` connects as a role TREK refuses restores for (a superuser or a member of one, or a role that may reach the server's files or programs; see [A role that is not a superuser](#a-role-that-is-not-a-superuser)), every plugin database call fails with "Plugin databases (db:own) are refused on Postgres ...", and the boot log says so. A plugin's SQL runs as TREK's role, and such a role could change the system catalogs for the whole server. Connect TREK as a role that owns its database and is not a superuser, and restart; TREK reads the role once per pool connection.- **A plugin's SQL stays in its schema**, in layers the database enforces as well as TREK's own check:- - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `has_table_privilege` and its siblings). It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.+ - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `has_table_privilege` and its siblings). Of PostgreSQL's own functions a plugin may call only those on an allowlist, the ones that work on their arguments alone (string, number, date and time, JSON, array, aggregate, window, UUID, range, geometry, network address and full text search functions). Every other one is refused, so a function that reads the catalogs or the server (`obj_description`, `format_type`, `version()`, `current_database()`, `inet_server_addr()`, ...) cannot reveal the names or comments of TREK's objects, and neither can a function a later PostgreSQL adds; the keywords `current_user`, `session_user` and their siblings are refused too. It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.- Right before an `ALTER`, `DROP`, `REFRESH`, `TRUNCATE` or `CREATE INDEX ... ON`, Postgres itself resolves the objects the statement changes, and TREK refuses it unless each one lies in the plugin's schema. An unqualified `int4` or `text` is the built-in type and is refused, whatever the role may do.- Each statement is sent on its own over the extended query protocol, which runs one statement and no more.- Every connection of TREK's pool searches the temporary schema last, and a plugin call drops the temporary tables and other session state of the connection it used before handing it back, so a temporary table can never stand in for one of TREK's.