Referencia · §8.11

System catalogs

ncatalog; modules/pg-compat

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

nucleus’s own catalog is nc_catalog: read-only views made from the catalog when scanned (D13), registered by the built-in module (§8.12).

Table Rows
nc_catalog.schemas name, description (the session registry’s schemas)
nc_catalog.tables table_id, name, columns, primary_key (names), has_row_id, indexes, checks, foreign_keys, referenced_by, key_prefix (hex), analyzed_rows, owner, row_security, force_row_security, comment, storage (§8.15), engine (btree or lsm, §4.6)
nc_catalog.storages name (the table storages registered, §8.15)
nc_catalog.text_analyzers name (the text analyzers registered, §8.19)
nc_catalog.partitions table_name, partition, strategy (range, list, hash), key (names), bound (FOR VALUES … or DEFAULT), storage (§8.16)
nc_catalog.segments table_name, segment (id, hex), rows, deleted, bytes (encoded) — each segment of each column table (§8.15)
nc_catalog.columns table_id, table_name, position, name, type, nullable, default_expr, in_primary_key, comment, generated (stored, embedding, or NULL), generation_expr, model, model_version, next_model (§8.24), number (the column’s number: given when it is added, kept through renames, type changes and other columns’ drops, never given again — gRPC’s field numbers, §M16.6b P2)
nc_catalog.indexes table_id, table_name, index_id (0 = primary), name, columns, is_unique, is_primary, key_prefix, orderings (per column, the taught ordering it is indexed in, or NULL), method (btree or a registered method’s, §8.17), opclasses (per column, its operator class, or NULL), options (name=value), is_ready (false while it is built online: writers keep it, queries do not use it)
nc_catalog.constraints table_id, table_name, name, kind, definition
nc_catalog.foreign_keys table_id, table_name, name, columns, referenced_table, referenced_columns, on_delete, on_update
nc_catalog.statistics table_id, table_name, column_name, rows, nulls, distinct_values, histogram
nc_catalog.statistics_objects table_id, table_name, name, columns — each CREATE STATISTICS
nc_catalog.column_groups table_id, table_name, columns, distinct_values — each set of columns ANALYZE counted together
nc_catalog.dependencies table_id, table_name, from_column, to_column, degree (0–1)
nc_catalog.orderings type, name, mapping, used_by (the indexes in it)
nc_catalog.operators symbol, left_type, right_type, function, source (distance: a type’s ability; registered: a module’s; taught)
nc_catalog.casts from_type, to_type, function, context
nc_catalog.enums type, label, position, sort_key (hex)
nc_catalog.roles name, superuser, login, inherit, createrole, connection_limit, has_password, valid_until
nc_catalog.role_members role, member, admin_option, condition (a WHEN condition, or NULL)
nc_catalog.access_rules position, name, roles, addresses, front_ends, auth_methods, tls, action, read_only, as_role (in order)
nc_catalog.audit seq, at, kind (login, ddl, statement), ok, code, session_user_name, user_name, client_addr, front_end, auth_method, tls, access_rule, detail (NULL once an erasure blanked it), hash, erasure (the one that blanked it) (an administrator’s; empty for others)
nc_catalog.audit_chain records, intact, broken_at, problem (the chain walked)
nc_catalog.erasures erasure, at, session_user_name, user_name, tables (text[], 'name: rows'), rows, scrubbed, found, audit_erased — each FORGET SUBJECT (an administrator’s all, a role’s own; §8.29)
nc_catalog.database_settings name, value, is_set, default, description (ALTER DATABASE nucleus SET …)
nc_catalog.statements user_name, query (constants as $n), calls, errors, total_ms, mean_ms, min_ms, max_ms, rows_read, rows_returned, model_calls, model_texts, model_cached, model_tokens, model_errors, model_ms, last_call (statement statistics, §8.13; an administrator sees all, others their own; the model columns §8.27)
nc_catalog.index_advice table_name, columns, create_statement, statements, calls, rows_read, rows_read_with_index, example_query, plan (the index advisor, §8.13)
nc_catalog.reads request_id, at, user_name, as_of (the commit read), tables, ids (returned), parameters, statement, erasure (the FORGET that blanked it) — the queries run under SET request_id (an administrator’s all, a role’s own; §8.28)
nc_catalog.migrations version, name, checksum, applied_at, applied_by — each migration applied (RECORD MIGRATION, nucleus migrate, §8.34)
nc_catalog.definitions position, kind, name, table_name, definition — every schema object as the statement that makes it, in an order that replays (§8.33)
nc_catalog.history retention (the retention by time; NULL without one), oldest_time, oldest_commit (how far back AS OF reaches: the oldest snapshot whose commit time is recorded), newest_commit — one row (§8.7, §M14.14)
nc_catalog.sessions id, user_name, session_user_name, client_addr, front_end, auth_method, tls, access_rule, read_only, as_role, roles (active at login), started (the sessions a front end admitted; an administrator sees all, others their own)
nc_catalog.policies table_name, name, permissive, command, roles, using, with_check
nc_catalog.tokens name, login, role, read_only, tables, valid_until, created, created_by, max_rows, max_scan, timeout, rate_per_minute (the tokens the current role may manage; never a secret)
nc_catalog.models name, owner, provider, dimensions, max_batch, secret, query_prefix, document_prefix, options, files, bytes, created, calls, texts, cached, errors, total_ms, tokens, throttled_ms, batch_tokens, requests_per_minute, tokens_per_minute, parallel (the models the current role may call; the calls since the process started, §8.23, §8.27)
nc_catalog.model_providers name, remote (whether its calls reach the network)
nc_catalog.sequences name, owner, data_type, start_value, min_value, max_value, increment_by, cycle, cache_size, last_value (the last handed out; NULL before one), owned_by (the sequences the current role may use, read or set)
nc_catalog.chunk_tables table_name, source, column_name, by, size, overlap, model (the chunk tables and what they chunk, §8.26)
nc_catalog.embedding_jobs table_name, column_name, model, kind (current, next), key, state (pending, retrying, failed), attempts, enqueued, next_attempt, error (the embedding columns’ queue, §8.24; the tables the current role may read)
nc_catalog.secrets name, owner, source (value, env), env, created, changed (the secrets the current role may use; never a value)
nc_catalog.grants kind, object, column, grantee, privilege, grantable (the ACLs written out)
nc_catalog.types name, aliases, category, module (which registered it), equality, hashing, ordering, key_encoding, distance (its operator), encoding_version

