Sequences, Auto-Increment and Identity
All generated ids in SynergyDB come from one storage primitive: an i64 counter stored as a bincode value under a key, advanced under a process-wide lock with a per-process reservation block. This page describes the keys, the SQL functions on top of them, how each wire maps its own auto-id syntax onto them, and what survives a crash. Catalog storage in general is on the catalog overview.
Keys
All keys live inside the database namespace (db:<name>\x1F).
| Key | Value | Created by |
|---|---|---|
__sequence__:<name> |
bincode i64: last value, or last ordinal for a sequence with options |
CREATE SEQUENCE, or the first nextval on a column default |
__seqopts__:<name> |
bincode SequenceOpts { start, increment, min, max, cycle }
|
CREATE SEQUENCE with options |
__autoincrement__:<table>:<column> |
bincode i64: last value issued |
CREATE TABLE for each SERIAL-family column, initialized to 0 |
__rowseq__:<table> |
Hidden row id counter for tables without a usable primary key | First insert; see Keys and namespaces |
__catalog__:tds_ident:<table> |
Text: reserved IDENTITY ceiling (SQL Server wire) | First IDENTITY insert |
(source: src/query/engine.rs, sequence_key, execute_create_sequence_opts, SequenceOpts, execute_create_table; src/protocol/mssql/tsql.rs, ident_key)
<name> is the output of normalize_sequence_name, which lowercases, strips quotes and resolves schema qualification against search_path and schema namespaces. (source: src/query/engine.rs, normalize_sequence_name)
The Sequence and SequenceRepository types in src/catalog/sequence.rs keep sequences under a global __catalog:: prefix. Not wired: apart from the re-export in src/catalog/mod.rs, nothing uses them. They have their own unit tests (test_sequence_creation, test_sequence_with_options, test_sequence_next_value, test_sequence_cycle, test_sequence_no_cycle, test_sequence_currval_not_called, test_sequence_setval). (source: src/catalog/sequence.rs; src/catalog/mod.rs)
The counter primitive
StorageEngine offers three advance modes. All hold sequence_alloc_lock, so two connections never receive the same value.
| Mode | Function | Durable write | Used by |
|---|---|---|---|
| Block | advance_i64_counter |
Once per 32 values: the end of the reserved block |
nextval, SERIAL on every wire except MySQL |
| Exact |
advance_i64_counter_exact, advance_i64_counter_exact_by(n)
|
Every call, the exact last value (or the last of n) |
MySQL AUTO_INCREMENT
|
| Row id | advance_u64_counter_by |
Once per 1024-value block (or the whole request if larger), with a synced put
|
Hidden row ids (__rowseq__) |
(source: src/storage/mod.rs, advance_i64_counter_with, advance_i64_counter_exact_by, advance_u64_counter_by)
Block mode
On first use in a process the counter is seeded from the stored value. When the in-memory block is used up, the engine reserves the next 32 values by writing next + 31 as the new stored value, then hands them out from memory. (source: src/storage/mod.rs, advance_i64_counter_with, STRIDE)
The stored value is written with put_unsynced: it goes to the WAL and memtable but does not wait for its own fsync. The row insert that uses the value commits next, and that commit's fsync also covers the counter write. (source: src/storage/mod.rs, advance_i64_counter doc comment)
(source: src/storage/mod.rs, advance_i64_counter_with, shutdown)
Restart behaviour
| Event | Next value |
|---|---|
| Clean shutdown, then start | Last issued + 1: shutdown writes back the exact last value of every partly used block |
Crash or kill -9, block mode |
Up to 32 past the last issued value; never a value already issued |
| Crash, exact mode | Last issued + 1, provided the inserting row's commit was synced |
| Any restart, row id mode | Up to 1024 past the last issued value: shutdown writes back only the 32-value blocks, not the row id blocks |
(source: src/storage/mod.rs, shutdown, advance_i64_counter_with) Tested by serial_counter_reserves_blocks_and_never_repeats_across_restart (asserts the next value after a restart is above the last issued and at most 32 past it), exact_counter_resumes_at_last_value_after_restart_without_shutdown, serial_counter_reads_one_write_per_value_files_and_restarts_after_tombstone, restart_never_reissues_an_id (row ids), oversized_reservation_is_contiguous_and_disjoint and delete_does_not_wait_on_counter_lock. (source: src/storage/mod.rs, those tests)
The guarantee rests on the row commit fsyncing after the counter write. With a wal_sync_mode that does not fsync each commit, a crash can lose both the counter write and the rows that used it; the storage settings describe those modes. Not verified: no test combines a relaxed sync mode with a counter crash.
Other rules
- Any explicit write or delete of a
__sequence__:or__autoincrement__:key throughNamespacedStoragedrops that counter's in-memory block, so the next advance re-reads the stored value. (source:src/storage/namespaced.rs,reset_counter_if_counter;src/storage/mod.rs,reset_counter_block) - A tombstone on a counter key drops its block on the next counter operation. (source:
src/storage/mod.rs,lock_serial_blocks,pending_counter_drops) -
peek_i64_counterreturns the last value handed out in this process, or the stored value if none. (source:src/storage/mod.rs,peek_i64_counter) -
bump_i64_counter_to_at_least(key, v)moves a counter and its block pastv. (source:src/storage/namespaced.rs,bump_i64_counter_to_at_least) - A stored value that does not decode as
i64is read as 0. Not verified: no test covers a corrupt counter. (source:src/storage/mod.rs,advance_i64_counter_with) - The bulk-ingest fast path is skipped for any batch that contains a counter or catalog key. (source:
src/storage/namespaced.rs, bulk ingest check)
PostgreSQL-style sequences
CREATE SEQUENCE
| Form | Stored |
|---|---|
CREATE SEQUENCE s [START WITH n], no other options |
__sequence__:s = n - 1 (default 0). nextval returns the stored value + 1 |
With any of INCREMENT, MINVALUE, MAXVALUE, CYCLE
|
__seqopts__:s and __sequence__:s = 0. The counter holds an ordinal; value_for(ord) maps it to a value |
(source: src/query/engine.rs, execute_create_sequence, execute_create_sequence_opts)
Option defaults follow PostgreSQL:
| Option | Ascending (INCREMENT > 0) |
Descending |
|---|---|---|
MINVALUE |
1 | i64::MIN |
MAXVALUE |
i64::MAX |
-1 |
START |
MINVALUE |
MAXVALUE |
INCREMENT 0 fails with INCREMENT must not be zero. An existing name fails with relation "s" already exists unless IF NOT EXISTS is given. (source: src/query/engine.rs, execute_create_sequence_opts)
value_for(ord) returns start + (ord - 1) * increment while inside [min, max]. Past the bound, a CYCLE sequence restarts at MINVALUE (ascending) or MAXVALUE (descending); otherwise nextval fails with nextval: reached maximum value of sequence "s" (max) (or minimum). The ordinal has already advanced when that error is raised. (source: src/query/engine.rs, SequenceOpts::value_for, nextval)
DROP SEQUENCE deletes both keys and the session's currval entry. (source: src/query/engine.rs, execute_drop_sequence)
Functions
| Function | Behaviour | Error |
|---|---|---|
nextval('s') |
Block-mode advance; records the value for currval and lastval
|
42P01 (relation does not exist) when s has no state, is not the implicit <table>_<column>_seq of a SERIAL column, and is not named by any column default |
currval('s') |
This session's last nextval of s
|
currval of sequence "s" is not yet defined in this session |
lastval() |
This session's last value from any sequence, including the implicit advance of a SERIAL insert | lastval is not yet defined in this session |
setval('s', n [, is_called]) |
is_called true (default): next nextval returns n + increment. False: next nextval returns n
|
|
SELECT last_value FROM s |
One row (last_value, log_cnt = 0, is_called); a never-advanced sequence reports (1, 0, false)
|
(source: src/query/engine.rs, nextval_checked, sequence_exists_or_implicit, currval, lastval, set_sequence_value, sequence_relation_entry) Tested by nextval_of_missing_sequence_errors, sequences_are_visible, pg_sequences_and_multi_ordinal_order_by and nextval_keeps_its_alias. (source: src/query/engine.rs; src/query/engine_hub_walk_tests.rs)
nextval, currval and setval are executed by a fast path that recognizes a SELECT whose list items are these calls; SELECT nextval('s'), nextval('s') advances twice. setval is only handled there: its value must be an integer literal (anything else is read as 1). Not verified: setval inside a larger query (a WHERE, a subquery or a non-SELECT statement). (source: src/query/engine.rs, sequence-function projections)
ALTER SEQUENCE ... RESTART WITH n stores n - 1 through set_sequence_value, converted to an ordinal for a sequence with options. (source: src/query/engine.rs, set_sequence_value)
Transactions
CREATE, ALTER and DROP SEQUENCE inside an explicit transaction are undone by ROLLBACK: DDL statements run with the namespaced storage's undo log recording, which saves the prior value of every key they write. nextval and setval run inside SELECT statements, which do not record, so their effects stay after ROLLBACK, as in PostgreSQL. See Savepoints and transactional DDL. Tested by rollback_undoes_index_view_sequence_and_constraint. (source: src/query/engine.rs, that test; src/storage/namespaced.rs, record_before_write)
Writes to __sequence__: keys bump the catalog epoch, so other sessions see new and dropped sequences; nextval does not bump it. (source: src/storage/namespaced.rs, bumps_catalog_epoch) Tested by statement_caches_follow_views_and_sequences_from_other_sessions and catalog_relation_cache_follows_analyze_and_sequences.
SERIAL and identity columns
Declaration
| Declaration | Becomes |
|---|---|
SERIAL, BIGSERIAL, SMALLSERIAL
|
Itself |
INT ... GENERATED {ALWAYS \| BY DEFAULT} AS IDENTITY [(options)] |
SERIAL (BIGINT gives BIGSERIAL, SMALLINT/TINYINT give SMALLSERIAL) |
MySQL INT ... AUTO_INCREMENT
|
Same promotion |
ALTER COLUMN c ADD GENERATED ... AS IDENTITY |
Same promotion |
(source: src/query/sql/parser.rs, column definition parsing, AUTO_INCREMENT branch, ALTER COLUMN identity branch)
The identity option list in parentheses is skipped, so START WITH and INCREMENT BY on an identity column have no effect, and GENERATED ALWAYS accepts explicit values like BY DEFAULT. (source: src/query/sql/parser.rs, identity form) The statements page records the same lowering.
Values on insert
An insert that omits a SERIAL column calls next_autoincrement(table, column), which advances __autoincrement__:<table>:<column>:
-
MySQL wire (
mysql_dialecton): exact mode. A multi-rowINSERTreserves all its ids in one write (advance_i64_counter_exact_by) and hands them out fromautoinc_prealloc. - Every other wire: block mode.
(source: src/query/engine.rs, next_autoincrement; src/protocol/mysql/mod.rs, set_mysql_dialect)
The value also feeds lastval() and MySQL's LAST_INSERT_ID(). A table whose column has no counter is remembered in MetaCache.autoinc_absent until the next DDL. (source: src/query/engine.rs, next_autoincrement, MetaCache)
An insert with an explicit id moves the counter past it (ensure_autoincrement_at_least). (source: src/query/engine.rs, ensure_autoincrement_at_least)
Column counter versus the named sequence
A SERIAL column's counter and a sequence named <table>_<column>_seq (or the sequence named in the column's nextval(...) default) can both carry state, for example after a pg_dump load runs setval. serial_past_default_sequence keeps them in step: the column never hands out a value at or below the plain sequence's last value, and the sequence is moved up to what the column handed out. Sequences with options are left alone. (source: src/query/engine.rs, serial_past_default_sequence) Tested by 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 and inheritance_children_share_parent_sequence. The migration guide describes the user-visible fix.
TRUNCATE
On the SQL engine path, RESTART IDENTITY and CONTINUE IDENTITY are parsed and ignored, so counters always continue. Tested by truncate_empties_table_frees_unique_values_and_keeps_serial, which runs TRUNCATE ... RESTART IDENTITY and asserts the next id is above the old range. (source: src/query/sql/parser.rs, TRUNCATE options; src/query/engine.rs, TRUNCATE rewrite; tests/truncate_fast.rs) PostgreSQL resets the owned sequences for RESTART IDENTITY, so this differs.
On the MySQL wire, TRUNCATE resets every counter of the table to 0 after the delete, as MySQL does. (source: src/protocol/mysql/mod.rs, TRUNCATE result handling; src/query/engine.rs, reset_autoincrement)
MySQL
| Feature | Behaviour |
|---|---|
AUTO_INCREMENT column |
SERIAL family, exact-mode counter |
LAST_INSERT_ID(), LAST_INSERT_ID(expr)
|
Session value from the engine; LAST_INSERT_ID(expr) sets it |
OK packet last_insert_id
|
Filled from the engine when the statement uses LAST_INSERT_ID(
|
SHOW CREATE TABLE |
Prints AUTO_INCREMENT=<last + 1> when the counter is above 0 |
CREATE TABLE ... AUTO_INCREMENT=n table option |
Skipped by the parser with the other table options; no code applies it |
TRUNCATE |
Resets the counter to 0 |
(source: src/query/engine.rs, next_autoincrement, last_insert_id, SHOW CREATE TABLE builder, reset_autoincrement; src/query/sql/parser.rs, MySQL table options; src/protocol/mysql/mod.rs)
The per-table counters map in the MySQL wire's AutoIncrementTracker is never advanced (get_next has no caller); only its session last_insert_id is used. (source: src/protocol/mysql/mod.rs, AutoIncrementTracker)
Contradiction: the README's MySQL known-gaps entry and the guide say AUTO_INCREMENT values are reserved 32 at a time and can jump by up to 32 after kill -9. The code uses exact mode for the MySQL wire, which the storage test exact_counter_resumes_at_last_value_after_restart_without_shutdown shows resuming at last + 1. (source: README.md, Known gaps, MySQL; src/query/engine.rs, next_autoincrement; src/storage/mod.rs, that test)
SQL Server IDENTITY
The TDS wire keeps its own IDENTITY allocator instead of SERIAL:
| Item | Behaviour |
|---|---|
| Current value | In memory per table in Shared.ident_lock; after a restart, the stored ceiling; with neither, MAX(col) or seed - increment
|
| Durable state |
__catalog__:tds_ident:<table>: a ceiling of first + 1000 * increment, rewritten when an allocation passes it |
| After a crash | Resumes past the ceiling, so ids can jump by up to 1000, as SQL Server's identity cache does |
Temporary tables (#t) |
Key suffixed __s<spid>, deleted when the session ends |
SCOPE_IDENTITY(), IDENT_CURRENT('t')
|
Session's last identity; table's current value |
SET IDENTITY_INSERT t ON |
Explicit values allowed; the counter moves past the new MAX(col) (bump_identity) |
Explicit value with IDENTITY_INSERT OFF
|
Error Cannot insert explicit value for identity column in table 't' when IDENTITY_INSERT is set to OFF.
|
DBCC CHECKIDENT |
Handled by exec_checkident
|
(source: src/protocol/mssql/tsql.rs, Shared, ident_current_locked, ident_set, alloc_identity, bump_identity, ident_store_key, exec_checkident; src/protocol/mssql/mod.rs, session cleanup)
The ceiling is written with a plain put, separate from the row insert, and the clean-shutdown write-back of the block counters does not apply to it. Not verified: no test in the snapshot covers IDENTITY allocation or restart behaviour; src/protocol/mssql/batch.rs only checks that SCOPE_IDENTITY() is split into its own statement.
rowversion values come from nextval('__tds_dbts'), a database-wide sequence. (source: src/protocol/mssql/tsql.rs, ROWVERSION_EXPR)
SQLite and libSQL
The SQLite wire assigns rowids itself before the insert reaches the engine, because SQLite reuses ids that the engine's counters never would:
- The new rowid is
max(rowid) + 1over the table, so ids freed by a failed or rolled-back insert are reused, as in SQLite. - For
INTEGER PRIMARY KEY AUTOINCREMENT, the base is also at least the high-water mark kept in__sqlite_metaunderseq:<table>, so ids are never reused, as withsqlite_sequence. The mark is advanced even whenON CONFLICT DO NOTHINGskips the row, and deleted with the table. - A
NULLin the rowid column also means "assign".
(source: src/protocol/sqlite/hrana.rs, assign_rowids, insert and drop handling; src/protocol/sqlite/dialect.rs, Table.autoincrement) Not verified: no unit test for assign_rowids was found; the SQLite wire page lists the wire-level evidence.
Snowflake and Oracle
The Snowflake dialect rewrites AUTOINCREMENT and IDENTITY [(start, inc)] [START s INCREMENT i] [ORDER|NOORDER] to GENERATED BY DEFAULT AS IDENTITY (START WITH s INCREMENT BY i). The engine parser then discards the option list (see above), so a non-default start or increment is not applied. Column metadata always reports IDENTITY START 1 INCREMENT 1 ORDER for such columns. (source: src/protocol/snowflake/dialect.rs, identity rewrite; src/protocol/snowflake/mod.rs, column description; src/query/sql/parser.rs, identity form) Not verified: no test checks a Snowflake identity with a non-default start.
The Oracle dialect maps seq.NEXTVAL to nextval('seq') and drops ON NULL from identity columns. Tested by identity_on_null_is_dropped. (source: src/protocol/oracle/dialect.rs, NEXTVAL rewrite, identity_on_null_is_dropped)
Summary of gap behaviour
| Source of ids | Gaps after a crash | Reuse |
|---|---|---|
PostgreSQL SERIAL, identity, nextval
|
Up to 32 | Never |
MySQL AUTO_INCREMENT
|
None if the row committed | Never, except after TRUNCATE
|
| Hidden row ids | Up to 1024, also after a clean restart | Never |
SQL Server IDENTITY
|
Up to 1000 | Never |
SQLite rowid without AUTOINCREMENT
|
None | Yes: max(rowid) + 1
|
SQLite AUTOINCREMENT
|
None | Never |
| Values from rolled-back transactions | Lost | Never (SQLite rowids excepted) |
(source: sections above)