Constraints, sequences and identity columns

This page describes, from the SQL side, which constraints SynergyDB enforces, when it checks them, the errors it raises, and how column defaults, SERIAL columns, identity columns and sequences produce values. Storage layout of the sequence counters is covered in Sequences (internals). The clauses that CREATE TABLE and ALTER TABLE accept are listed in Statements.

All constraint checks run in src/query/engine.rs unless a different file is named. The engine keeps constraint metadata in catalog keys in the same store as the rows:

Key Holds
__catalog__:constraints:{table} per column: name, type, nullable, primary key flag, unique flag
__catalog__:checks:{table} CHECK constraints (JSON)
__catalog__:fks:{table} foreign keys, a list of ForeignKeyDef (JSON)
__catalog__:unique_groups:{table} multi-column UNIQUE groups
__catalog__:uqindex:{table} CREATE UNIQUE INDEX definitions
__catalog__:defaults:{table}, __catalog__:default_exprs:{table} column defaults
__catalog__:generated:{table} generated column expressions
__autoincrement__:{table}:{column} SERIAL / identity counter
__sequence__:{name}, __seqopts__:{name} CREATE SEQUENCE counter and options

(source: src/query/engine.rs, check_insert_constraints, check_row_check_constraints, check_row_foreign_keys, unique_group_columns, check_unique_index_insert, fill_omitted_column, apply_generated_columns, execute_create_sequence_opts)

Error codes at a glance

The PostgreSQL handler derives SQLSTATE from the message text, so the codes below depend on the wording the engine uses. (source: src/protocol/postgres/mod.rs, PostgresHandler::error_to_sqlstate)

Violation Message starts with SQLSTATE
NOT NULL null value in column "c" violates not-null constraint 23502
NULL in a primary key column null value in column "c" violates primary key constraint 23502
Primary key duplicate duplicate key value violates primary key constraint on column(s) ... 23505
UNIQUE / unique index duplicate duplicate key value violates unique constraint "name" 23505
CHECK new row for relation "t" violates check constraint "name" 23514
Foreign key, child side insert or update on table "t" violates foreign key constraint "name" 23503
Foreign key, parent side update or delete on table "p" violates foreign key constraint "name" on table "child" 23503
Explicit write to a generated column text containing (SQLSTATE 428C9) XX000 on the wire, see below

(source: src/query/engine.rs, check_insert_constraints, check_row_check_constraints, check_row_foreign_keys, apply_parent_fk_actions, check_unique_index_insert; src/protocol/postgres/mod.rs, PostgresHandler::error_to_sqlstate)

The primary key message differs from PostgreSQL, which names the index ("t_pkey"). Clients that parse the constraint name out of the message will not find it. (source: src/query/engine.rs, check_insert_constraints)

The feature-matrix harness counts any rejection on both sides as parity, so its error scenarios do not check that the SQLSTATE matches PostgreSQL. (source: test-scripts/feature-matrix/feature_matrix.py)

NOT NULL

A NULL written to a NOT NULL column, or to any primary key column, is rejected on INSERT and UPDATE. (source: src/query/engine.rs, check_insert_constraints) Tests: test_not_null_enforced_on_write; feature matrix scenario not-null.

In the PostgreSQL dialect an explicit NULL stays NULL and is refused; only an omitted column or the DEFAULT keyword receives the column default. On the MySQL wire, a NULL written to an AUTO_INCREMENT column is replaced by the next counter value, as MySQL does. (source: src/query/engine.rs, fill_omitted_column; src/plan/logical.rs, Expr::is_default_marker) Test: explicit_null_into_not_null_with_default_is_refused.

PRIMARY KEY

A single-column primary key is the row's storage key ({table}:{encoded value}), so the duplicate check is one point read, plus a check of the rows already pending in the same statement and in the open transaction's buffer. (source: src/query/engine.rs, pk_storage_key, check_insert_constraints)

A composite primary key uses composite_pk_storage_key when every member value can be encoded, and otherwise falls back to composite_key_duplicate_exists, which scans the whole table. (source: src/query/engine.rs, composite_pk_storage_key, composite_key_duplicate_exists)