PostgreSQL compatibility: the pg-compat module (modules/pg-compat, nucleus_pg_compat::PgCompat, §8.12). Only sessions whose registry has it see any of what follows — the PostgreSQL front end’s (§9); ncp sessions and the embedded Session::new do not (principle 11). PostgreSQL clients hard-code PostgreSQL’s catalog names, so the same catalog is also shown as pg_catalog (pg_namespace, pg_class, pg_attribute, pg_attrdef, pg_type, pg_index, pg_constraint, pg_am, pg_collation, pg_roles, pg_database, pg_tablespace, pg_tables, pg_indexes, pg_statistic_ext (each CREATE STATISTICS, its columns by pg_get_statisticsobjdef_columns), pg_sequence, pg_sequences (last_value the last handed out), pg_depend (only a sequence’s on the column owning it: a, i for an identity’s), and empty pg_policy, pg_trigger, pg_inherits, pg_publication*, pg_description, pg_auth_members) and information_schema (schemata, tables, columns, table_constraints, key_column_usage, sequences), with the functions their queries call (format_type, pg_get_expr, pg_get_indexdef, pg_get_constraintdef, pg_get_userbyid, pg_table_is_visible, pg_partition_ancestors, has_*_privilege, obj_description, …) and ::regclass / regtype / regnamespace casts (regclass maps a name to an oid and an oid to a name). Unqualified pg_* names resolve to these unless a user table has the name. Oids: PostgreSQL’s for types, namespaces, access methods and the catalog tables clients compare with (pg_class 1259, pg_attribute, pg_type, pg_namespace, pg_constraint, pg_index, pg_description, pg_depend, pg_sequence); a table is 16384 + 1000 × table id, its indexes and constraints numbered after it; a sequence 1000000000 + its id, relkind S in pg_class (the module’s catalog.rs has the table). One role, nucleus. This is what makes psql’s \d, \d table, \d+, \dt, \di, \dv, \dn, \du, \l, \ds and \d sequence (its owner column too) work; \df and others that need functions or permissions do not. pg_typeof(x) and to_regtype(name) (a type’s oid by its pg_type or SQL name, NULL when there is none) are among its functions too. PostgreSQL’s text search — tsvector, tsquery, to_tsvector, to_tsquery, @@ — is the module’s too, served by the text index where it can be (§8.22).

