Referencia · §8.7

Writes, constraints and sessions

dml, session

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

Writes collect their rows first, then write (no Halloween problem). Constraint errors: 23502 NOT NULL, 22001 too long, 23514 CHECK (a NULL check passes), 23505 duplicate key, 23503 foreign key; 42804 wrong assignment type (assignment converts within numbers, within dates and timestamps, and from or to text). CREATE INDEX backfills (and refuses existing duplicates for UNIQUE).

ADD COLUMN (issue #18, step 4) reads no row when the rows stored before can take the new column’s value as theirs: with no default (a column that may be NULL: they read NULL), or a default the same for every row — immutable, of a type whose stored value is the value itself (booleans, numbers, text, char, bytea, dates and times) — without a CHECK or REFERENCES of its own. The default’s value, made once, is kept in the table’s record (Table::missing, by the column’s place in a stored row): a row stored with fewer values than the column’s place reads it there — in the row decoder (large::read_some), the vectorized one, and a column segment written before (column_store); a row written after holds its own; a later SET DEFAULT changes neither. No row read, no row is a premise of the commit: a write committed meanwhile under the old definition stored a row that reads the value as the others do, so no write to the table makes the change fail. Otherwise (a volatile default — random(), now(), a sequence —, a check, a foreign key, NOT NULL without a default) every row is rewritten, its default made for it (a volatile one’s values differ from row to row, as in PostgreSQL) and the row checked. The design is PostgreSQL 11’s fast ADD COLUMN (a non-volatile default kept as the attribute’s missing value).

DROP COLUMN (issue #18, steps 2b and 2c) of a table stored in rows, in columns or in both (not partitioned, a memory store or a chunk table, no column’s type being changed) reads and rewrites no row: the column leaves the definition, its place stays in the stored rows (Table::gone, the places ascending, record version 28). A row is stored with a value in every place — NULL in a dropped column’s, for a row written after (Table::to_stored) — and read by places, the dropped ones taken out (large::read_some, the vectorized decoder by each column’s place, Table::stored_at). A dropped column’s value stored out of line keeps its chunks until its row is rewritten or deleted (a delete reads the stored row for them); its indexes’ entries are removed after the drop commits, as DROP INDEX’s. No row read, none is a premise: a write committed meanwhile under the old definition stored a row in the old places, which read as the others. The places go when the rows are written again whole — a DROP COLUMN or a type change that rewrites them (Table::compact); the online type change (… CONCURRENTLY, the fallback of one meeting writes) is refused while rows keep a dropped column’s place, its transactional form compacting them. A column copy’s segments (column, row,column) hold each column by its place in a stored row too (column_store::place: the chunk’s key, the segment’s list of columns, its cache entries, its zone-map bounds), so a dropped column’s chunk stays in the segments written before, passed over, and goes when a merge writes them again; its delta store’s rows are rows. The design is PostgreSQL’s attisdropped (a dropped attribute stays in the tuples, as its documentation describes DROP COLUMN).

DDL over a table’s rows — an index built, an ADD COLUMN that rewrites them, a DROP COLUMN that does, ALTER COLUMN … TYPE, SET NOT NULL, ADD CONSTRAINT — makes the rows as its snapshot has them a premise of its commit (dml::rows_are_premise: the table’s whole key range validated, at any isolation level). A write the table’s validated definition does not stop — one that commits before the DDL, under the old definition — would otherwise keep no entries in a new index, break a new check, NOT NULL or foreign key, miss a new column’s default, or keep a dropped column; instead the DDL’s commit fails (40001), an autocommit DDL running again (up to ten times) and then seeing the write. On a table written without pause such a DDL can fail every time; the forms that work in parts of their own do not: an index built online (below), ALTER COLUMN … TYPE … CONCURRENTLY and storage conversions (§M14.20). A statement run alone falls back to one of them when its transaction met a write (issue #18): CREATE INDEX and ADD [CONSTRAINT name] UNIQUE (…) to an index built online, ALTER COLUMN … TYPE to a type checked online (below) or a conversion online, and SET NOT NULL and ADD [CONSTRAINT name] CHECK (…) to a constraint checked online.

Constraints checked online (validating, issue #18, step 3): one transaction records the constraint as being validated (Table::validating: NOT NULL of a column, or a check) — from then on every writer obeys it (23502, 23514; a check bound with the table’s own), its transaction reading the table’s record validated, so one begun before fails and runs again — then one read-only snapshot, taken after, holds every row written without obeying it and is checked whole (23502 “contains null values”, 23514 “is violated by some row”), and a last transaction makes the constraint the table’s. A row that breaks it abandons it: the record cleared, the statement failing with what was found. While one is validated the table’s other changes wait (55006); one cut short is taken over by the same statement run again (in its transaction or online), else abandoned by the maintenance thread or a restore. It is PostgreSQL’s ADD CONSTRAINT … NOT VALID followed by VALIDATE CONSTRAINT, made one statement that needs no lock, and F1’s write-only state for constraints.

Indexes built online (online_index, issue #18): CREATE [UNIQUE] INDEX CONCURRENTLY name ON t (…) — and a CREATE INDEX run alone whose build in one transaction failed over a write committed under it (it is built online then, instead of again) — builds the index while other sessions write the table, in transactions of its own; not inside a transaction block (25001); it returns when the index is ready. First the index joins the table’s indexes being built (Table::building, after the others in the table record): every writer — whose transaction reads the table’s record validated, so one begun before fails 40001 and runs again — keeps its entries as any index’s, a unique one refusing a duplicate it sees (23505), while queries and the planner do not see it (nc_catalog.indexes.is_ready is false). Then every row’s entry is written a part at a time in primary key order (retype::in_parts: a part that meets a writer runs again smaller): a part reads its rows validated, so it commits only if they stayed as it read them, and a row’s entry may be there already — its writer’s — or, in a unique index, another row’s: a duplicate, which fails the build. Last, one transaction moves the index among the table’s indexes. A row written after the first step has its entry from its writer, one written before from the part that read it. The one entry a writer may meet that is not its row’s is a unique index’s, of another row with the same value before the build finds the duplicate: so a writer removes a unique entry of an index being built only when it is its row’s, a look validated (dml::drop_entry; a build’s entry written after the writer’s snapshot fails it, where a removal would have met the build’s write). A failed build (a duplicate, the statement’s timeout or cancel) removes the index and its entries; DROP INDEX of one being built stops its build (55006). While an index is built, other changes of the table’s definition wait (55006). A build cut short by a crash leaves an index being built — written, not read; running the statement again finishes it, and so does the server’s maintenance thread (online_index::resume_all); a restore builds it with the table’s other indexes. Not built online (0A000 for CONCURRENTLY, the one transaction’s build for a fallback): an index method’s index, a partitioned table’s or a partition’s, a memory store’s, and a table whose column’s type or storage is being changed. The design is PostgreSQL’s CREATE INDEX CONCURRENTLY (an index first committed as kept by writers and not read, then filled, then made valid) and F1’s online schema change (Rae et al., VLDB 2013: a write-only state between absent and public); here no second pass over the rows written meanwhile is needed — each part’s rows are a premise of its commit — and no wait for older transactions — the validated table record turns them away. DROP INDEX (and DROP CONSTRAINT of a unique one) changes only the table record in its transaction: the index’s id joins the table’s dropped list (Table::dropped, record version 25), and its entries are removed after the drop commits, a part a transaction (online_index::clean_dropped: by the session after the statement or the block’s COMMIT, by the maintenance thread for a drop cut short); then the id leaves the list. Deleted in the drop’s own transaction, the entries met every concurrent writer of the index’s keys (40001). The integrity check and backups know the dropped ids; a restore leaves their entries out. crates/sql/tests/online_index.rs builds indexes on a twin table in one transaction and online, with writes between the parts, duplicates written or resolved meanwhile, other changes refused, a crash at thirty points, and writes that do not pause, on row, column and LSM tables.

Index builds (dml::IndexBuild, §M14.20 W2) — a new index’s entries, and every index’s when ALTER … TYPE or a key change rewrites a table’s rows — are gathered, sorted and written in key order. CREATE INDEX reads only the index’s columns, in up to 1024 parts of the table (split_points) scanned a round at a time on the statement’s workers, and computes only that index’s keys. The entries lie in one buffer — keys and primary keys side by side, no allocation per entry — with, per entry, its place and its key’s first sixteen bytes past the index’s prefix (which every entry shares) as a number, on which most comparisons end (PostgreSQL’s abbreviated keys, DuckDB’s normalized-key prefix). Up to work_mem (shared by the indexes built at once) they are sorted in memory by a sample sort: dealt into as many buckets as the statement has threads by ranges of those numbers (bounds from a sample), each bucket sorted on a thread of its own, the buckets in order with no merge after; past it each work_mem’s worth becomes one sorted run of byte records in scratch space (spill::Run::push_record; a large run’s records laid out on the workers, a few MiB each, written in order), and the runs are merged by a heap of run positions, the keys left where they are. A unique index’s duplicates are neighbours in that order — found without a look at the tree (23505). A large build (spilled, or 65,536 entries in memory, with workers) merges on a thread of its own, handing the writer 1 MiB blocks of entries while it writes the ones before. The writes go to the index’s fresh range in key order: into the store as they come, without the WAL (D16, §5.2), apply_sorted packing them into full pages — or, with --wal full, through the write set, which keeps them as appends.

Bulk load (copy, §M14.11). COPY t [(columns)] FROM STDIN loads rows the client sends, in one statement: PostgreSQL’s text format (fields split by a tab, \N for NULL, backslash escapes \t \n \\ \x41 \101 …, \. ending the data) or CSV (,, " quoting — newlines inside quotes are the field’s —, an unquoted empty field NULL, HEADER skipping the first line), parsed as the data arrives; or typed rows the front end decoded (ncp’s batches, §10). Each row is checked and stored as an INSERT’s: defaults for the columns not named, assignment from text, NOT NULL, lengths, CHECK, unique keys and indexes, row-level security, the INSERT privilege on the columns; foreign keys a chunk of 4096 rows at a time. A failing row fails the statement — nothing is stored — with the data’s line in the message (… (COPY data, line 3)); 22P04 for a record with too few or too many fields. It runs in the session’s transaction (or its own) and is never retried, its data having been read; a load larger than the transaction’s memory spills (§5.2), so its size is not bound by memory.

COPY and INSERT build their rows through one builder (dml::RowBuilder, §M14.20 W3): the target columns bound once, a text field parsed straight to its column’s type (Value::from_text — no string per field for numbers, dates and timestamps; anything else as a cast from text), the record’s fields in one buffer, and when the fields come in the table’s column order the row built as they are read; then the defaults, the checks and the policies. COPY collects up to 4 MiB of records and — when every default, check and policy is safe off the statement’s thread and the transaction can share its reads — parses and builds them in parts of 2048 on the statement’s workers (DuckDB’s parallel CSV reader, Instant Loading), a row table’s rows encoded there too (TableStorage::encode_new); the rows are stored in order on the statement’s thread, so a failure names the first failing line as a serial load would. Parsing and storing overlap (§M14.20 W3b): a parser thread parses on the workers, reading through the writer’s transaction behind a lock (nucleus_kv::Locked), while the statement’s thread stores what was parsed; the chunks waiting to be parsed are bounded (4), the parsed batches drained before each read. ncp’s binary batches (§10) are built into rows on the same parser thread.

Every insert — INSERT, COPY, an UPDATE moving rows between partitions — stores through one batch path (dml::insert_batch): rows handed over owned, routed to their partitions by bounds, their row ids reserved per batch (catalog::next_rowids), their index entries and foreign-key keys computed first, then handed to the storage (TableStorage::insert_batch; by default row by row). A foreign key’s keys are deduplicated by their encoding and checked once each. The first error in row order wins, and a statement failing on its own data skips the foreign-key checks, so a bad record is reported before a missing parent (PostgreSQL’s order). A column table (§8.15) takes an ascending batch into its gathered rows at once when nothing stored lies between its first and last key. A front end without a client to read from refuses it (0A000); Session::run_copy(stmt, params, reader) reads it from any Read. From a server-side file is not supported (the client sends files).

Upsert (INSERT … ON CONFLICT, PLAN.md §M15 D2; PostgreSQL’s statement and meaning). ON CONFLICT [(part, …) [WHERE predicate] | ON CONSTRAINT name] DO NOTHING | DO UPDATE SET col = expr, … [WHERE cond]. The arbiters are the unique keys the target names: the primary key or unique B-tree indexes whose parts are exactly those listed — columns or expressions, in any order (42P10 when none is; an expression matches an expression index’s bound the same way) —, the one key ON CONSTRAINT names (t_pkey or a unique index’s name; 42704 otherwise), or with no target every unique key (DO NOTHING only: DO UPDATE needs a target, 42601). nucleus has no partial indexes, so a target’s WHERE is accepted and any matching index serves (as PostgreSQL lets a non-partial index serve). INSERT INTO t AS a names the table in the clause and in RETURNING. The proposed rows are built first (defaults, generated columns, CHECKs and the insert policy’s check, as PostgreSQL checks them before looking for a conflict), then taken in order (dml::Upsert::run): each arbiter’s key of the row — the row key, or a unique index’s entry (none where a part is NULL: such a row conflicts with nothing) — looked up in the transaction; none taken: the row joins the batch being inserted (stored through insert_batch, 4,096 at a time); one taken: DO NOTHING leaves the row out (it looks only whether a key is taken, dml::taken: the row there is not read), DO UPDATE evaluates SET and WHERE over the row there and the proposed row as excluded (a column’s name alone is ambiguous, 42702, as PostgreSQL’s), the result checked as an UPDATE‘s (CHECKs, unique keys, foreign keys, the update policy’s WITH CHECK) and written by the UPDATE path — the batch inserted so far stored first, so the update’s checks see it. The keys of every row the statement inserted or updated are kept: a later row taking one is left out by DO NOTHING and refused by DO UPDATE (21000, “cannot affect row a second time”: the outcome would depend on the rows’ order). RETURNING gives the rows inserted and updated, in order; the count is theirs. Privileges: INSERT on the columns inserted, and for DO UPDATE UPDATE on the columns set and SELECT on those read; row-level security: the row there must pass the update policy’s USING (42501 otherwise, not skipped — PostgreSQL’s rule). A partitioned table’s rows go to their partitions, an arbiter index found in each by its parts (its name there is name_partition). Concurrent upserts of one key: the second writer either finds the first’s row in its snapshot or does not; if not, its insert’s key — row key or unique entry — is written by both and the second to commit gets 40001, never 23505: outside a block the statement runs again (up to 10 times, §8.7’s sessions) and then updates the row; inside a block the client runs the transaction again, as with PostgreSQL’s REPEATABLE READ. (tests/upsert.rs races four writers on twelve keys, in every storage and isolation level, and counts every update.)

COPY t [(columns)] | (query) TO STDOUT [options] (copy::copy_to) runs the query (SELECT columns FROM t for a table) and writes each row as a line in PostgreSQL’s text format (a backslash before itself and the delimiter, control characters escaped, \N for NULL) or CSV (a field quoted when it holds the delimiter, the quote or an end of line, reads as the NULL string, or is \. alone), HEADER naming the columns first; the same options as FROM. The lines go to the front end through Sink::copy_out / copy_line: pg-compat sends them as PostgreSQL’s CopyOutResponse, CopyData and CopyDone (psql’s \copy … to, drivers’ copy-out); any other front end gets them, by default, as rows of one text column, copy. To a server-side file: 0A000.

Sequences (issue #23). CREATE SEQUENCE [IF NOT EXISTS] name [AS smallint | integer | bigint] [INCREMENT [BY] n] [MINVALUE n | NO MINVALUE] [MAXVALUE n | NO MAXVALUE] [START [WITH] n] [CACHE n] [[NO] CYCLE] [OWNED BY t.c | NONE], ALTER SEQUENCE [IF EXISTS] name options | RESTART [[WITH] n] | RENAME TO new, DROP SEQUENCE [IF EXISTS] name, … [CASCADE]; nextval(name), currval(name), setval(name, n [, is_called]), lastval() — PostgreSQL’s defaults, checks and messages (22023 for a bad option, 2200H past a bound without CYCLE, 22003 for setval out of bounds, 55000 for currval / lastval before a nextval in the session, 25006 in a transaction read-only as declared; the name read as regclass reads it). A sequence shares the tables’ names (42P07). Privileges: USAGE or UPDATE for nextval, SELECT or USAGE for currval, UPDATE for setval (GRANT … ON SEQUENCE); the maker owns it. DROP SEQUENCE refuses while a default calls it (2BP01), CASCADE drops those defaults; RENAME rewrites them. DDL never spends a value: a volatile default is bound, not evaluated, when a table is made or a column’s type or default changes, and a column added with one gets each row’s own value. The definition is the catalog’s, transactional; the value is not, as PostgreSQL’s — a value is handed out once whatever becomes of its transaction, and takers never wait on one another. It lives in memory, shared by the database’s sessions, exact (ALTER makes no gap): what the store holds is a reservation, a value no smaller in the sequence’s direction than any handed out, written by a transaction of its own before a value past the last one is handed out — 32 values at first, doubling while reservations come within a second, up to 4,096 (PostgreSQL logs 32 values ahead, SEQ_LOG_VALS). After a crash or a restart a sequence goes on past its reservation: values may be skipped, never repeated. setval and RESTART act at once, not with the transaction (PostgreSQL’s RESTART is transactional). A sequence’s id comes from a counter advanced by a transaction of its own, so two made at once never share one. The definition and the privilege decision are read through the session’s catalog cache, the state kept by the session: SELECT count(nextval('s')) FROM generate_series(1, 1000000) 281 ms (PostgreSQL 18: 194 ms), an INSERT of 200,000 rows keyed by one 141 ms (PostgreSQL 18: 229 ms).

serial and identity columns (issue #23). serial / serial4, bigserial / serial8, smallserial / serial2 are integer, bigint, smallint NOT NULL DEFAULT nextval('t_c_seq'), the sequence (of the column’s type) made with the table and owned by the column. GENERATED ALWAYS | BY DEFAULT AS IDENTITY [(SEQUENCE NAME s, sequence options)] is the same, the column NOT NULL, of smallint, integer or bigint (22023 otherwise), the column marked: an ALWAYS one takes no value given — an INSERT’s (but DEFAULT) or an UPDATE’s or upsert’s SET (but = DEFAULT) is 428C9 — unless INSERT … OVERRIDING SYSTEM VALUE; OVERRIDING USER VALUE ignores the values given for identity columns of either kind. COPY takes the values given, as PostgreSQL’s. An identity column’s default is its sequence’s (SET / DROP DEFAULT: 42601), and its sequence is not dropped alone (2BP01, CASCADE or not). A sequence’s name is table_column_seq, with 1, 2, … after it when that is taken (PostgreSQL’s). A sequence owned by a column (OWNED BY, serial, identity) goes with the column or its table — 2BP01 if another table’s default calls it, that default dropped with CASCADE — and follows their renames; TRUNCATE … RESTART IDENTITY restarts it. pg_get_serial_sequence(table, column) names it (public.s). The definitions write an identity column GENERATED … AS IDENTITY (SEQUENCE NAME s options), a sequence another column owns ALTER SEQUENCE s OWNED BY t.c after the tables; pg-compat shows pg_attribute.attidentity (a, d) and information_schema.columns .is_identity. The table record (version 30 on) keeps each column’s identity after the rest: 0, 1 <sequence> (ALWAYS) or 2 <sequence>. ALTER TABLE t ALTER [COLUMN] c ADD GENERATED ALWAYS | BY DEFAULT AS IDENTITY [(options)] makes a column one (NOT NULL already, without a default: 55000 otherwise, 22023 not an integer); SET GENERATED ALWAYS | BY DEFAULT, SET option and RESTART [[WITH] n] (in any number, one after another) change it and its sequence; DROP IDENTITY [IF EXISTS] makes it a plain column (NOT NULL kept), its sequence dropped — 55000 on a column that is not one. Not on a partitioned table or a partition yet (0A000).

Sessions: outside BEGIN every statement is its own transaction, retried up to 10 times on 40001 (with the KV contract’s back_off); inside, the KV transaction starts with the first statement (so SET TRANSACTION may follow BEGIN), an error moves the block to failed (25P02 until ROLLBACK; COMMIT then rolls back). Savepoints as PostgreSQL’s: SAVEPOINT name, ROLLBACK [WORK | TRANSACTION] TO [SAVEPOINT] name (the writes after it taken back, the savepoints inside it gone, the block no longer failed), RELEASE [SAVEPOINT] name (it and those inside it gone, their writes kept); a name used twice means the newest; outside a block 25P01, an unknown name 3B001 (the block failed). The block’s savepoints before its first statement are set on its transaction when it begins. What a statement read stays read: a serializable block validates it at COMMIT still. REPEATABLE READ, READ COMMITTED and READ UNCOMMITTED all run as snapshot isolation; SERIALIZABLE as §5.2. SET default_transaction_isolation; SHOW transaction_isolation | server_version | ….

At a past time (§M14.14 TT2). BEGIN [READ ONLY] AS OF TIMESTAMP expr (also AS OF SYSTEM TIME, CockroachDB’s words), AS OF COMMIT n, or SET TRANSACTION AS OF … before the block’s first statement: the block’s transaction reads the snapshot of the last commit at or before that time (Kv::snapshot_at, §5.2) — read-only (25006 on a write). SET read_as_of = '2026-11-13 10:00:00+00' (or 'commit n'; RESET ends it) puts every following statement and block of the session there. The expression is evaluated when the transaction begins, in a transaction of its own (now() - interval '1 hour' works; a parameter does not); a time in the future, NULL or a commit not positive is 22023; one before the retention by time (§5.2; the server’s --history, §9; how far back: nc_catalog.history), or with none set, 72000 (snapshot too old). The statement binds against the catalog as it was then — the session’s catalog cache serves only snapshots that read the catalog as it was filled (watched_as_at) — so a table since altered reads in its old shape and a dropped one is there; index methods answer from their stored state at that snapshot (the text index and HNSW, tests/time_travel.rs).

A table at a past time (§M14.14 TT3). FROM t AS OF TIMESTAMP expr (or AS OF SYSTEM TIME, AS OF COMMIT n, SQL:2011’s FOR SYSTEM_TIME AS OF expr; before the alias) reads one table at its own snapshot, beside the present in the same statement: SELECT … FROM t AS OF … JOIN t … compares, INSERT INTO t SELECT … FROM t AS OF … or CREATE TABLE t2 AS SELECT * FROM t AS OF … restores. The binder evaluates the expression (time_travel::snapshot, as for a block), begins a read-only transaction there, and binds the table against that snapshot’s catalog — its past shape, a table dropped since included — in a sub-binder of its own (checked as the outer one is); the plan is Plan::Past { at, plan }, which the executor runs in a transaction of its own at at and materializes, as a CTE’s rows (EXPLAIN shows As Of commit n) — the whole table: the statement’s filters and its indexes do not reach into it yet, so an indexed lookup at a past time is a block’s AS OF. Privileges are the present’s: a table that still exists needs SELECT now; one dropped since is readable only to whom the past catalog’s grants allowed. A CTE’s name with AS OF is 0A000. WITH is a reserved word (as in PostgreSQL), so it ends a table’s alias.