Only Boolean, integer, text, UUID, date and timestamp values can be encoded into a key. Float, numeric, bytea, array, JSON, interval and time values cannot. (source: src/query/engine.rs, encode_pk_value)

Tests: test_composite_primary_key_full_tuple_uniqueness, test_single_column_primary_key_still_rejects_dup.

ALTER TABLE … ADD PRIMARY KEY

ADD PRIMARY KEY sets the primary key flag and NOT NULL on the named columns. For a single column, relocate_rows_under_pk rewrites every existing row under its new storage key and rejects the change if two rows share a value. (source: src/query/engine.rs, LogicalPlan::AlterTableAddConstraint arm, relocate_rows_under_pk) Tests: test_add_primary_key_relocates_rows_across_batches, test_add_primary_key_rejects_duplicates_and_keeps_rows, test_add_primary_key_new_key_on_another_rows_old_id, add_primary_key_on_indexed_table (src/query/engine_app_install_tests.rs).

A composite ADD PRIMARY KEY on a table that already has rows does not relocate the rows. Not verified: no test covers duplicate detection for that case. (source: src/query/engine.rs, LogicalPlan::AlterTableAddConstraint arm)

UNIQUE

Single-column UNIQUE

Each non-NULL value of a UNIQUE column is recorded in a secondary key __uniq__:{table}:{column}:{value}, so the check is a point read. NULLs are not recorded, so any number of rows may hold NULL. A citext column is compared in lower case. If the value cannot be encoded, the check scans the table instead. (source: src/query/engine.rs, unique_index_key, check_insert_constraints)

Tests: test_single_column_unique_still_rejects_dup, test_citext_unique_constraint_case_insensitive, concurrent_inserts_of_one_unique_key_keep_one_row, unique_column_insert_waits_then_reports_duplicate.

Multi-column UNIQUE

A table-level UNIQUE (a, b) is stored as a unique group. Every INSERT and UPDATE scans the whole table to look for a matching tuple, so the cost grows with table size. A NULL in any member makes the tuple distinct, as in PostgreSQL. (source: src/query/engine.rs, unique_group_columns, composite_key_duplicate_exists)

Tests: test_multi_column_unique_full_tuple, test_bug4_multirow_insert_same_statement_composite_unique_duplicate.

ALTER TABLE ... ADD [CONSTRAINT name] UNIQUE (cols) takes a different route: it creates a unique index, named {table}_{cols}_uniq when no name is given, and checks the existing rows first. (source: src/query/engine.rs, LogicalPlan::AlterTableAddConstraint arm, backfill_unique_index) Test: test_composite_unique_index_alter_enforce_and_read.

CREATE UNIQUE INDEX

A unique index may have expression keys and a WHERE predicate (a partial unique index). Rows that do not match the predicate do not take part. Creating the index fails if existing rows already break it. (source: src/query/engine.rs, UniqueIndexDef, check_unique_index_insert, backfill_unique_index)

Tests: test_partial_unique_index_soft_delete_semantics, test_partial_unique_index_update_flips_participation, test_expression_unique_index_lower, test_partial_unique_index_backfill_validation, test_unique_index_enforced_within_txn, secidx_unique_index_keeps_enforcement_and_accelerates, upsert_on_conflict_via_unique_index; feature matrix scenarios partial-unique-*, expression-unique.

When a key value cannot be encoded (see the type list under PRIMARY KEY), unique_index_secondary_key returns no key and the row does not take part in the index. A unique index over a numeric, float, bytea, time or json key is therefore not enforced. Not verified: no test covers this case. (source: src/query/engine.rs, unique_index_secondary_key, encode_pk_value)

CHECK

CHECK constraints, column-level or table-level, are evaluated on every INSERT and UPDATE with three-valued logic. The row is refused only when the expression is definitely FALSE; NULL (unknown) passes, as in PostgreSQL. (source: src/query/engine.rs, check_row_check_constraints, eval_predicate_3vl)