Teaching a type an ordering (§M14.19): ALTER TYPE t ADD ORDERING name BY mapping — mapping is SQL over value (a t), into a type with an order, and must be immutable (no subqueries, parameters, or functions that are not Volatility::Immutable: 22023 otherwise). Values then sort as their mappings: ORDER BY x USING name [DESC] (in aggregates too), and an index can hold the mappings: CREATE INDEX [name] ON t (col USING name) (not UNIQUE: a mapping may have ties, which the primary key breaks; such an index is kept current by every write but is no access path for predicates on the column). ALTER TYPE t ALTER ORDERING name BY mapping redefines it and rebuilds the indexes in it; ALTER TYPE t DROP ORDERING [IF EXISTS] name is refused while an index uses it (2BP01, naming the index) unless CASCADE, which drops those indexes. A plain ORDER BY of a type without an order names the orderings taught to it. Collations are text orderings: x COLLATE name sorts and compares (=, <, …) in text ordering name — C, default, POSIX, ucs_basic are text’s own byte order, any other one taught (ALTER TYPE text ADD ORDERING ci BY lower(value)); the value itself is unchanged. Orderings live in the catalog (key 00 05), so teaching is transactional DDL; indexes record them per column (table record version 5). CREATE INDEX without a name makes one up (table_columns_idx; an expression’s part named by the function it calls, or expr).

Expression indexes (§M14.15 J4a): CREATE [UNIQUE] INDEX [name] ON t ((expr), col, lower(c), …) — a key part is a column, an expression in parentheses, or a function’s call; any type whose values keys encode (and compare, for UNIQUE), not JSON only (((doc->>'kind')), (((doc->>'age')::int)), ((JSON_VALUE(doc, '$.id' RETURNING int)))). The expression is kept as SQL text with its type and the columns it reads (catalog::IndexExpr, table record version 19); it must be immutable — no subquery, parameter, function that may vary, or conversion to or of a timestamptz (42P17) — and read a column. dml::IndexKeys binds it once per writer and computes each row’s key (as a taught ordering’s mapping is), so inserts, updates, deletes and builds keep it; a UNIQUE one refuses two rows with equal non-NULL values (23505). The optimizer binds it with the built-in functions (Stats::key_parts, once a statement) and matches a condition’s side to it structurally — lower(email) = $1, (doc->>'age')::int >= 30; the same function on another RETURNING type is another expression — so it is an access path like a column’s, costed by the statistics’ sample (which evaluates the condition on its rows). ALTER COLUMN … TYPE binds it again against the new type and rebuilds the index. An expression part is no uniqueness of its columns (the optimizer’s and foreign keys’ inferences ignore it), and an index method’s index takes columns only (0A000). nc_catalog.indexes.columns and pg-compat’s indexdef show (expr); pg_index.indkey holds 0 for it, as PostgreSQL’s.

