Skip to main content

postrust_core/schema_cache/
queries.rs

1//! SQL queries for schema introspection.
2
3use super::relationship::{
4    Cardinality, MediaHandler, MediaHandlerMap, Relationship, RelationshipsMap,
5};
6use super::routine::{FuncVolatility, RetType, Routine, RoutineMap, RoutineParam};
7use super::table::{Column, ColumnMap, Table, TablesMap};
8use crate::api_request::QualifiedIdentifier;
9use crate::db::Tx;
10use crate::error::{Error, Result};
11use indexmap::IndexMap;
12use postrust_sql::SqlParam;
13use std::collections::{HashMap, HashSet};
14use std::sync::LazyLock;
15
16/// Get PostgreSQL version.
17pub async fn get_pg_version<T: Tx>(tx: &mut T) -> Result<i32> {
18    let rows = catalog(
19        tx,
20        "SELECT current_setting('server_version_num')::int as version",
21        &[],
22        &[],
23    )
24    .await?;
25    match rows.first() {
26        Some(row) => row.get("version"),
27        None => Err(Error::SchemaCacheLoadFailed(
28            "no rows returned by a query that expected to return at least one row".into(),
29        )),
30    }
31}
32
33/// A row of a catalog query, as PostgreSQL's own `row_to_json` rendered it.
34///
35/// The catalog is read through the same driver-neutral interface as requests
36/// (`crate::db`), whose drivers decode the types a response carries. Catalog
37/// rows carry others -- `name[]`, `text[]` -- so each query is wrapped to
38/// return its row as one `json` value and PostgreSQL does the decoding. A
39/// driver then needs nothing but `json` to load a schema cache.
40pub(super) struct CatalogRow(serde_json::Map<String, serde_json::Value>);
41
42impl CatalogRow {
43    /// A column, by name. A value of the wrong type fails the load rather than
44    /// the process.
45    ///
46    /// A column the query does not have is an error too, not a null.
47    /// `row_to_json` writes every column, null ones included, so an absent key
48    /// is a name misspelled here or in the query's alias -- and read as null it
49    /// would turn every `Option` field it fills into `None`, silently.
50    pub(super) fn get<V: serde::de::DeserializeOwned>(&self, column: &str) -> Result<V> {
51        let value = self.0.get(column).ok_or_else(|| {
52            Error::SchemaCacheLoadFailed(format!("catalog query has no column \"{column}\""))
53        })?;
54        V::deserialize(value)
55            .map_err(|e| Error::SchemaCacheLoadFailed(format!("catalog column \"{column}\": {e}")))
56    }
57}
58
59/// Run a catalog query, reading each row as [`CatalogRow`], ordered by the
60/// query's output columns `order_by`. Empty where the order does not matter.
61///
62/// The query's own `ORDER BY` is not enough. It sorts the subquery the
63/// wrapper reads from, and SQL promises nothing about the order a query
64/// reads a sorted subquery in. PostgreSQL keeps it today, but where a row
65/// order reaches the client (see `load_relationships`) that is not a thing to
66/// lean on. The planner sees that the subquery is already in this order, so
67/// asking again costs no second sort.
68async fn catalog<T: Tx>(
69    tx: &mut T,
70    sql: &str,
71    order_by: &[&str],
72    params: &[SqlParam],
73) -> Result<Vec<CatalogRow>> {
74    tx.fetch_values(&catalog_sql(sql, order_by), params)
75        .await
76        .map_err(|e| Error::SchemaCacheLoadFailed(e.to_string()))?
77        .into_iter()
78        .map(|row| match row.into_iter().next() {
79            Some(serde_json::Value::Object(map)) => Ok(CatalogRow(map)),
80            other => Err(Error::SchemaCacheLoadFailed(format!(
81                "a catalog row was not an object: {other:?}"
82            ))),
83        })
84        .collect()
85}
86
87/// A catalog query, wrapped to return each row as one `json` value, in the
88/// order of its output columns `order_by`. See [`catalog`].
89fn catalog_sql(sql: &str, order_by: &[&str]) -> String {
90    let mut wrapped = format!("SELECT row_to_json(pgrst_catalog) FROM ({sql}) AS pgrst_catalog");
91    for (i, column) in order_by.iter().enumerate() {
92        wrapped.push_str(if i == 0 { " ORDER BY " } else { ", " });
93        wrapped.push_str("pgrst_catalog.");
94        wrapped.push_str(column);
95    }
96    wrapped
97}
98
99/// A text parameter.
100fn text(value: &str) -> SqlParam {
101    SqlParam::Text(value.to_string())
102}
103
104/// A `text[]` parameter.
105fn texts(values: &[String]) -> SqlParam {
106    SqlParam::Array(values.iter().cloned().map(SqlParam::Text).collect())
107}
108
109/// Whether a role this connection can become holds one of `privileges` in the
110/// ACL `acl`, or `PUBLIC` does.
111///
112/// This is the test `information_schema` makes, with one word changed. Its
113/// views ask `pg_has_role(role, 'USAGE')` -- does this connection hold the
114/// role's privileges *without* switching to it -- which is false of every role
115/// granted to a `NOINHERIT` authenticator. That is the setup PostgREST
116/// recommends, and the one where the API runs every request after `SET ROLE`:
117/// what the authenticator could do *as itself* is beside the point, and with
118/// `USAGE` the schema cache saw no tables at all. `MEMBER` asks whether the
119/// connection can become the role, which is what a request does.
120///
121/// For a superuser, or an authenticator that inherits, the two answers are
122/// the same, so nothing about those deployments changes.
123///
124fn acl_grants(acl: &str, privileges: &str) -> String {
125    format!(
126        "EXISTS (SELECT 1 FROM aclexplode({acl}) g \
127          WHERE g.privilege_type = ANY ('{{{privileges}}}'::text[]) \
128            AND {grantee})",
129        grantee = can_become("g.grantee"),
130    )
131}
132
133/// Whether this connection can become the role `role` (an OID expression), or
134/// `role` is `PUBLIC`, which every role is.
135///
136/// `CASE` rather than `OR`: SQL does not promise to short-circuit, and
137/// `pg_has_role` refuses OID 0, which is how an ACL spells `PUBLIC`.
138fn can_become(role: &str) -> String {
139    format!("CASE WHEN {role} = 0 THEN true ELSE pg_has_role({role}, 'MEMBER') END")
140}
141
142/// Whether this connection can become a predefined role that holds privileges
143/// on every table without appearing in any ACL: `pg_read_all_data` and
144/// `pg_write_all_data` (PostgreSQL 14 and later). `has_table_privilege`, which
145/// `information_schema` asks, counts them, so a scan of the ACLs alone hid
146/// every table from a deployment that grants one of these instead of
147/// per-table privileges. Looked up by name, so on a server too old to have
148/// them this is simply false rather than an error.
149const PREDEFINED_DATA_ROLE: &str = "EXISTS (SELECT 1 FROM pg_roles pr \
150     WHERE pr.rolname IN ('pg_read_all_data', 'pg_write_all_data') \
151       AND pg_has_role(pr.oid, 'MEMBER'))";
152
153/// A relation's own ACL, or the owner-only default it stands for when unset.
154const RELATION_ACL: &str = "COALESCE(c.relacl, acldefault('r', c.relowner))";
155
156/// Whether a relation is visible to this connection: `information_schema.tables`'
157/// condition, with `MEMBER` for `USAGE` (see `acl_grants`). A role it can
158/// become owns it, or holds a privilege on it or on one of its columns, or
159/// reads or writes every table (see `PREDEFINED_DATA_ROLE`).
160fn relation_visible() -> String {
161    format!(
162        "(pg_has_role(c.relowner, 'MEMBER') \
163          OR {PREDEFINED_DATA_ROLE} \
164          OR {table} \
165          OR EXISTS (SELECT 1 FROM pg_attribute ca \
166                      WHERE ca.attrelid = c.oid AND ca.attnum > 0 \
167                        AND NOT ca.attisdropped AND ca.attacl IS NOT NULL \
168                        AND {column}))",
169        table = acl_grants(
170            RELATION_ACL,
171            "SELECT,INSERT,UPDATE,DELETE,TRUNCATE,REFERENCES,TRIGGER"
172        ),
173        column = acl_grants("ca.attacl", "SELECT,INSERT,UPDATE,REFERENCES"),
174    )
175}
176
177/// Whether a privilege on a relation is held by anyone this connection can
178/// act for: `information_schema.table_privileges`' condition -- the grant is
179/// visible when its grantor or its grantee is a role this connection can
180/// become, or the grantee is `PUBLIC` -- with `MEMBER` for `USAGE`.
181fn privilege_granted(privilege: &str) -> String {
182    format!(
183        "(c.relkind IN ('r', 'v', 'f', 'p') AND EXISTS (\
184            SELECT 1 FROM aclexplode({RELATION_ACL}) g \
185             WHERE g.privilege_type = '{privilege}' \
186               AND ({grantee} OR pg_has_role(g.grantor, 'MEMBER'))))",
187        grantee = can_become("g.grantee"),
188    )
189}
190
191/// Load all tables and their columns.
192pub async fn load_tables<T: Tx>(tx: &mut T, schemas: &[String]) -> Result<TablesMap> {
193    let mut tables = HashMap::new();
194
195    // From the catalogue rather than `information_schema`, whose views show a
196    // connection only what it can use without switching role -- nothing, for
197    // a NOINHERIT authenticator. See `acl_grants`. Built once: it does not
198    // change between loads.
199    static SQL: LazyLock<String> = LazyLock::new(|| {
200        format!(
201            r#"
202        SELECT
203            t.table_schema,
204            t.table_name,
205            t.table_type,
206            pg_catalog.obj_description(t.oid, 'pg_class') as description,
207            COALESCE(
208                (SELECT array_agg(a.attname::text ORDER BY array_position(i.indkey, a.attnum))
209                FROM pg_index i
210                JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
211                WHERE i.indrelid = t.oid
212                  AND i.indisprimary),
213                ARRAY[]::text[]
214            ) as pk_cols,
215            -- Being granted INSERT on a view does not make the view
216            -- insertable. A view is written through only where it is simple
217            -- enough for PostgreSQL to write through automatically, or where
218            -- an INSTEAD OF trigger says how -- `projects_view_without_triggers`
219            -- carries every grant and accepts nothing. Both halves have to
220            -- hold. A table is not a view, so the grant is the whole answer
221            -- there.
222            --
223            -- The view half is `information_schema.views`' own: the bits of
224            -- `pg_relation_is_updatable` it reads, and the INSTEAD OF trigger
225            -- types (`tgtype` 69 insert, 81 update, 73 delete).
226            {insert} AND (
227                t.relkind <> 'v'
228                OR (pg_relation_is_updatable(t.oid, false) & 8) = 8
229                OR EXISTS (SELECT 1 FROM pg_trigger tg
230                            WHERE tg.tgrelid = t.oid AND (tg.tgtype::int & 69) = 69)
231            ) as insertable,
232            {update} AND (
233                t.relkind <> 'v'
234                OR (pg_relation_is_updatable(t.oid, false) & 20) = 20
235                OR EXISTS (SELECT 1 FROM pg_trigger tg
236                            WHERE tg.tgrelid = t.oid AND (tg.tgtype::int & 81) = 81)
237            ) as updatable,
238            -- Updatable rather than a deletable bit, as `information_schema`
239            -- has it: a view PostgreSQL can write through automatically is
240            -- one it can delete through as well. Only the trigger half is
241            -- asked separately.
242            {delete} AND (
243                t.relkind <> 'v'
244                OR (pg_relation_is_updatable(t.oid, false) & 20) = 20
245                OR EXISTS (SELECT 1 FROM pg_trigger tg
246                            WHERE tg.tgrelid = t.oid AND (tg.tgtype::int & 73) = 73)
247            ) as deletable,
248            t.relkind = 'p' as is_partitioned
249        FROM (
250            -- A foreign table is a table: it has columns, it can be selected
251            -- from and written to, and which server stores the rows is not
252            -- the API's business. Leaving it out meant a schema that exposes
253            -- one answered "no such table".
254            --
255            -- A materialized view is a view that cannot be written to, which
256            -- is what the privilege tests report for it -- they cover only
257            -- the relation kinds `information_schema.table_privileges` does,
258            -- and this is not one of them.
259            SELECT c.oid, c.relkind, c.relispartition,
260                   n.nspname::text AS table_schema,
261                   c.relname::text AS table_name,
262                   CASE WHEN c.relkind IN ('v', 'm') THEN 'VIEW'
263                        WHEN c.relkind = 'f' THEN 'FOREIGN'
264                        ELSE 'BASE TABLE' END AS table_type,
265                   {visible} OR c.relkind = 'm' AS visible
266              FROM pg_class c
267              JOIN pg_namespace n ON n.oid = c.relnamespace
268             WHERE c.relkind IN ('r', 'v', 'f', 'p', 'm')
269               AND NOT pg_is_other_temp_schema(n.oid)
270               AND n.oid <> pg_my_temp_schema()
271        ) t
272        JOIN pg_class c ON c.oid = t.oid
273        WHERE t.table_schema = ANY($1)
274          AND t.visible
275          -- A partition is reached through the table it partitions, not on its
276          -- own. Listing every one of them gave a schema with a year of
277          -- monthly partitions twelve endpoints PostgREST does not have -- and
278          -- a request naming one was answered as though the table were real,
279          -- which made a missing relationship read as a missing column. The
280          -- partitioned parent itself (`relkind = 'p'`) is not a partition and
281          -- stays.
282          AND NOT t.relispartition
283        ORDER BY t.table_schema, t.table_name
284        "#,
285            insert = privilege_granted("INSERT"),
286            update = privilege_granted("UPDATE"),
287            delete = privilege_granted("DELETE"),
288            visible = relation_visible(),
289        )
290    });
291    let rows = catalog(tx, &SQL, &["table_schema", "table_name"], &[texts(schemas)]).await?;
292
293    for row in rows {
294        let schema: String = row.get("table_schema")?;
295        let name: String = row.get("table_name")?;
296        let qi = QualifiedIdentifier::new(&schema, &name);
297
298        let table_type: String = row.get("table_type")?;
299        let pk_cols: Vec<String> = row.get("pk_cols")?;
300
301        let table = Table {
302            schema: schema.clone(),
303            name: name.clone(),
304            description: row.get("description")?,
305            is_view: table_type == "VIEW",
306            is_partitioned: row.get("is_partitioned")?,
307            insertable: row.get("insertable")?,
308            updatable: row.get("updatable")?,
309            deletable: row.get("deletable")?,
310            pk_cols: pk_cols.clone(),
311            unique_constraints: Vec::new(),
312            columns: load_columns(tx, &schema, &name, &pk_cols).await?,
313            computed_columns: Default::default(),
314        };
315
316        tables.insert(qi, table);
317    }
318
319    Ok(tables)
320}
321
322/// Load columns for a table.
323async fn load_columns<T: Tx>(
324    tx: &mut T,
325    schema: &str,
326    table: &str,
327    pk_cols: &[String],
328) -> Result<ColumnMap> {
329    let mut columns = IndexMap::new();
330
331    // `information_schema.columns`, read from the catalogue: the view's own
332    // expressions for every column used here, so a type is named exactly as it
333    // was, and its visibility test with `MEMBER` for `USAGE` -- see
334    // `acl_grants` for why the view itself shows a NOINHERIT authenticator
335    // nothing. Built once, as it runs once per table.
336    static SQL: LazyLock<String> = LazyLock::new(|| {
337        format!(
338            r#"
339        SELECT
340            c.column_name,
341            c.ordinal_position,
342            c.is_nullable,
343            c.data_type,
344            c.udt_name,
345            -- A domain's own name. `information_schema` reports the type
346            -- underneath it in `data_type` and `udt_name`, so this is the only
347            -- column that says a value is a `color` rather than an integer --
348            -- and the domain is what a data representation is declared on.
349            c.domain_name,
350            c.character_maximum_length,
351            -- An identity column has no `column_default`: `information_schema`
352            -- describes it as generated rather than defaulted. What it would
353            -- take if a row left it out is the next value of the sequence the
354            -- column owns, which is the answer `Prefer: missing=default`
355            -- needs.
356            COALESCE(
357                c.column_default,
358                (SELECT format('nextval(%L)', s.oid::regclass)
359                   FROM pg_class rel
360                   JOIN pg_namespace ns ON ns.oid = rel.relnamespace
361                   JOIN pg_attribute att ON att.attrelid = rel.oid
362                                        AND att.attname = c.column_name
363                                        AND att.attidentity = 'd'
364                   JOIN pg_depend dep ON dep.refobjid = rel.oid
365                                     AND dep.refobjsubid = att.attnum
366                                     AND dep.deptype = 'i'
367                   JOIN pg_class s ON s.oid = dep.objid AND s.relkind = 'S'
368                  WHERE ns.nspname = c.table_schema
369                    AND rel.relname = c.table_name
370                  LIMIT 1)
371            ) AS column_default,
372            -- What a write may not name at all. `GENERATED ALWAYS AS
373            -- IDENTITY` and a stored generated column both belong to
374            -- PostgreSQL, which answers `cannot insert a non-DEFAULT value`
375            -- to anything that names one. `BY DEFAULT` is deliberately not
376            -- here: it has a default, and a value given for it is taken.
377            COALESCE(
378                (c.is_identity = 'YES' AND c.identity_generation = 'ALWAYS')
379                    OR c.is_generated = 'ALWAYS',
380                false
381            ) AS always_generated,
382            -- By OID: naming the table and casting to `regclass` needs USAGE
383            -- on its schema, which a NOINHERIT authenticator does not have.
384            pg_catalog.col_description(c.relid, c.ordinal_position) as description,
385            CASE WHEN e.enumtypid IS NOT NULL
386                 THEN array_agg(e.enumlabel ORDER BY e.enumsortorder)
387                 ELSE ARRAY[]::text[]
388            END as enum_values
389        FROM (
390            SELECT
391                c.oid AS relid,
392                nc.nspname::text AS table_schema,
393                c.relname::text AS table_name,
394                a.attname::text AS column_name,
395                a.attnum::int AS ordinal_position,
396                -- A column of a domain declared `DEFAULT v` has no pg_attrdef
397                -- row of its own; the default is the domain's
398                -- (`typdefaultbin`), as PostgREST reads it.
399                CASE WHEN t.typbasetype <> 0 AND ad.adbin IS NULL
400                          THEN pg_get_expr(t.typdefaultbin, 0)
401                     WHEN a.attgenerated = '' THEN pg_get_expr(ad.adbin, ad.adrelid)
402                END AS column_default,
403                CASE WHEN a.attnotnull OR (t.typtype = 'd' AND t.typnotnull)
404                     THEN 'NO' ELSE 'YES' END AS is_nullable,
405                CASE WHEN t.typtype = 'd' THEN
406                         CASE WHEN bt.typelem <> 0 AND bt.typlen = -1 THEN 'ARRAY'
407                              WHEN nbt.nspname = 'pg_catalog' THEN format_type(t.typbasetype, NULL)
408                              ELSE 'USER-DEFINED' END
409                     ELSE
410                         CASE WHEN t.typelem <> 0 AND t.typlen = -1 THEN 'ARRAY'
411                              WHEN nt.nspname = 'pg_catalog' THEN format_type(a.atttypid, NULL)
412                              ELSE 'USER-DEFINED' END
413                END AS data_type,
414                information_schema._pg_char_max_length(
415                    information_schema._pg_truetypid(a.*, t.*),
416                    information_schema._pg_truetypmod(a.*, t.*)
417                )::int AS character_maximum_length,
418                CASE WHEN t.typtype = 'd' THEN t.typname::text END AS domain_name,
419                COALESCE(bt.typname, t.typname)::text AS udt_name,
420                -- The same type by OID, for its enum labels: two schemas may
421                -- each have an enum of one name.
422                COALESCE(bt.oid, t.oid) AS udt_oid,
423                CASE WHEN a.attidentity IN ('a', 'd') THEN 'YES' ELSE 'NO' END AS is_identity,
424                CASE a.attidentity WHEN 'a' THEN 'ALWAYS' WHEN 'd' THEN 'BY DEFAULT' END
425                    AS identity_generation,
426                CASE WHEN a.attgenerated <> '' THEN 'ALWAYS' ELSE 'NEVER' END AS is_generated
427            FROM pg_attribute a
428            LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
429            JOIN pg_class c ON a.attrelid = c.oid
430            JOIN pg_namespace nc ON c.relnamespace = nc.oid
431            JOIN pg_type t ON a.atttypid = t.oid
432            JOIN pg_namespace nt ON t.typnamespace = nt.oid
433            LEFT JOIN (pg_type bt JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid)
434                   ON t.typtype = 'd' AND t.typbasetype = bt.oid
435            WHERE nc.nspname = $1 AND c.relname = $2
436              AND NOT pg_is_other_temp_schema(nc.oid)
437              AND a.attnum > 0 AND NOT a.attisdropped
438              AND c.relkind IN ('r', 'v', 'f', 'p')
439              AND (pg_has_role(c.relowner, 'MEMBER')
440                   OR {predefined}
441                   OR {table_grant}
442                   OR (a.attacl IS NOT NULL AND {column_grant}))
443        ) c
444        LEFT JOIN pg_enum e ON e.enumtypid = c.udt_oid
445        WHERE c.table_schema = $1 AND c.table_name = $2
446        GROUP BY c.relid, c.table_schema, c.table_name, c.column_name, c.ordinal_position, c.is_nullable,
447                 c.data_type, c.udt_name, c.domain_name, c.character_maximum_length,
448                 c.column_default, c.is_identity, c.identity_generation, c.is_generated,
449                 c.udt_oid, e.enumtypid
450        ORDER BY c.ordinal_position
451        "#,
452            predefined = PREDEFINED_DATA_ROLE,
453            table_grant = acl_grants(RELATION_ACL, "SELECT,INSERT,UPDATE,REFERENCES"),
454            column_grant = acl_grants("a.attacl", "SELECT,INSERT,UPDATE,REFERENCES"),
455        )
456    });
457    let rows = catalog(
458        tx,
459        &SQL,
460        &["ordinal_position"],
461        &[text(schema), text(table)],
462    )
463    .await?;
464
465    // A materialized view has no rows in `information_schema.columns`; its
466    // columns come from the catalogue instead.
467    let rows = match rows.is_empty() {
468        true => load_catalog_columns(tx, schema, table).await?,
469        false => rows,
470    };
471
472    for row in rows {
473        let name: String = row.get("column_name")?;
474        let is_nullable: String = row.get("is_nullable")?;
475        let data_type: String = row.get("data_type")?;
476        let udt_name: String = row.get("udt_name")?;
477        let max_len: Option<i32> = row.get("character_maximum_length")?;
478        let enum_values: Vec<String> = row.get("enum_values")?;
479        let position: i32 = row.get("ordinal_position")?;
480
481        let column = Column {
482            name: name.clone(),
483            description: row.get("description")?,
484            nullable: is_nullable == "YES",
485            data_type,
486            nominal_type: udt_name,
487            domain_type: row.get("domain_name")?,
488            max_len,
489            default: row.get("column_default")?,
490            enum_values,
491            is_pk: pk_cols.contains(&name),
492            position,
493            always_generated: row.get("always_generated")?,
494        };
495
496        columns.insert(name, column);
497    }
498
499    Ok(columns)
500}
501
502/// Load foreign key relationships.
503pub async fn load_relationships<T: Tx>(tx: &mut T, schemas: &[String]) -> Result<RelationshipsMap> {
504    let mut relationships: RelationshipsMap = HashMap::new();
505
506    let rows = catalog(
507        tx,
508        r#"
509        SELECT
510            c.conname as constraint_name,
511            ns1.nspname as table_schema,
512            t1.relname as table_name,
513            ns2.nspname as foreign_table_schema,
514            t2.relname as foreign_table_name,
515            -- Each key's columns are read in their own subquery, by ordinal
516            -- position. Joining pg_attribute twice in the outer query instead
517            -- would multiply the two keys together: a two-column foreign key
518            -- came back as four pairs, of which two paired a column with the
519            -- wrong one on the other side.
520            (SELECT array_agg(a.attname ORDER BY k.ord)
521               FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
522               JOIN pg_attribute a
523                 ON a.attrelid = c.conrelid AND a.attnum = k.attnum) as columns,
524            (SELECT array_agg(a.attname ORDER BY k.ord)
525               FROM unnest(c.confkey) WITH ORDINALITY AS k(attnum, ord)
526               JOIN pg_attribute a
527                 ON a.attrelid = c.confrelid AND a.attnum = k.attnum) as foreign_columns,
528            t1.relkind = 'v' as table_is_view,
529            t2.relkind = 'v' as foreign_table_is_view,
530            -- The key is unique when a unique index is *covered by* it, not
531            -- when the index merely contains it. Asked the other way round,
532            -- any key that is part of a wider unique index looked unique --
533            -- so a foreign key on two of a three-column primary key became a
534            -- one-to-one, and the far side embedded a single object where it
535            -- should have embedded an array.
536            EXISTS (
537                SELECT 1 FROM pg_index i
538                WHERE i.indrelid = c.conrelid
539                  AND i.indisunique
540                  AND c.conkey::int[] @> i.indkey::int[]
541            ) as is_unique
542        FROM pg_constraint c
543        JOIN pg_class t1 ON t1.oid = c.conrelid
544        JOIN pg_namespace ns1 ON ns1.oid = t1.relnamespace
545        JOIN pg_class t2 ON t2.oid = c.confrelid
546        JOIN pg_namespace ns2 ON ns2.oid = t2.relnamespace
547        WHERE c.contype = 'f'
548          -- A partition's foreign key is a copy of the parent's, inherited
549          -- (`conparentid` is the constraint it was cloned from). Only the
550          -- original counts, as in PostgREST's allM2OandO2ORels.
551          AND c.conparentid = 0
552          AND ns1.nspname = ANY($1)
553        -- Ordered, because the order reaches the client. Where two foreign
554        -- keys join the same pair of tables the embed is ambiguous, and the
555        -- PGRST201 that says so lists the candidates -- in this order, both in
556        -- `details` and in the `hint` that tells the caller what to write
557        -- instead. `pg_constraint` unordered is heap order, which differs
558        -- between two databases holding the same schema and can differ between
559        -- two reads of one database. That made the error message arbitrary and
560        -- the conformance cases covering it flip between runs.
561        ORDER BY ns1.nspname, t1.relname, c.conname
562        "#,
563        &["table_schema", "table_name", "constraint_name"],
564        &[texts(schemas)],
565    )
566    .await?;
567
568    for row in rows {
569        let table_schema: String = row.get("table_schema")?;
570        let table_name: String = row.get("table_name")?;
571        let foreign_schema: String = row.get("foreign_table_schema")?;
572        let foreign_name: String = row.get("foreign_table_name")?;
573        let constraint_name: String = row.get("constraint_name")?;
574        let columns: Vec<String> = row.get("columns")?;
575        let foreign_columns: Vec<String> = row.get("foreign_columns")?;
576        let table_is_view: bool = row.get("table_is_view")?;
577        let foreign_is_view: bool = row.get("foreign_table_is_view")?;
578        let is_unique: bool = row.get("is_unique")?;
579
580        let table_qi = QualifiedIdentifier::new(&table_schema, &table_name);
581        let foreign_qi = QualifiedIdentifier::new(&foreign_schema, &foreign_name);
582
583        let column_pairs: Vec<(String, String)> =
584            columns.into_iter().zip(foreign_columns).collect();
585
586        let is_self = table_qi == foreign_qi;
587
588        // M2O relationship (this table has FK to foreign table)
589        let cardinality = if is_unique {
590            Cardinality::O2O {
591                constraint: constraint_name.clone(),
592                columns: column_pairs.clone(),
593                is_parent: false,
594            }
595        } else {
596            Cardinality::M2O {
597                constraint: constraint_name.clone(),
598                columns: column_pairs.clone(),
599            }
600        };
601
602        let rel = Relationship::ForeignKey {
603            table: table_qi.clone(),
604            foreign_table: foreign_qi.clone(),
605            is_self,
606            cardinality,
607            table_is_view,
608            foreign_table_is_view: foreign_is_view,
609            constraint_name: constraint_name.clone(),
610        };
611
612        relationships
613            .entry((table_qi.clone(), table_schema.clone()))
614            .or_default()
615            .push(rel);
616
617        // O2M relationship (foreign table has many of this table)
618        let reverse_columns: Vec<(String, String)> = column_pairs
619            .iter()
620            .map(|(a, b)| (b.clone(), a.clone()))
621            .collect();
622
623        let reverse_cardinality = if is_unique {
624            Cardinality::O2O {
625                constraint: constraint_name.clone(),
626                columns: reverse_columns.clone(),
627                is_parent: true,
628            }
629        } else {
630            // Reversed, like the O2O case above: column pairs are always
631            // (local column, foreign column) relative to the table the
632            // relationship is stored under. For this direction the local table
633            // is the referenced one, so the pair must be swapped.
634            Cardinality::O2M {
635                constraint: constraint_name.clone(),
636                columns: reverse_columns,
637            }
638        };
639
640        let reverse_rel = Relationship::ForeignKey {
641            table: foreign_qi.clone(),
642            foreign_table: table_qi,
643            is_self,
644            cardinality: reverse_cardinality,
645            table_is_view: foreign_is_view,
646            foreign_table_is_view: table_is_view,
647            constraint_name,
648        };
649
650        relationships
651            .entry((foreign_qi, foreign_schema))
652            .or_default()
653            .push(reverse_rel);
654    }
655
656    load_computed_relationships(tx, schemas, &mut relationships).await?;
657
658    Ok(relationships)
659}
660
661/// Add relationships that are computed by a function rather than declared by a
662/// foreign key.
663///
664/// A function qualifies when it takes exactly one argument, that argument is
665/// the composite type of an exposed table, and it returns rows of an exposed
666/// table. `SETOF t` yields many rows per parent and a bare `t` yields one;
667/// `ROWS 1` on a set-returning function declares it yields one as well, which
668/// is how a to-one computed relationship is written.
669///
670/// The relationship is named after the function, not after the table it
671/// returns, so that two functions returning the same table stay distinct.
672async fn load_computed_relationships<T: Tx>(
673    tx: &mut T,
674    schemas: &[String],
675    relationships: &mut RelationshipsMap,
676) -> Result<()> {
677    let rows = catalog(
678        tx,
679        r#"
680        SELECT
681            pn.nspname  AS function_schema,
682            p.proname   AS function_name,
683            tn.nspname  AS table_schema,
684            t.relname   AS table_name,
685            fn.nspname  AS foreign_table_schema,
686            f.relname   AS foreign_table_name,
687            (NOT p.proretset) OR p.prorows = 1 AS to_one,
688            (SELECT p.proargnames[i]
689               FROM generate_series(1, p.pronargs) AS i
690              WHERE p.proargtypes[i - 1] = argt.oid
691              LIMIT 1) AS row_argument
692        FROM pg_proc p
693        JOIN pg_namespace pn ON pn.oid = p.pronamespace
694        -- one argument is a table's composite type. Usually the only one, and
695        -- then the call is positional; a function that also takes a search
696        -- term or the caller's session has it somewhere among the rest, and is
697        -- called by name.
698        JOIN pg_type argt ON argt.oid = ANY (p.proargtypes::oid[])
699        JOIN pg_class t   ON t.oid = argt.typrelid
700        JOIN pg_namespace tn ON tn.oid = t.relnamespace
701        -- and the return type is a table as well
702        JOIN pg_type rett ON rett.oid = p.prorettype
703        JOIN pg_class f   ON f.oid = rett.typrelid
704        JOIN pg_namespace fn ON fn.oid = f.relnamespace
705        -- Every argument named, since one that is not cannot be given by name
706        -- and a call with more than the row has to be.
707        WHERE (p.pronargs = 1 OR (SELECT count(*)
708                                    FROM generate_series(1, p.pronargs) AS i
709                                   WHERE COALESCE(p.proargnames[i], '') = '') = 0)
710          AND pn.nspname = ANY($1)
711          AND tn.nspname = ANY($1)
712          AND fn.nspname = ANY($1)
713          -- relkind 'c' would be a standalone composite type, not a relation
714          AND t.relkind = ANY (ARRAY['r','v','m','f','p'])
715          AND f.relkind = ANY (ARRAY['r','v','m','f','p'])
716        "#,
717        &[],
718        &[texts(schemas)],
719    )
720    .await?;
721
722    for row in rows {
723        let function = QualifiedIdentifier::new(
724            row.get::<String>("function_schema")?,
725            row.get::<String>("function_name")?,
726        );
727        let table_schema: String = row.get("table_schema")?;
728        let table = QualifiedIdentifier::new(&table_schema, row.get::<String>("table_name")?);
729        let foreign_table = QualifiedIdentifier::new(
730            row.get::<String>("foreign_table_schema")?,
731            row.get::<String>("foreign_table_name")?,
732        );
733        let is_self = table == foreign_table;
734
735        relationships
736            .entry((table.clone(), table_schema))
737            .or_default()
738            .push(Relationship::Computed {
739                function,
740                table: table.clone(),
741                foreign_table: foreign_table.clone(),
742                table_alias: table,
743                to_one: row.get("to_one")?,
744                is_self,
745                row_argument: row.get::<Option<String>>("row_argument")?,
746            });
747    }
748
749    Ok(())
750}
751
752/// Decode the `params` JSON built by [`load_routines`]'s query.
753///
754/// Anything malformed yields no parameters rather than an error: an argument
755/// whose type we don't know is bound untyped, which is how the server behaved
756/// before parameter types were loaded at all.
757fn parse_routine_params(value: serde_json::Value) -> Vec<RoutineParam> {
758    let Some(items) = value.as_array() else {
759        return Vec::new();
760    };
761
762    items
763        .iter()
764        .filter_map(|item| {
765            let param_type = item.get("type")?.as_str()?.to_string();
766            Some(RoutineParam {
767                name: item
768                    .get("name")
769                    .and_then(|n| n.as_str())
770                    .unwrap_or_default()
771                    .to_string(),
772                // A parameter declared `char(4)` is stored as bare
773                // `character`, whose length is 1, so casting an argument to
774                // the declared type truncates it. PostgreSQL does not enforce
775                // a length on a function parameter at all, so the unbounded
776                // spelling is the honest one to cast to.
777                type_max_length: item
778                    .get("cast_type")
779                    .and_then(|t| t.as_str())
780                    .unwrap_or(&param_type)
781                    .to_string(),
782                param_type,
783                required: item
784                    .get("required")
785                    .and_then(|r| r.as_bool())
786                    .unwrap_or(true),
787                variadic: item
788                    .get("variadic")
789                    .and_then(|v| v.as_bool())
790                    .unwrap_or(false),
791            })
792        })
793        .collect()
794}
795
796/// Load stored functions.
797pub async fn load_routines<T: Tx>(tx: &mut T, schemas: &[String]) -> Result<RoutineMap> {
798    let mut routines: RoutineMap = HashMap::new();
799
800    let rows = catalog(
801        tx,
802        r#"
803        -- What a type is once every domain over it is stripped away.
804        --
805        -- `RETURNS SETOF projects_domain` returns rows of `projects`, and a
806        -- domain is transparent to everything that matters here: whether the
807        -- result is composite, and which table's columns it has. Reading the
808        -- declared type alone finds a type name that names no table.
809        WITH RECURSIVE base_types AS (
810            SELECT oid, typbasetype, oid AS base_type FROM pg_catalog.pg_type
811            UNION
812            SELECT t.oid, b.typbasetype, b.oid AS base_type
813              FROM base_types t
814              JOIN pg_catalog.pg_type b ON b.oid = t.typbasetype
815        ),
816        resolved AS (
817            SELECT oid, base_type FROM base_types WHERE typbasetype = 0
818        )
819        SELECT
820            n.nspname as schema,
821            p.proname as name,
822            pg_catalog.obj_description(p.oid) as description,
823            p.provolatile::text as volatility,
824            p.provariadic <> 0 as has_variadic,
825            EXISTS (
826                SELECT 1 FROM unnest(COALESCE(p.proargmodes, '{}'::"char"[])) AS mode
827                 WHERE mode IN ('o', 't', 'b')
828            ) as has_out_params,
829            p.prokind = 'p' as is_procedure,
830            pg_get_function_identity_arguments(p.oid) as args,
831            -- Input parameters, in declaration order. Built from the catalog
832            -- rather than parsed out of the identity-arguments string, whose
833            -- types can themselves contain commas (`numeric(10,2)`).
834            -- `proargtypes` covers the IN parameters only and is 0-indexed;
835            -- `proargnames` is 1-indexed and lists IN names first, so the two
836            -- line up over 1..pronargs. A parameter is optional when it falls
837            -- inside the trailing run that has defaults.
838            COALESCE((
839                SELECT json_agg(
840                    json_build_object(
841                        'name', COALESCE(p.proargnames[i], ''),
842                        'type', pg_catalog.format_type(p.proargtypes[i - 1], NULL),
843                        -- What an argument is cast to. `character` and `bit`
844                        -- name themselves without a length, and casting to
845                        -- either truncates to one character; a parameter's
846                        -- length is not enforced anyway, so the varying
847                        -- spelling is what the value should reach.
848                        'cast_type', CASE p.proargtypes[i - 1]
849                            WHEN 'character'::regtype   THEN 'character varying'
850                            WHEN 'character[]'::regtype THEN 'character varying[]'
851                            WHEN 'bit'::regtype         THEN 'bit varying'
852                            WHEN 'bit[]'::regtype       THEN 'bit varying[]'
853                            ELSE pg_catalog.format_type(p.proargtypes[i - 1], NULL)
854                        END,
855                        'required', i <= (p.pronargs - p.pronargdefaults),
856                        'variadic', p.provariadic <> 0 AND i = p.pronargs
857                    ) ORDER BY i
858                )
859                FROM generate_series(1, p.pronargs) AS i
860            ), '[]'::json) as params,
861            -- The columns the function's rows have, where it names them:
862            -- `RETURNS TABLE(a text, b colour)` declares them as OUT
863            -- parameters, and they are the only account of the result's shape
864            -- -- there is no table to read it off. `proallargtypes` is a
865            -- plain 1-indexed array and lines up with `proargnames`.
866            COALESCE((
867                SELECT json_agg(
868                    json_build_object(
869                        'name', COALESCE(p.proargnames[i], ''),
870                        'type', pg_catalog.format_type(p.proallargtypes[i], NULL)
871                    ) ORDER BY i
872                )
873                FROM generate_series(
874                    1, COALESCE(array_length(p.proallargtypes, 1), 0)) AS i
875                WHERE p.proargmodes[i] IN ('o', 't', 'b')
876            ), '[]'::json) as out_params,
877            CASE
878                WHEN p.proretset THEN 'SETOF ' || pg_catalog.format_type(rt.base_type, NULL)
879                ELSE pg_catalog.format_type(rt.base_type, NULL)
880            END as return_type,
881            p.proretset as returns_set,
882            (SELECT t.typtype::text FROM pg_catalog.pg_type t WHERE t.oid = rt.base_type)
883                as ret_typtype,
884            -- A domain named after a media type says the value already is
885            -- that media type: `returns "image/png"` is a PNG, not a row to
886            -- serialise. Only a single value can be one, so a set-returning
887            -- function is not it.
888            (SELECT lower(dt.typname) FROM pg_catalog.pg_type dt
889              WHERE dt.oid = p.prorettype
890                AND dt.typbasetype <> 0
891                AND NOT p.proretset
892                AND (dt.typname ~ '^[A-Za-z0-9.-]+/[A-Za-z0-9.+-]+$'
893                     OR dt.typname = '*/*')) as media_type,
894            -- What that domain is a domain *over*. A value whose type this
895            -- side does not recognise arrives as PostgreSQL's text rendering
896            -- of it, and a `bytea` renders as `\x` and hex -- which is a
897            -- description of the bytes, not the bytes. Knowing the base type
898            -- is what tells the two apart.
899            (SELECT lower(bt.typname) FROM pg_catalog.pg_type dt
900               JOIN pg_catalog.pg_type bt ON bt.oid = dt.typbasetype
901              WHERE dt.oid = p.prorettype
902                AND NOT p.proretset
903                AND (dt.typname ~ '^[A-Za-z0-9.-]+/[A-Za-z0-9.+-]+$'
904                     OR dt.typname = '*/*')) as media_base_type
905        FROM pg_proc p
906        JOIN pg_namespace n ON n.oid = p.pronamespace
907        JOIN resolved rt ON rt.oid = p.prorettype
908        WHERE n.nspname = ANY($1)
909          AND p.prokind IN ('f', 'p')
910          -- A parameter with no name cannot be given an argument by name, so
911          -- a function that has one is not callable over the API at all --
912          -- and leaving it in the cache makes it a candidate that no request
913          -- can ever match, and a hint that sends the client nowhere.
914          --
915          -- The exception is the single unnamed parameter that takes the
916          -- whole request body, which is how a function is called with one
917          -- json, text, xml or bytea argument and no name for it.
918          AND (
919            (SELECT count(*) FROM generate_series(1, p.pronargs) AS i
920              WHERE COALESCE(p.proargnames[i], '') = '') = 0
921            OR (
922              p.pronargs = 1
923              AND COALESCE(p.proargnames[1], '') = ''
924              AND p.proargtypes[0] IN ('bytea'::regtype, 'json'::regtype,
925                                       'jsonb'::regtype, 'text'::regtype,
926                                       'xml'::regtype)
927            )
928          )
929        ORDER BY n.nspname, p.proname
930        "#,
931        &["schema", "name"],
932        &[texts(schemas)],
933    )
934    .await?;
935
936    for row in rows {
937        let schema: String = row.get("schema")?;
938        let name: String = row.get("name")?;
939        let qi = QualifiedIdentifier::new(&schema, &name);
940
941        let volatility: String = row.get("volatility")?;
942        let return_type_str: String = row.get("return_type")?;
943        let returns_set: bool = row.get("returns_set")?;
944
945        let return_type = if return_type_str == "void" {
946            RetType::Void
947        } else if returns_set {
948            RetType::SetOf(return_type_str.replace("SETOF ", ""))
949        } else {
950            RetType::Single(return_type_str)
951        };
952
953        // Composite ('c') and pseudo ('p', e.g. `record` from RETURNS TABLE)
954        // return types expand to their own columns in `SELECT * FROM fn()`;
955        // scalar returns yield a single column named after the function. Void
956        // is pseudo too but renders as a function-named null column, so it
957        // counts as non-composite.
958        let ret_typtype: Option<String> = row.get("ret_typtype")?;
959        // A named row type always expands. `record` expands only when the
960        // function declares its columns as `OUT` parameters or a `RETURNS
961        // TABLE` -- a bare `RETURNS record` has none, and PostgreSQL refuses
962        // to put one in a `FROM` clause without being told what they are.
963        let has_out_params: bool = row.get("has_out_params")?;
964        let returns_composite = !matches!(return_type, RetType::Void)
965            && (ret_typtype.as_deref() == Some("c")
966                || (ret_typtype.as_deref() == Some("p") && has_out_params));
967
968        let routine = Routine {
969            schema,
970            name,
971            description: row.get("description")?,
972            params: parse_routine_params(row.get("params")?),
973            return_type,
974            returns_composite,
975            volatility: FuncVolatility::from_char(volatility.chars().next().unwrap_or('v')),
976            has_variadic: row.get("has_variadic")?,
977            isolation_level: None,
978            settings: vec![],
979            is_procedure: row.get("is_procedure")?,
980            media_type: row.get("media_type")?,
981            media_base_type: row.get("media_base_type")?,
982            output_columns: parse_routine_params(row.get("out_params")?)
983                .into_iter()
984                .filter(|param| !param.name.is_empty())
985                .map(|param| (param.name, param.param_type))
986                .collect(),
987        };
988
989        routines.entry(qi).or_default().push(routine);
990    }
991
992    // Overloads of one name in a fixed order: fewest parameters first, then by
993    // the parameters themselves. Catalogue order is whatever the planner
994    // happened to return, and it decides which signature a client is offered
995    // first when a call cannot be told apart -- an answer that should not
996    // change between two servers reading the same schema.
997    for overloads in routines.values_mut() {
998        overloads.sort_by(|a, b| {
999            let key = |r: &Routine| {
1000                (
1001                    r.params.len(),
1002                    r.params
1003                        .iter()
1004                        .map(|p| (p.name.clone(), p.param_type.clone()))
1005                        .collect::<Vec<_>>(),
1006                )
1007            };
1008            key(a).cmp(&key(b))
1009        });
1010    }
1011
1012    Ok(routines)
1013}
1014
1015/// Load valid timezone names.
1016pub async fn load_timezones<T: Tx>(tx: &mut T) -> Result<HashSet<String>> {
1017    let rows = catalog(tx, "SELECT name FROM pg_timezone_names", &[], &[]).await?;
1018
1019    rows.iter().map(|r| r.get("name")).collect()
1020}
1021
1022/// Load user-defined renderers for media types.
1023///
1024/// A renderer is an aggregate whose state type is a domain named after a media
1025/// type. The domain is how the name survives -- `application/geo+json` is not
1026/// a legal identifier otherwise -- and the `/` in it is what makes an
1027/// ordinary-looking domain recognisable as one.
1028///
1029/// The aggregate's argument says what it renders: a table's composite type
1030/// renders that table, and `anyelement` renders anything in the schema.
1031pub async fn load_media_handlers<T: Tx>(tx: &mut T, schemas: &[String]) -> Result<MediaHandlerMap> {
1032    let rows = catalog(
1033        tx,
1034        r#"
1035        SELECT
1036            n.nspname    AS agg_schema,
1037            p.proname    AS agg_name,
1038            t.typname    AS media_type,
1039            bt.typname   AS media_base_type,
1040            argn.nspname AS arg_schema,
1041            argc.relname AS arg_table
1042        FROM pg_aggregate a
1043        JOIN pg_proc p       ON p.oid = a.aggfnoid
1044        JOIN pg_namespace n  ON n.oid = p.pronamespace
1045        JOIN pg_type t       ON t.oid = a.aggtranstype
1046        JOIN pg_type bt      ON bt.oid = t.typbasetype
1047        LEFT JOIN pg_type argt      ON argt.oid = p.proargtypes[0]
1048        LEFT JOIN pg_class argc     ON argc.oid = argt.typrelid
1049        LEFT JOIN pg_namespace argn ON argn.oid = argc.relnamespace
1050        WHERE n.nspname = ANY($1)
1051          AND t.typtype = 'd'
1052          AND t.typname LIKE '%/%'
1053        "#,
1054        &[],
1055        &[texts(schemas)],
1056    )
1057    .await?;
1058
1059    let mut handlers: MediaHandlerMap = HashMap::new();
1060    for row in rows {
1061        let agg_schema: String = row.get("agg_schema")?;
1062        let media_type: String = row.get("media_type")?;
1063        let table = match (
1064            row.get::<Option<String>>("arg_schema")?,
1065            row.get::<Option<String>>("arg_table")?,
1066        ) {
1067            (Some(schema), Some(name)) => Some(QualifiedIdentifier::new(schema, name)),
1068            _ => None,
1069        };
1070
1071        handlers
1072            .entry((agg_schema.clone(), media_type))
1073            .or_default()
1074            .push(MediaHandler {
1075                aggregate: QualifiedIdentifier::new(agg_schema, row.get::<String>("agg_name")?),
1076                table,
1077                base_type: row.get("media_base_type")?,
1078            });
1079    }
1080
1081    Ok(handlers)
1082}
1083
1084/// Which base-table column each of a view's columns comes from.
1085///
1086/// A view has no foreign keys of its own, but it can still be embedded: the
1087/// relationships of the tables it selects from apply to it, through whichever
1088/// of their columns it carries.
1089///
1090/// The mapping is made by name. PostgreSQL records which base columns a view
1091/// depends on, but not which of the view's own columns each one became -- that
1092/// lives in the parsed rule tree. Matching by name covers a view that selects
1093/// its columns through unchanged, and misses one that renames them, which is
1094/// Columns read straight from the catalogue, for a relation
1095/// `information_schema` does not describe.
1096///
1097/// The columns are shaped to match what the `information_schema` query
1098/// returns, so the caller cannot tell which of the two answered.
1099async fn load_catalog_columns<T: Tx>(
1100    tx: &mut T,
1101    schema: &str,
1102    table: &str,
1103) -> Result<Vec<CatalogRow>> {
1104    catalog(
1105        tx,
1106        r#"
1107        SELECT
1108            a.attname AS column_name,
1109            a.attnum::int AS ordinal_position,
1110            CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable,
1111            pg_catalog.format_type(a.atttypid, NULL) AS data_type,
1112            t.typname AS udt_name,
1113            CASE WHEN t.typtype = 'd' THEN t.typname END AS domain_name,
1114            NULL::int AS character_maximum_length,
1115            pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS column_default,
1116            (a.attidentity = 'a' OR a.attgenerated <> '') AS always_generated,
1117            pg_catalog.col_description(c.oid, a.attnum) AS description,
1118            COALESCE(
1119                (SELECT array_agg(e.enumlabel ORDER BY e.enumsortorder)
1120                   FROM pg_enum e WHERE e.enumtypid = t.oid),
1121                ARRAY[]::text[]
1122            ) AS enum_values
1123        FROM pg_class c
1124        JOIN pg_namespace n ON n.oid = c.relnamespace
1125        JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
1126        JOIN pg_type t ON t.oid = a.atttypid
1127        LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
1128        WHERE n.nspname = $1 AND c.relname = $2
1129        ORDER BY a.attnum
1130        "#,
1131        &["ordinal_position"],
1132        &[text(schema), text(table)],
1133    )
1134    .await
1135}
1136
1137/// Casts a schema declares between one of its domains and `json` or `text`.
1138///
1139/// PostgREST calls these data representations: a domain over `integer` with a
1140/// cast to `json` decides how a column of that domain is rendered, and a cast
1141/// back from `text` decides how a filter value written against it is read. It
1142/// lets a schema say that a colour is `"#01E240"` on the wire and an integer in
1143/// storage, with neither the client nor the table having to know about the
1144/// other.
1145///
1146/// Keyed by `(source type, target type)` so both directions come out of one
1147/// query: the render is `(domain, json)` and the parse is `(text, domain)`.
1148pub async fn load_representations<T: Tx>(
1149    tx: &mut T,
1150) -> Result<std::collections::HashMap<(String, String), String>> {
1151    // Whether a request may call the cast function: owned by, or executable
1152    // by, a role this connection can become. `has_function_privilege` asked
1153    // whether the connection could call it *as itself*, which a NOINHERIT
1154    // authenticator cannot once EXECUTE is revoked from PUBLIC -- and the
1155    // representation was dropped. See `acl_grants`.
1156    static SQL: LazyLock<String> = LazyLock::new(|| {
1157        format!(
1158            r#"
1159        SELECT c.castsource::regtype::text AS source,
1160               c.casttarget::regtype::text AS target,
1161               c.castfunc::regproc::text   AS function
1162          FROM pg_catalog.pg_cast c
1163          JOIN pg_catalog.pg_type src ON src.oid = c.castsource
1164          JOIN pg_catalog.pg_type dst ON dst.oid = c.casttarget
1165          JOIN pg_catalog.pg_proc p ON p.oid = c.castfunc
1166         WHERE c.castcontext = 'i'
1167           AND c.castmethod = 'f'
1168           AND (pg_has_role(p.proowner, 'MEMBER') OR {execute})
1169           AND ((src.typtype = 'd' AND c.casttarget IN ('json'::regtype, 'text'::regtype))
1170             OR (dst.typtype = 'd' AND c.castsource IN ('json'::regtype, 'text'::regtype)))
1171        "#,
1172            execute = acl_grants("COALESCE(p.proacl, acldefault('f', p.proowner))", "EXECUTE"),
1173        )
1174    });
1175    let rows = catalog(tx, &SQL, &[], &[]).await?;
1176
1177    rows.into_iter()
1178        .map(|row| {
1179            Ok((
1180                (row.get::<String>("source")?, row.get::<String>("target")?),
1181                row.get::<String>("function")?,
1182            ))
1183        })
1184        .collect()
1185}
1186
1187/// Functions of a table's row type, which read as though they were columns.
1188///
1189/// `create function always_true(items) returns boolean` makes
1190/// `?select=id,always_true` and `?always_true=is.true` work on `items`:
1191/// PostgreSQL resolves `items.always_true` to the function call, and PostgREST
1192/// exposes that. Only single-argument functions returning a single value
1193/// qualify -- one returning `setof` another table is a computed *relationship*,
1194/// which is embedded rather than selected.
1195/// `function_schemas` is where the function itself may live: the exposed
1196/// schemas plus whatever `db-extra-search-path` adds. The table has to be
1197/// exposed -- it is the thing being read -- but the function need not be, and
1198/// PostgREST resolves it along the search path. `always_false(test.items)`
1199/// lives in `public`, so requiring the function to be in an exposed schema
1200/// left `?always_false=is.false` answered "column does not exist" for a field
1201/// PostgREST reads as a column.
1202pub async fn load_computed_columns<T: Tx>(
1203    tx: &mut T,
1204    schemas: &[String],
1205    function_schemas: &[String],
1206) -> Result<Vec<ComputedColumnRow>> {
1207    // One argument is the table's row. The rest are the caller's, and are
1208    // exposed as the field's own arguments -- except the session document
1209    // Hasura fills in, `hasura_session json`, which a client never sends and
1210    // which is what lets a computed field know who is asking.
1211    //
1212    // Every argument has to be named: one that is not cannot be given by name,
1213    // and a call with more than the row has to be.
1214    let rows = catalog(
1215        tx,
1216        r#"
1217        SELECT tn.nspname AS table_schema,
1218               t.relname  AS table_name,
1219               fn.nspname AS function_schema,
1220               p.proname  AS function_name,
1221               pg_catalog.format_type(p.prorettype, null) AS return_type,
1222               pg_catalog.obj_description(p.oid, 'pg_proc') AS description,
1223               (SELECT p.proargnames[i]
1224                  FROM generate_series(1, p.pronargs) AS i
1225                 WHERE p.proargtypes[i - 1] = t.reltype
1226                 LIMIT 1) AS row_argument,
1227               (SELECT p.proargnames[i]
1228                  FROM generate_series(1, p.pronargs) AS i
1229                 WHERE p.proargnames[i] = 'hasura_session'
1230                 LIMIT 1) AS session_argument,
1231               p.pronargs > 1 AS takes_arguments
1232          FROM pg_proc p
1233          JOIN pg_namespace fn ON fn.oid = p.pronamespace
1234          JOIN pg_class t ON t.reltype = ANY (p.proargtypes::oid[])
1235          JOIN pg_namespace tn ON tn.oid = t.relnamespace
1236         WHERE (p.pronargs = 1 OR (SELECT count(*)
1237                                     FROM generate_series(1, p.pronargs) AS i
1238                                    WHERE COALESCE(p.proargnames[i], '') = '') = 0)
1239           AND NOT p.proretset
1240           AND p.prokind = 'f'
1241           AND p.prorettype <> 'pg_catalog.trigger'::pg_catalog.regtype
1242           AND t.relkind = ANY (ARRAY['r', 'v', 'm', 'p', 'f'])
1243           AND fn.nspname = ANY($2)
1244           AND tn.nspname = ANY($1)
1245        "#,
1246        &[],
1247        &[texts(schemas), texts(function_schemas)],
1248    )
1249    .await?;
1250
1251    rows.into_iter()
1252        .map(|row| -> Result<_> {
1253            Ok(ComputedColumnRow {
1254                table: QualifiedIdentifier::new(
1255                    row.get::<String>("table_schema")?,
1256                    row.get::<String>("table_name")?,
1257                ),
1258                name: row.get::<String>("function_name")?,
1259                function: QualifiedIdentifier::new(
1260                    row.get::<String>("function_schema")?,
1261                    row.get::<String>("function_name")?,
1262                ),
1263                return_type: row.get::<String>("return_type")?,
1264                description: row.get::<Option<String>>("description")?,
1265                row_argument: row.get::<Option<String>>("row_argument")?,
1266                session_argument: row.get::<Option<String>>("session_argument")?,
1267                takes_arguments: row.get::<bool>("takes_arguments")?,
1268            })
1269        })
1270        .collect()
1271}
1272
1273/// One function that reads as a column of a table.
1274#[derive(Clone, Debug)]
1275pub struct ComputedColumnRow {
1276    /// The table it belongs to.
1277    pub table: QualifiedIdentifier,
1278    /// The name it is read under, which is the function's.
1279    pub name: String,
1280    /// The function itself.
1281    pub function: QualifiedIdentifier,
1282    /// What it returns.
1283    pub return_type: String,
1284    /// The function's comment.
1285    pub description: Option<String>,
1286    /// The parameter that takes the row.
1287    pub row_argument: Option<String>,
1288    /// The parameter filled from the session, if any.
1289    pub session_argument: Option<String>,
1290    /// Whether it takes anything besides the row.
1291    pub takes_arguments: bool,
1292}
1293
1294/// One view column, and the base-table column it was selected from.
1295#[derive(Clone, Debug)]
1296pub struct ViewColumn {
1297    /// The view.
1298    pub view: QualifiedIdentifier,
1299    /// The table the column ultimately comes from.
1300    pub base: QualifiedIdentifier,
1301    /// The column's name on the base table.
1302    pub base_column: String,
1303    /// The name the view gives it.
1304    pub view_column: String,
1305    /// Where the view puts it (`attnum`), so that "the first view column"
1306    /// and "the first base table" mean the same as they do in the view.
1307    pub view_ordinal: i32,
1308}
1309
1310/// Which base-table column each view column came from.
1311///
1312/// A view may rename what it selects -- `select article_id as "articleId"` --
1313/// so matching by name gets the mapping wrong exactly where it matters, and a
1314/// view over another view has to be followed through. PostgreSQL records the
1315/// answer in the rewrite rule's target list, where every entry carries the
1316/// table and column it originated from, but only as a `pg_node_tree`, which
1317/// has no catalogue view and no parser exposed to SQL.
1318///
1319/// The shape below is PostgREST's: turn the node tree into JSON with a fixed
1320/// series of string replacements -- the fields wanted are quoted first so the
1321/// one regular expression can strip everything else -- read the target list
1322/// out of it, then follow view-on-view chains recursively, stopping on a cycle.
1323///
1324/// One base column may arrive under several names (`select t1_id as t1_id1,
1325/// t1_id as t1_id2`), so a single mapping is a row per name.
1326pub async fn load_view_columns<T: Tx>(tx: &mut T, schemas: &[String]) -> Result<Vec<ViewColumn>> {
1327    let rows = catalog(
1328        tx,
1329        r#"
1330        WITH RECURSIVE
1331        views AS (
1332            SELECT c.oid AS view_id, c.relnamespace AS view_schema_id,
1333                   n.nspname AS view_schema, c.relname AS view_name,
1334                   r.ev_action AS view_definition
1335              FROM pg_class c
1336              JOIN pg_namespace n ON n.oid = c.relnamespace
1337              JOIN pg_rewrite r ON r.ev_class = c.oid
1338             WHERE c.relkind IN ('v', 'm')
1339        ),
1340        transform_json AS (
1341            SELECT view_id, view_schema_id, view_schema, view_name,
1342                replace(
1343                replace(
1344                replace(
1345                replace(
1346                replace(
1347                replace(
1348                replace(
1349                regexp_replace(
1350                replace(
1351                replace(
1352                replace(
1353                replace(
1354                replace(
1355                replace(
1356                replace(
1357                replace(
1358                replace(
1359                replace(
1360                replace(
1361                    view_definition::text,
1362                    '<>', '()'
1363                ), ',', ''
1364                ), E'\\{', ''
1365                ), E'\\}', ''
1366                ), ' :targetList ', ',"targetList":'
1367                ), ' :resno ', ',"resno":'
1368                ), ' :resorigtbl ', ',"resorigtbl":'
1369                ), ' :resorigcol ', ',"resorigcol":'
1370                ), '{', '{ :'
1371                ), '((', '{(('
1372                ), '({', '{({'
1373                ), ' :[^}{,]+', ',"":', 'g'
1374                ), ',"":}', '}'
1375                ), ',"":,', ','
1376                ), '{(', '('
1377                ), '{,', '{'
1378                ), '(', '['
1379                ), ')', ']'
1380                ), ' ', ','
1381                )::json AS view_definition
1382              FROM views
1383        ),
1384        results AS (
1385            SELECT view_id, view_schema_id, view_schema, view_name,
1386                   (entry->>'resno')::int AS view_column,
1387                   (entry->>'resorigtbl')::oid AS resorigtbl,
1388                   (entry->>'resorigcol')::int AS resorigcol
1389              FROM (
1390                SELECT view_id, view_schema_id, view_schema, view_name,
1391                       json_array_elements(view_definition->0->'targetList') AS entry
1392                  FROM transform_json
1393              ) target_entries
1394        ),
1395        -- A view over a view is followed down to the base table. `path`
1396        -- carries the tables already visited so a cyclic definition stops
1397        -- rather than recursing forever.
1398        recursion(view_id, view_schema, view_name, view_column,
1399                  resorigtbl, resorigcol, is_cycle, path) AS (
1400            SELECT r.view_id, r.view_schema, r.view_name, r.view_column,
1401                   r.resorigtbl, r.resorigcol, false, ARRAY[r.resorigtbl]
1402              FROM results r
1403             WHERE r.view_schema = ANY($1)
1404            UNION ALL
1405            SELECT v.view_id, v.view_schema, v.view_name, v.view_column,
1406                   t.resorigtbl, t.resorigcol,
1407                   t.resorigtbl = ANY(v.path), v.path || t.resorigtbl
1408              FROM recursion v
1409              JOIN results t ON v.resorigtbl = t.view_id AND v.resorigcol = t.view_column
1410             WHERE NOT v.is_cycle
1411        )
1412        SELECT DISTINCT
1413               rec.view_schema, rec.view_name,
1414               sch.nspname AS base_schema, tbl.relname AS base_name,
1415               col.attname AS base_column, vcol.attname AS view_column,
1416               vcol.attnum::int AS view_ordinal
1417          FROM recursion rec
1418          JOIN pg_attribute vcol ON vcol.attrelid = rec.view_id
1419                                AND vcol.attnum = rec.view_column
1420                                AND NOT vcol.attisdropped
1421          JOIN pg_class tbl ON tbl.oid = rec.resorigtbl
1422          JOIN pg_namespace sch ON sch.oid = tbl.relnamespace
1423          JOIN pg_attribute col ON col.attrelid = tbl.oid
1424                               AND col.attnum = rec.resorigcol
1425                               AND NOT col.attisdropped
1426         WHERE rec.resorigtbl <> 0
1427        "#,
1428        &[],
1429        &[texts(schemas)],
1430    )
1431    .await?;
1432
1433    rows.into_iter()
1434        .map(|row| -> Result<_> {
1435            Ok(ViewColumn {
1436                view: QualifiedIdentifier::new(
1437                    row.get::<String>("view_schema")?,
1438                    row.get::<String>("view_name")?,
1439                ),
1440                base: QualifiedIdentifier::new(
1441                    row.get::<String>("base_schema")?,
1442                    row.get::<String>("base_name")?,
1443                ),
1444                base_column: row.get::<String>("base_column")?,
1445                view_column: row.get::<String>("view_column")?,
1446                view_ordinal: row.get::<i32>("view_ordinal")?,
1447            })
1448        })
1449        .collect()
1450}
1451
1452/// Primary key columns for every table in the given schemas.
1453///
1454/// Junction detection needs the key of the table doing the joining, and that
1455/// table may sit in a schema which is not exposed -- the junction behind two
1456/// public views. Loading the key alone keeps it out of the API surface while
1457/// still letting the relationship be derived.
1458/// Every unique constraint, by the table it belongs to.
1459///
1460/// Returned as `(constraint name, columns)`. The primary key is one of them:
1461/// PostgreSQL treats it as a unique constraint and `ON CONFLICT ON CONSTRAINT`
1462/// accepts it, which is what an upsert on a table's key needs.
1463///
1464/// Only constraints, not bare unique indexes. `ON CONFLICT ON CONSTRAINT`
1465/// takes a constraint name, and a unique index created without one has no name
1466/// to give it.
1467pub async fn load_unique_constraints<T: Tx>(
1468    tx: &mut T,
1469    schemas: &[String],
1470) -> Result<HashMap<QualifiedIdentifier, Vec<(String, Vec<String>)>>> {
1471    let rows = catalog(
1472        tx,
1473        r#"
1474        SELECT
1475            n.nspname AS table_schema,
1476            c.relname AS table_name,
1477            con.conname AS constraint_name,
1478            (SELECT array_agg(a.attname ORDER BY k.ord)
1479               FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum, ord)
1480               JOIN pg_attribute a
1481                 ON a.attrelid = c.oid AND a.attnum = k.attnum) AS columns
1482        FROM pg_constraint con
1483        JOIN pg_class c     ON c.oid = con.conrelid
1484        JOIN pg_namespace n ON n.oid = c.relnamespace
1485        WHERE con.contype IN ('p', 'u')
1486          AND n.nspname = ANY($1)
1487        "#,
1488        &[],
1489        &[texts(schemas)],
1490    )
1491    .await?;
1492
1493    let mut by_table: HashMap<QualifiedIdentifier, Vec<(String, Vec<String>)>> = HashMap::new();
1494    for row in rows {
1495        let Some(columns): Option<Vec<String>> = row.get("columns")? else {
1496            continue;
1497        };
1498        by_table
1499            .entry(QualifiedIdentifier::new(
1500                row.get::<String>("table_schema")?,
1501                row.get::<String>("table_name")?,
1502            ))
1503            .or_default()
1504            .push((row.get::<String>("constraint_name")?, columns));
1505    }
1506    for constraints in by_table.values_mut() {
1507        constraints.sort();
1508    }
1509    Ok(by_table)
1510}
1511
1512pub async fn load_primary_keys<T: Tx>(
1513    tx: &mut T,
1514    schemas: &[String],
1515) -> Result<HashMap<QualifiedIdentifier, Vec<String>>> {
1516    let rows = catalog(
1517        tx,
1518        r#"
1519        SELECT
1520            n.nspname AS table_schema,
1521            c.relname AS table_name,
1522            (SELECT array_agg(a.attname ORDER BY k.ord)
1523               FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
1524               JOIN pg_attribute a
1525                 ON a.attrelid = c.oid AND a.attnum = k.attnum) AS pk_cols
1526        FROM pg_index i
1527        JOIN pg_class c      ON c.oid = i.indrelid
1528        JOIN pg_namespace n  ON n.oid = c.relnamespace
1529        WHERE i.indisprimary
1530          AND n.nspname = ANY($1)
1531        "#,
1532        &[],
1533        &[texts(schemas)],
1534    )
1535    .await?;
1536
1537    let mut keys = HashMap::new();
1538    for row in rows {
1539        let Some(columns): Option<Vec<String>> = row.get("pk_cols")? else {
1540            continue;
1541        };
1542        keys.insert(
1543            QualifiedIdentifier::new(
1544                row.get::<String>("table_schema")?,
1545                row.get::<String>("table_name")?,
1546            ),
1547            columns,
1548        );
1549    }
1550    Ok(keys)
1551}
1552
1553/// The members of an enum table: its key column, and its `comment` column
1554/// when it has one, ordered by key.
1555///
1556/// Read as a role that may read the table. The connection reads it as itself
1557/// when it can, which a superuser or an inheriting authenticator always
1558/// could; a NOINHERIT authenticator can read nothing as itself, so it becomes
1559/// the first role it can become that holds SELECT on the table, inside a
1560/// transaction that is then rolled back.
1561#[cfg(feature = "sqlx")]
1562pub async fn enum_values(
1563    pool: &sqlx::PgPool,
1564    schema: &str,
1565    table: &str,
1566    key_column: &str,
1567    has_comment: bool,
1568) -> Result<Vec<(String, Option<String>)>> {
1569    let failed = |e: sqlx::Error| Error::SchemaCacheLoadFailed(e.to_string());
1570    let mut tx = pool.begin().await.map_err(failed)?;
1571
1572    let reader: Option<String> = sqlx::query_scalar(
1573        r#"
1574        SELECT r.rolname::text
1575          FROM pg_class c
1576          JOIN pg_namespace n ON n.oid = c.relnamespace
1577          JOIN pg_roles r ON pg_has_role(r.oid, 'MEMBER')
1578         WHERE n.nspname = $1 AND c.relname = $2
1579           AND has_schema_privilege(r.oid, n.oid, 'USAGE')
1580           AND has_table_privilege(r.oid, c.oid, 'SELECT')
1581         ORDER BY r.rolname = current_user DESC, r.rolname
1582         LIMIT 1
1583        "#,
1584    )
1585    .bind(schema)
1586    .bind(table)
1587    .fetch_optional(&mut *tx)
1588    .await
1589    .map_err(failed)?;
1590    let current: String = sqlx::query_scalar("SELECT current_user::text")
1591        .fetch_one(&mut *tx)
1592        .await
1593        .map_err(failed)?;
1594    // No role can read it: read as the connection anyway, so the error says
1595    // what PostgreSQL says rather than something invented here.
1596    if let Some(reader) = reader.filter(|reader| *reader != current) {
1597        sqlx::query(sqlx::AssertSqlSafe(format!(
1598            "SET LOCAL ROLE {}",
1599            postrust_sql::escape_ident(&reader)
1600        )))
1601        .execute(&mut *tx)
1602        .await
1603        .map_err(failed)?;
1604    }
1605
1606    let comment = match has_comment {
1607        true => format!("{}::text", postrust_sql::escape_ident("comment")),
1608        false => "NULL::text".to_string(),
1609    };
1610    let sql = format!(
1611        "SELECT {}::text, {} FROM {}.{} ORDER BY 1",
1612        postrust_sql::escape_ident(key_column),
1613        comment,
1614        postrust_sql::escape_ident(schema),
1615        postrust_sql::escape_ident(table)
1616    );
1617    let rows: Vec<(Option<String>, Option<String>)> = sqlx::query_as(sqlx::AssertSqlSafe(sql))
1618        .fetch_all(&mut *tx)
1619        .await
1620        .map_err(failed)?;
1621    tx.rollback().await.map_err(failed)?;
1622
1623    Ok(rows
1624        .into_iter()
1625        .filter_map(|(value, comment)| value.map(|v| (v, comment)))
1626        .collect())
1627}
1628
1629#[cfg(test)]
1630mod tests {
1631    use super::*;
1632    use serde_json::json;
1633
1634    fn row(value: serde_json::Value) -> CatalogRow {
1635        match value {
1636            serde_json::Value::Object(map) => CatalogRow(map),
1637            other => panic!("not an object: {other}"),
1638        }
1639    }
1640
1641    #[test]
1642    fn a_null_column_reads_as_none() {
1643        let row = row(json!({"description": null}));
1644        assert_eq!(row.get::<Option<String>>("description").unwrap(), None);
1645    }
1646
1647    #[test]
1648    fn a_column_the_query_does_not_have_fails_the_load() {
1649        // A misspelled name: read as null, it would quietly be `None`.
1650        let row = row(json!({"description": "a table"}));
1651        let error = row.get::<Option<String>>("descripton").unwrap_err();
1652        assert!(
1653            matches!(&error, Error::SchemaCacheLoadFailed(m) if m.contains("descripton")),
1654            "{error:?}"
1655        );
1656    }
1657
1658    #[test]
1659    fn a_value_of_the_wrong_type_fails_the_load() {
1660        let row = row(json!({"is_unique": "yes"}));
1661        assert!(matches!(
1662            row.get::<bool>("is_unique"),
1663            Err(Error::SchemaCacheLoadFailed(_))
1664        ));
1665    }
1666
1667    #[test]
1668    fn the_wrapper_sorts_by_the_order_it_is_given() {
1669        assert_eq!(
1670            catalog_sql("SELECT 1 AS a, 2 AS b ORDER BY a", &["a", "b"]),
1671            "SELECT row_to_json(pgrst_catalog) FROM (SELECT 1 AS a, 2 AS b ORDER BY a) \
1672             AS pgrst_catalog ORDER BY pgrst_catalog.a, pgrst_catalog.b"
1673        );
1674        assert_eq!(
1675            catalog_sql("SELECT 1 AS a", &[]),
1676            "SELECT row_to_json(pgrst_catalog) FROM (SELECT 1 AS a) AS pgrst_catalog"
1677        );
1678    }
1679}