An unnamed CHECK is reported as {table}_check. A name given at column level (col int CONSTRAINT positive CHECK (col > 0)) is read and dropped by the parser, so that constraint is also reported as {table}_check. Table-level names are kept. (source: src/query/engine.rs, check_row_check_constraints; src/query/sql/parser.rs, parse_create_table, column loop)

ALTER TABLE ... ADD CONSTRAINT ... CHECK does not check rows that already exist; only later writes are checked. PostgreSQL scans the table unless NOT VALID is given. (source: src/query/engine.rs, LogicalPlan::AlterTableAddConstraint arm, append_check_constraint)

Tests: test_check_constraint_enforced_on_write, test_table_level_check_and_fk; feature matrix scenario check.

FOREIGN KEY

Definition

A foreign key is stored as a ForeignKeyDef: name, child columns, referenced table, referenced columns (empty means the parent's primary key), on_delete, on_update, deferrable and initially_deferred. (source: src/plan/logical.rs, ForeignKeyDef)

Clause Accepted Behaviour
ON DELETE / ON UPDATE NO ACTION yes default; checked at once unless deferred
RESTRICT yes checked at once
CASCADE yes deletes or updates child rows
SET NULL yes sets the child columns to NULL
SET DEFAULT yes sets the child columns to their default, or NULL
SET NULL (cols), SET DEFAULT (cols) no the column-list form is not parsed
MATCH SIMPLE yes the only match mode implemented
MATCH FULL, MATCH PARTIAL parsed treated as MATCH SIMPLE
DEFERRABLE, INITIALLY DEFERRED yes honoured for foreign keys, see below
NOT VALID parsed constraint is enforced immediately

(source: src/plan/logical.rs, FkAction, FkAction::from_keyword; src/query/sql/parser.rs, parse_fk_action, consume_constraint_modifiers)

Any action keyword that FkAction::from_keyword does not recognise becomes NO ACTION. (source: src/plan/logical.rs, FkAction::from_keyword)

An unnamed foreign key is reported as {table}_{columns}_fkey. (source: src/query/engine.rs, check_row_foreign_keys)

Child-side checks

On INSERT and on UPDATE of the child, the engine looks for the referenced parent row. If any foreign key column is NULL the check is skipped (MATCH SIMPLE). The lookup sees the open transaction's own writes. When the foreign key references the parent's whole primary key it is one point read; otherwise the parent is scanned. Numeric values of different types (for example int and bigint) compare equal when they hold the same number. (source: src/query/engine.rs, check_row_foreign_keys, referenced_row_exists_txn, fk_parent_pk_key, fk_values_equal)

On the MySQL wire, SET foreign_key_checks = 0 turns these checks off for the session. (source: src/query/engine.rs, set_foreign_key_checks, fk_checks_off)

Parent-side actions

On DELETE or UPDATE of a parent row the engine finds dependent child rows by scanning each child table; no index is used. (source: src/query/engine.rs, apply_parent_fk_actions, scan_table_with_txn)

Action What happens
NO ACTION error at once, unless the constraint is deferred, in which case the check waits
RESTRICT error at once
CASCADE on delete child rows are deleted through the normal DELETE path, so their own foreign keys cascade in turn
CASCADE on update child key columns are set to the new parent key through the normal UPDATE path
SET NULL child key columns set to NULL through UPDATE
SET DEFAULT child key columns set to their column default, or NULL when there is none

(source: src/query/engine.rs, apply_parent_fk_actions, execute_delete, execute_update, fk_column_defaults)

Cascades stop at a depth of 64 with the error foreign key cascade exceeded maximum depth (64). (source: src/query/engine.rs, FK_CASCADE_MAX_DEPTH)

flowchart TD A["DELETE or UPDATE parent row"] --> B["scan each child table for matching rows"] B --> C{"any dependents?"} C -- no --> Z["write parent row"] C -- yes --> D{"action"} D -- "NO ACTION, not deferred" --> E["error 23503"] D -- RESTRICT --> E D -- "NO ACTION, deferred" --> F["record check for COMMIT"] D -- CASCADE --> G["execute_delete or execute_update on child"] D -- "SET NULL or SET DEFAULT" --> H["execute_update on child"] F --> Z G --> Z H --> Z

(source: src/query/engine.rs, apply_parent_fk_actions)

Deferred foreign keys

A foreign key declared DEFERRABLE is deferred when it is INITIALLY DEFERRED or when the session ran SET CONSTRAINTS ALL DEFERRED or SET CONSTRAINTS name DEFERRED, and only inside an explicit transaction. Deferred checks run at COMMIT; if one fails, the transaction is rolled back, including its DDL. SET CONSTRAINTS ... IMMEDIATE runs the pending checks at once. (source: src/query/engine.rs, fk_is_deferred, handle_set_constraints, run_deferred_fk_checks, check_deferred_constraints_at_commit) Test: test_deferred_foreign_keys_checked_at_commit.

Deferral applies to foreign keys only. UNIQUE ... DEFERRABLE is accepted and still checked per row. (source: src/query/sql/parser.rs, consume_constraint_modifiers; src/query/engine.rs, fk_is_deferred) The feature matrix scenario deferrable-accept only checks that the syntax is accepted.

Adding a foreign key later

ALTER TABLE ... ADD [CONSTRAINT name] FOREIGN KEY ... stores the definition; a second constraint with the same name is an error. Existing rows are not checked. (source: src/query/engine.rs, LogicalPlan::AlterTableAddConstraint arm, append_foreign_key) Test: alter_table_add_unnamed_foreign_key.

Foreign key tests: test_foreign_key_child_insert_enforced, test_foreign_key_same_transaction_read_your_writes, test_foreign_key_parent_delete_restrict, test_fk_on_delete_cascade_and_set_null_repro, test_fk_on_delete_cascade_two_level, test_fk_on_delete_set_default, test_fk_on_delete_restrict_still_errors, test_fk_on_update_cascade, test_fk_cascade_in_transaction, test_fk_self_referential_cascade_terminates, test_bug7_multirow_insert_fk_self_reference_same_statement, test_multi_table_truncate_ignores_fks_between_listed_tables, pg_constraint_has_primary_and_foreign_keys; feature matrix scenarios fk-violation, fk-ok, fk-on-delete-cascade, fk-on-delete-set-null.

Not wired: src/query/constraints.rs defines a separate ForeignKeyManager and ReferentialAction that use __catalog__:fk: keys. Nothing outside that file calls them; the engine uses the code described above. (source: src/query/constraints.rs, ForeignKeyManager)

Dropping constraints

ALTER TABLE ... DROP CONSTRAINT is accepted and does nothing, and VALIDATE CONSTRAINT is a no-op, so a constraint once added stays enforced. See Statements. (source: src/plan/logical.rs, AlterTableNoop; src/query/engine.rs, AlterTableNoop arm)

DEFAULT

When a column is omitted, or written as the DEFAULT keyword, the engine fills it in this order:

Step Applies when Value
1 column is SERIAL, BIGSERIAL, SMALLSERIAL or an identity column next counter value
2 default is a function call that must run at write time result of running SELECT <expr>; PL/pgSQL functions work here
3 stored default text evaluated; nextval('seq') advances the sequence; now(), current_timestamp and other volatile functions are evaluated per row
4 no default NULL

(source: src/query/engine.rs, fill_omitted_column, next_autoincrement, eval_deferred_default, eval_default_value)

On the MySQL wire, in non-strict sql_mode, an omitted NOT NULL column with no default receives the type's zero value; in strict mode the statement fails with Field 'x' doesn't have a default value. (source: src/query/engine.rs, fill_omitted_column, mysql_zero_value)

Defaults are applied to INSERT ... SELECT as well. (source: src/query/engine.rs, fill_omitted_column) Tests: test_insert_select_applies_defaults_for_omitted_columns, test_function_call_default_evaluated_per_insert, alter_column_set_default_function_is_evaluated_per_insert, column_defaults_reach_pg_attrdef_and_information_schema, rollback_undoes_add_column_not_null_default.

On the MySQL wire ON UPDATE CURRENT_TIMESTAMP is accepted and ignored. (source: src/query/sql/parser.rs, parse_create_table)

Generated columns

GENERATED ALWAYS AS (expr) STORED is supported; VIRTUAL is accepted and stored the same way. The value is computed on INSERT and recomputed on every UPDATE. (source: src/query/engine.rs, apply_generated_columns)

Writing an explicit value to a generated column is refused. The error is a QueryExecution error whose text contains (SQLSTATE 428C9), but the PostgreSQL handler maps that error kind to XX000, so clients see XX000 rather than 428C9. (source: src/query/engine.rs, apply_generated_columns; src/protocol/postgres/mod.rs, PostgresHandler::error_to_sqlstate) The feature matrix scenario generated-reject-explicit passes only because the harness accepts any rejection.

Tests: test_generated_column_computed_on_insert, test_generated_column_recomputed_on_update, test_generated_column_rejects_explicit_insert, test_generated_column_rejects_explicit_update, test_fts_generated_tsvector_column.

SERIAL columns

SERIAL, BIGSERIAL and SMALLSERIAL create a counter key __autoincrement__:{table}:{column} starting at 0. They do not create a __sequence__ row. (source: src/query/engine.rs, execute_create_table)

Behaviour SynergyDB PostgreSQL
Omitted value next counter value nextval of the owned sequence
Explicit integer value accepted, and the counter is raised to at least that value once per statement accepted; the sequence does not move
nextval('t_c_seq'), setval('t_c_seq', n) mapped to the column counter act on the owned sequence

(source: src/query/engine.rs, ensure_autoincrement_at_least, implicit_serial_counter_key, serial_past_default_sequence)

Because explicit ids raise the counter, a table loaded with explicit ids continues after the highest id. When a dump also calls setval on a sequence the column default uses, serial_past_default_sequence keeps the counter at or beyond that sequence. (source: src/query/engine.rs, serial_past_default_sequence) Tests: serial_default_after_pg_dump_load_uses_setval, serial_default_follows_setval_after_explicit_ids, serial_default_skips_ids_below_setval_sequence, identity_default_after_metabase_dump_order, inheritance_children_share_parent_sequence.

MySQL AUTO_INCREMENT columns use the same counter. (source: src/query/sql/parser.rs, parse_create_table)

pg_get_serial_sequence('t', 'c') returns schema.t_c_seq only when a __sequence__:t_c_seq key exists. A plain SERIAL column has only a counter, so the function returns NULL for it. Not verified: no test covers this. (source: src/query/engine.rs, pg_get_serial_sequence arm)

Identity columns

GENERATED ALWAYS AS IDENTITY and GENERATED BY DEFAULT AS IDENTITY are rewritten by the parser to SERIAL, BIGSERIAL or SMALLSERIAL according to the base type, and the identity options in parentheses (START WITH, INCREMENT BY and so on) are skipped. (source: src/query/sql/parser.rs, parse_create_table)

Form Behaviour
GENERATED BY DEFAULT AS IDENTITY as SERIAL
GENERATED ALWAYS AS IDENTITY as SERIAL; explicit values are accepted, where PostgreSQL refuses them without OVERRIDING SYSTEM VALUE
identity options ( START WITH 100 ... ) ignored; numbering starts at 1
ALTER COLUMN c ADD GENERATED ... AS IDENTITY column type changed to BIGSERIAL
ALTER COLUMN c DROP IDENTITY [IF EXISTS] the column default is removed; the counter key is kept

(source: src/query/sql/parser.rs, parse_create_table, parse_alter_column_action)

Not verified: after DROP IDENTITY the counter key remains, and no test shows whether omitted values are still numbered. (source: src/query/sql/parser.rs, parse_alter_column_action)

TRUNCATE ... RESTART IDENTITY is not wired; see Statements.

Sequences

CREATE SEQUENCE

Option Behaviour
IF NOT EXISTS no error when the name exists; otherwise relation "x" already exists
AS type parsed and ignored
START [WITH] n honoured
INCREMENT [BY] n honoured; 0 gives INCREMENT must not be zero
MINVALUE n, MAXVALUE n, NO MINVALUE, NO MAXVALUE honoured
CYCLE, NO CYCLE, NOCYCLE honoured
CACHE n parsed and ignored
OWNED BY t.c parsed and ignored

(source: src/query/sql/parser.rs, parse_create_sequence; src/query/engine.rs, execute_create_sequence_opts)

Defaults follow PostgreSQL: an ascending sequence runs from 1 to the largest bigint, a descending one from -1 down to the smallest bigint, and the start is the minimum or maximum respectively. The options are stored as SequenceOpts { start, increment, min, max, cycle } and the counter as an ordinal starting at 0. (source: src/query/engine.rs, execute_create_sequence_opts, SequenceOpts)

Sequence functions

Call Behaviour
nextval('s') value number n is start + (n-1) * increment; past the range it errors with nextval: reached maximum value of sequence "s" (max), or wraps with CYCLE
nextval of an unknown sequence error 42P01
currval('s') last value this session took from s; before any nextval in the session, error 55000 currval of sequence ... is not yet defined in this session
lastval() last value this session took from any sequence; error lastval is not yet defined in this session before that
setval('s', n) next nextval returns the value after n
setval('s', n, false) next nextval returns n

(source: src/query/engine.rs, SequenceOpts::value_for, nextval_checked, session_sequence_values, last_sequence_value, set_sequence_value)

nextval advances the counter atomically outside the transaction, so a rolled-back transaction does not give its values back, as in PostgreSQL. (source: src/query/engine.rs, nextval, advance_i64_counter)

Tests: nextval_of_missing_sequence_errors, test_lastval_session_tracking, test_lastval_undefined_and_no_cross_session_leak, nextval_keeps_its_alias (src/query/engine_hub_walk_tests.rs), sequences_are_visible, pg_sequences_and_multi_ordinal_order_by, rollback_undoes_index_view_sequence_and_constraint; feature matrix scenarios sequence-nextval, sequence-currval.

Where the functions are evaluated

The full behaviour above applies when the statement is a SELECT whose every item is a bare nextval, currval or setval call, optionally aliased, and to nextval in a column default. lastval() works only as the whole statement SELECT lastval(). (source: src/query/engine.rs, execute_with_timeout_inner, sequence fast path before try_handle_advisory_lock; eval_default_value)

Inside a larger expression (for example INSERT INTO t VALUES (nextval('s') * 10) or SELECT nextval('s') FROM t), the expression evaluator's nextval arm advances the raw counter and returns the ordinal. It ignores START, INCREMENT, MINVALUE, MAXVALUE and CYCLE, and it does not update currval or lastval. currval and setval have no arm there, and an unknown function evaluates to NULL. Not verified: no test covers these forms. (source: src/query/engine.rs, evaluate_expr, "nextval" arm)

ALTER SEQUENCE and DROP SEQUENCE

Clause Behaviour
RESTART WITH n honoured
RESTART restarts at 1, not at the sequence's START value
RENAME TO new the counter moves to the new name; the stored options do not
OWNER TO accepted, does nothing
START, INCREMENT, MINVALUE, MAXVALUE, CACHE, CYCLE, OWNED BY parsed and ignored
IF EXISTS accepted; the alter runs whether or not the sequence exists

(source: src/query/engine.rs, LogicalPlan::AlterSequence arm)

Because RENAME TO does not carry the __seqopts__ row, a renamed sequence presumably loses its START, INCREMENT and range options. Not verified: no test covers rename with options. (source: src/query/engine.rs, LogicalPlan::AlterSequence arm)

DROP SEQUENCE removes the counter and the options; a missing sequence gives sequence "x" does not exist. (source: src/query/engine.rs, LogicalPlan::DropSequence arm)

Reading a sequence as a relation

SELECT * FROM s on a sequence returns one row with last_value, log_cnt (always 0) and is_called. (source: src/query/engine.rs, sequence_relation_entry) Sequences also appear in pg_class, pg_sequence, pg_sequences and information_schema.sequences; see System catalogs.

Not wired: src/catalog/sequence.rs has a SequenceRepository with its own unit tests (for example test_sequence_cycle), but the engine does not use it. (source: src/catalog/sequence.rs, SequenceRepository)