Conditions a key range applies exactly (§M14.33 S17): of a scan through a secondary index, the filter’s conjuncts that bound a key part of an integer or boolean (or equal a text’s) by a value computed once are recorded on the path (Access::Key::exact). The rows the range reads pass them, so they are not checked again (Access::rest, which EXPLAIN shows as the filter) and no column is read for them; where a value at run time is NULL or would not convert exactly (exec::key_range_exact), all are checked on whole rows. A range below a bound only starts past the part’s NULL keys. An index scan that wants no column — count(*) over the range — reads the entries alone (exec::FromEntries; not a sealed table’s, whose destroyed rows its fetch tells): an entry is visible exactly when its row version is, so the count needs no visibility map.

Encoding versions (registered types): each stored value carries its type’s encoding version. A value in an older one is upgraded as it is read (Type::upgrade(from, bytes)), and writes use the current one, so old and new values live side by side; ALTER TYPE t UPGRADE rewrites every row and key holding t in one transaction. The catalog records the oldest version stored (00 08; nc_catalog.types.stored_version). An upgrade that changes the type’s keys (Type::upgrade_changes_keys) is done by the first transaction that may write, before anything reads those keys (a read-only statement before it gets 25006); a database storing a version newer than the build is refused (0A000). tests/upgrade.rs plays successive builds of one type, crashes UPGRADE at every I/O operation (all old or all new afterwards), and changes keys.

ALTER TABLE t ALTER [COLUMN] c [SET DATA] TYPE type [USING expr]: every value converted — by expr over the row, else by a taught cast of context ASSIGNMENT or IMPLICIT, else a built-in assignment cast (between numbers, between dates and timestamps, to text; anything else needs USING: 42804) — and stored as the column now says (lengths, precision), every row, key and index entry rewritten, checks, defaults, keys and uniqueness holding afterwards (22001, 23505, 23514). One transaction: readers keep the old column until it commits. A column a foreign key uses cannot change type yet. 22_alter_column_type.slt’s results came from PostgreSQL 18.

A type that keeps the values (validating, issue #18) rewrites no row: values are stored as what they are, not by the column’s type, so an integer and a bigint hold the same value, a varchar(n) a text. Without USING, on a column no index reads through anything but its values (an expression, a method, an ordering or operator class):

  • the same type changes nothing;
  • a wider one — smallint → integer → bigint, varchar(n) to a longer one or text, numeric(p, s) → numeric — changes the catalog alone, reading no row, so no write to the table makes it fail;
  • a narrower one — the other way — checks every value fits (22003, 22001) and the default too, then changes the catalog. In the statement’s transaction the rows are a premise of its commit, so a write committed meanwhile fails it (40001); a statement run alone then checks them online instead of again: one transaction records the new type as being validated (Table::validating), which every writer obeys from then on — its transaction reads the table’s record validated, so one begun before fails and runs again — then one read-only snapshot, taken after, holds every row written under the old type and is checked whole, and a last transaction gives the column its type. A value that does not fit abandons it: the record cleared, the statement failing with what was found. While a type is validated, the table’s other changes wait (55006); one cut short (a crash, its session gone) is taken over by the same statement run again, else abandoned by the server’s maintenance thread (validating::abandon_all) or a restore.

Any other change run alone whose rewrite in one transaction met a write is converted online instead (the CONCURRENTLY form below), when that form can take it. The design is PostgreSQL’s binary-coercible type changes (no rewrite) and its NOT VALID constraint with VALIDATE CONSTRAINT made one statement, and F1’s online schema change (Rae et al., VLDB 2013: a state writers obey before the data is known to).

Online: ALTER TABLE t ALTER COLUMN c TYPE type [USING expr] CONCURRENTLY (retype, §M14.18 O5) converts the same way while other sessions read and write the table — in transactions of its own, a part at a time; not inside a transaction block (25001); it returns when done. The table’s record holds the conversion (catalog::Conversion), and each switch of phase is a small transaction rewriting it, which a write begun under the old phase meets as 40001 (the write’s own retry runs it under the new one):

  • Backfill. The converted value is kept as a hidden last value of each row — the row stores the table’s columns and one more, which readers do not decode — and the indexes on the column are made again over it as shadow indexes with ids of their own. Writers compute it for every row they write (retype::Shadow, bound once per statement in dml::Writer): a value that does not convert, a NULL under NOT NULL, a check broken under the new type or a shadow unique index’s duplicate fails their statement (22…, 23502, 23514, 23505). An updated or deleted row’s shadow entries are found from the hidden value it has stored. The rows without one are given theirs a part at a time in key order; a part that conflicts with writers runs again smaller (down to a row), one that commits lets the next grow back (to 512).
  • Cutover (one transaction): the column takes its new type, the shadow indexes take the old ones’ places and names, the checks and default are bound against the new type, the statistics go.
  • Rewrite. A row still holding a hidden value is read with it as the column’s — the row’s length says which, without a lookup (retype::read_some under large::read_some and the vectorized scan) — until it is rewritten, a part at a time; then the old indexes’ entries are removed a part at a time and the record cleared.

A backfill that finds a value that does not convert (or a duplicate, or a check broken) abandons the change: the shadows’ entries and the hidden values are removed, the table is as before, and the statement fails with what was found. While a change runs, other changes of the table’s definition wait (55006), and so does a second change of the same table (55006). A change cut short (a crash, the session gone) leaves a table that reads and writes correctly in its phase; running the statement again finishes it, and so does the server’s maintenance thread (retype::resume_all); a restore finishes a backed-up one, abandoning one caught before its cutover (its shadow indexes are not backed up). The conversion is computed by every writer in its own session, so it must be immutable: CONCURRENTLY refuses (0A000, pointing at the transactional form) a USING with a function that may vary, a subquery or a parameter, a change from or to timestamptz (it depends on the time zone), and — first cut — primary key columns, columns a foreign key or a chunk table uses or a generated column reads, generated and expiry columns, indexes on the column that are an expression’s, a method’s or in a taught ordering, tables not stored as rows alone, chunk tables and memory stores, and partitioned tables and partitions. crates/sql/tests/retype.rs converts a twin of a table through several types and compares it with the transactional form, converts while another session writes (inserts, deletes, updates of the column and of a value stored out of line), provokes each failure, and crashes a change at I/O points: the rows read the same, the integrity check holds (it knows the shadow indexes and the hidden values), and running it again or resuming it finishes it. tests/retype_bench.rs measures it (docs/benchmarks.md, “Changing a column’s type”).

Operators outside the grammar’s own. The lexer reads operators as PostgreSQL does — the longest run of +-*/<>=~!@#%^&|?, not into a comment, a run of more than one not ending in +or-unless it holds one of~!@#%^&|? — so a=-1 is = and -, a<->b one operator. Those the grammar does not know (<->, @>) all parse at one precedence, PostgreSQL’s for “any other operator” (that of ||), and the binder finds them by symbol and operand types: a type’s distance (its Distance ability’s operator: ORDER BY at <-> '(47.5,19.04)'), a module’s (Registry::add_operator), or one taught: ALTER TYPE t ADD OPERATOR symbol (left, right) [RETURNS type] AS function / DROP OPERATOR [IF EXISTS] symbol (left, right) (the grammar’s own operators cannot be taught: 22023). Casts taught: ALTER TYPE t ADD CAST TO target AS function [EXPLICIT | ASSIGNMENT | IMPLICIT] / DROP CAST [IF EXISTS] TO target, between types one of which is registered (the built-in casts are fixed); CAST(x AS target) and x::target then call the function, and ALTER COLUMN … TYPE without USING takes an ASSIGNMENT or IMPLICIT one. (INSERT and UPDATE do not apply taught casts unwritten yet.) Naming a type’s distances in SQL (ADD DISTANCE) comes with the nearest-neighbour indexes of §M14.12; today a type’s distance is its ability’s. crates/testkit/slt/21_orderings.slt and tests/types.rs (geopoint taught by_geohash) test it.