14 Commits

Author SHA1 Message Date
Pekka Enberg
1e21c2beb6 core, sqlite/parser: reject LIMIT and ORDER BY on DELETE and UPDATE
Turso accepted DELETE/UPDATE ... LIMIT unconditionally, while a default
SQLite build only allows it with SQLITE_ENABLE_UPDATE_DELETE_LIMIT. Worse,
the support was a half-implementation: LIMIT/OFFSET executed but
ORDER BY ... LIMIT was rejected at translate time, so the upstream
wherelimit tests ran and failed spuriously instead of skipping.

Remove the order_by/limit fields from the DELETE and UPDATE AST nodes so
the parser stops consuming those clauses. The trailing token then fails
the normal end-of-statement check and produces the same
`near "LIMIT": syntax error` as stock sqlite3. Stripping the AST fields
also removes all the dead LIMIT plumbing from the translator, planner,
optimizer, and emitters.

Mark the update_delete_limit capability as unavailable in the upstream
conformance harness, and make its simplified ifcapable propagate return
codes so tests using `ifcapable !x { finish_test; return }` actually
skip. wherelimit.test and wherelimit2.test now skip themselves exactly
as they do on default sqlite3 builds.

Tests: new delete-update-limit-rejected.sqltest passes against both
tursodb and stock sqlite3 with no skip markers; parser regression test;
CLI tests rewritten to assert rejection.

Fixes #6076
2026-08-10 17:01:33 +03:00
Claude
8618d9a555 docs: document NULLS FIRST/LAST in indexes and constraints
Cover the new NULLS FIRST/LAST support in CREATE INDEX and in table
PRIMARY KEY and UNIQUE constraints: syntax, storage placement defaults,
sort elision, the rowid alias and WITHOUT ROWID cases where the clause
has no effect, and the warning that stock SQLite cannot open a schema
that uses it. List it as a Turso extension on the compatibility page
and note that upsert conflict targets still reject it.

Also fix wrong claims that predate this feature: the SELECT page said
the default NULL placement was NULLS LAST for ASC and NULLS FIRST for
DESC (it is the opposite), and the language reference book said NULLS
LAST was a parse error and showed COLLATE after ASC/DESC in ordering
terms (the parser only accepts it before).

Tests: verified every documented example and default against tursodb,
including EXPLAIN QUERY PLAN showing sort elision for matching
placements and a sorter fallback for mismatched ones.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VpGXUdx42eQrq5ZXEqCRNz
2026-08-03 19:27:20 +00:00
Glauber Costa
2d671ede9b docs: refresh SQL reference for Turso 0.7
Fill the gaps in docs/sql-reference that were still stale after the 0.7
release. Verified every claim against the v0.7.0 source (COMPAT.md,
core/function.rs, the parser AST, and cli/).

- window: row_number() and FILTER (WHERE ...) are supported now
- scalar: add unistr, unistr_quote, turso_version()
- vector: add vector32_sparse; note the experimental sparse vector index
- transactions: document SAVEPOINT / RELEASE / ROLLBACK TO
- add REINDEX statement page
- create-trigger: drop the experimental banner (triggers are stable);
  mark INSTEAD OF as not yet supported
- create-table: reclassify WITHOUT ROWID and GENERATED as experimental
  flags; note locale/custom collations
- create-index: document COLLATE and link REINDEX
- select: correct the window ranking note (row_number available)
- experimental-features: triggers are no longer experimental; add
  generated_columns, without_rowid, mvcc_passive_checkpoint
- extensions: document the crypto, fuzzy, and ipaddr extensions
- pragmas: add data_sync_retry, require_where/i_am_a_dummy,
  mvcc_checkpoint_threshold, mvcc_gc_threshold
- cli: drop --experimental-triggers; add the new experimental flags
2026-07-15 09:16:37 -05:00
Glauber Costa
b9503e7d0b feat: add PostgreSQL-style sequences and MVCC-safe AUTOINCREMENT
Add CREATE SEQUENCE / DROP SEQUENCE / nextval() / setval() / currval()
as first-class schema objects, and reimplement AUTOINCREMENT on top of
the same infrastructure so it works correctly under MVCC.

Sequences are the standard mechanism for generating monotonically
increasing (or decreasing) identifiers. This commit adds full support
for user-created sequences (CREATE SEQUENCE name [INCREMENT BY n]
[MINVALUE n] [MAXVALUE n] [START n] [CYCLE | NO CYCLE]) and the
functions nextval(), setval(), and currval(). AUTOINCREMENT tables now
implicitly create a sequence named __turso_internal_autoincrement_<table>
so high-water-mark logic is unified across both features.

Design: disk is the source of truth
-----------------------------------

Every sequence is backed by a hidden B-tree table:

    CREATE TABLE "__turso_internal_seq_<name>"(
        value INTEGER PRIMARY KEY,    -- rowid alias = the sequence value
        is_called INTEGER,
        start INTEGER, inc INTEGER,
        min INTEGER, max INTEGER, cycle INTEGER)

`value` is INTEGER PRIMARY KEY (the rowid alias). The B-tree is keyed
by the sequence value, so MIN(value) / MAX(value) is an O(1) seek to
the first/last leaf -- the B-tree *is* the watermark.

The in-memory `Sequence` is pure schema data -- start, increment, min,
max, cycle. No AtomicI64, no is_called flag, no dirty bit, no
in-process current-value cache. This is a deliberate change from an
earlier in-memory-atomic design which couldn't be made safe across
processes (multiple workers on the same disk would each maintain their
own atomic and diverge). Reading from disk on every call is the only
design that survives multiprocess WAL, MVCC, and crash-recovery
uniformly.

nextval execution
-----------------

At compile time, nextval() emits `begin_write_on_database`, making the
statement a write transaction. At runtime the translator emits an RMW
sequence (see core/translate/sequence.rs::emit_disk_read_nextval):

1. SequenceBeginInnerTx -- under MVCC, open an autonomous inner
   Concurrent tx scoped to this RMW. The outer tx (if any) is saved
   off. Under WAL or when the outer tx is exclusive, this is a no-op
   -- the RMW runs in the outer tx; the single-writer WAL lock
   provides the same serialization the inner tx provides under MVCC.
2. Cursor RMW: Rewind/Last on the backing table -> read the single
   watermark row -> SequenceComputeNext opcode computes the next value
   from (current, is_called, start, inc, min, max, cycle) baked into
   the program -> Insert the new row keyed by the new value (since
   `value` is INTEGER PRIMARY KEY, distinct nextvals land on distinct
   B-tree keys and never key-conflict).
3. Inline backing-table compaction: a small loop emitted right after
   the insert deletes every row except the new watermark. After every
   successful nextval the backing table holds exactly one row. (This
   used to run at commit time via flush_dirty_sequences, but the
   implementation issued nested prepare_internal() calls that drove
   pager.io.step() synchronously and broke the vdbe async contract --
   the outer Statement::step() would block instead of returning
   StepResult::IO. Moving the compaction inline fixed that.)
4. For AUTOINCREMENT-backing sequences, mirror the watermark into
   sqlite_sequence in the same inner tx so SQLite-compat readers see
   the high-water mark without needing a checkpoint.
5. SequenceCommitInnerTx -- commit the inner tx. On WriteWriteConflict
   (against another nextval racing on the same backing table),
   op_sequence_commit_inner_tx retries the whole RMW with a bounded
   budget (ProgramState::sequence_inner_retry_count); when the budget
   is exhausted it surfaces LimboError::Busy so the caller can retry
   at their level. The outer tx (if any) is restored.

Why an inner tx under MVCC: a nextval that aborts because its outer tx
rolls back must still leave its watermark advance durable on disk --
otherwise a parallel reader could observe the same value twice (the
first reader sees the in-memory state, the rolled-back tx releases its
disk write, the next reader recomputes and lands on the same value).
The autonomous inner tx commits the backing-table write independent of
the outer tx, so a rolled-back nextval still "consumed" the value.
This is the standard PostgreSQL semantics (rollback does not reclaim
nextval'd values; gaps are expected).

setval
------

setval(seq, value) can place the watermark anywhere, which cannot be
expressed as a conflict-free append (two concurrent setval(s, 5)
followed by setval(s, 3) are not commutative). It requires an
exclusive write transaction and is rejected inside BEGIN CONCURRENT.

currval
-------

currval(seq) is per-connection. It returns the value most recently
emitted by nextval or setval on this connection. It's a register
lookup populated by the SetSequenceCurrval opcode at the tail of
every nextval/setval; it does not touch disk.

Restart / recovery
------------------

On database open, sequences are initialized from disk:
- User sequences: read the single watermark row from each
  __turso_internal_seq_* backing table.
- AUTOINCREMENT: read sqlite_sequence and seed the implicit sequence
  to that value.

If a crash occurs after a nextval committed but before its compaction
loop deleted the prior row, the backing table may briefly contain
multiple rows. The compaction always re-runs on the next nextval, and
the open-time read uses MAX(value) for ascending or MIN(value) for
descending sequences, so multi-row state is recovered cleanly.

The MVCC checkpoint state machine also rewrites sqlite_sequence from
the in-schema sequence list during checkpoint, ensuring the on-disk
autoinc state is clean after every checkpoint cycle.

Testing
-------

- Integration tests covering all sequence operations, concurrent
  nextval from multiple connections, AUTOINCREMENT interaction, ATTACH
  database sequences, transaction rollback semantics, descending and
  CYCLE sequences, and restart-recovery scenarios.
- Simulator (limbo_sim): sequence-aware query generation
  (CREATE/DROP SEQUENCE, nextval, setval) and a SequenceMonotonicity
  property -- creates a fresh sequence in a reserved namespace, runs N
  nextvals, asserts the engine returned start + k*increment (or
  correct CYCLE wrap).
- Concurrent simulator (whopper): dedicated sequence workloads
  testing MVCC concurrent nextval, setval exclusivity, in-flight
  setval that survives worker death, autocommit and in-tx nextval
  interleavings, CYCLE wrap-aware duplicate / wrong-direction
  tracking, and cross-checkpoint persistence. Coverage includes
  InsertSeqDefault (INSERT into table with DEFAULT (nextval('s'))) and
  tracker handling for sequences advanced through that opaque path.
- SQL tests (sqltest): sequence.sqltest, mvcc_sequence.sqltest, and
  attach/sequence.sqltest covering the full feature surface.

Closes #5688
2026-06-08 15:25:05 -04:00
Glauber Costa
a2b7f8d846 docs: mention array types in data-types and CREATE TYPE pages
Arrays are part of the custom types system alongside STRUCT and UNION,
but were only documented in the array functions page. Now the data-types
page introduces arrays early (opening paragraph + STRICT types callout)
and the CREATE TYPE page has a dedicated Array Types section with examples.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 08:08:02 -05:00
Avinash Sajjanshetty
fed0c30814 vacuum: expose experimental plain vacuum 2026-04-27 21:43:39 +05:30
Glauber Costa
0d30ac633b Add STRUCT and UNION composite types for STRICT tables
Adds STRUCT and UNION composite types, defined via CREATE TYPE and
usable as column types in STRICT tables.

- STRUCT stores named, typed fields as a SQLite record blob
- UNION is a tagged union (one-byte tag + variant value)
- New functions: struct_pack, struct_extract, union_value, union_tag,
  union_extract
- Dot notation sugar: col.variant.field desugars to nested extract calls
- Type checking enforces schema on INSERT
- Expression indexes on STRUCT/UNION functions are supported
- Partial index WHERE predicates using custom type functions work
  correctly across INSERT, UPDATE, and UPSERT (uses emit_dml_expr_index_value
  to preserve type context)

Gated behind --experimental-custom-types.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 18:33:00 -04:00
Glauber Costa
db2504b5c6 Document retroactive type/domain creation behavior on non-STRICT tables
Add notes to CREATE DOMAIN and CREATE TYPE docs explaining that if a
non-STRICT table uses a type name before the type/domain is created,
constraints are not retroactively enforced. This is by design since
non-STRICT tables treat all type names as plain affinity hints, and
STRICT tables prevent the scenario by rejecting unknown type names.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 21:53:15 -05:00
Glauber Costa
e5c540aabd Add CREATE DOMAIN / DROP DOMAIN support
This is also present in Postgres and is part of the type system.
It will make a great addition to what we do.

Domains are much lighter than types: they are just normal types that
encode properties (like default, not null, and checks).

This is also dependent on the experimental flag for custom types.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-19 21:43:09 -05:00
Glauber Costa
2c16e2a2e8 Add DEFAULT keyword support in INSERT VALUES expressions
Implement the SQL-standard (SQL:2016 §14.11) DEFAULT keyword inside
INSERT VALUES lists, allowing explicit use of column defaults on a
per-value basis:

  INSERT INTO t (a, b) VALUES (1, DEFAULT), (DEFAULT, 2);

This feature does not exist in SQLite — it is a Turso extension as
part of our effort to make Turso behave more like Postgres, which has
supported this syntax for a long time. The motivation is that omitting
columns from the INSERT column list applies defaults uniformly across
all rows, but DEFAULT in VALUES lets different rows use defaults for
different columns within the same statement.

Expr::Default is resolved to the actual column default expression (or
NULL) in the AST before bytecode compilation, so both single-row and
multi-row INSERT paths work without special-casing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 20:26:18 -05:00
Glauber Costa
0bc101a6b3 feat: add array column type support with PostgreSQL-style array functions
Adds array column types (e.g. INTEGER[], TEXT[][]) stored as record-format
blobs with zero-copy ValueIterator streaming. Includes ARRAY[] constructor,
subscript access, comparison operators (@>, &&, =, <, etc.), 12 scalar
functions (array_length, array_append, array_cat, etc.), and array_agg
aggregate. Parser extended with ARRAY keyword, bracket subscripts, and
new operator tokens.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 10:19:39 -04:00
Pekka Enberg
5b8d84888f Rename remaining experimental_mvcc references to mvcc
Update VDBE comment, docs, simulator, and integration tests to use
the new mvcc pragma name.
2026-03-02 10:44:02 +02:00
Glauber Costa
3114781455 feat: per-database MVCC transactions for attached databases
Each attached database now gets its own independent MvStore with its own
.db-log file when the main database uses MVCC mode. This enables full
MVCC isolation across all databases in a session.

Key changes:
- Split MVCC transaction storage: mv_tx for main DB (hot path),
  attached_mv_txs SmallVec for attached DBs (cold path)
- op_open_read/op_open_write/op_transaction use per-DB MvStore lookup
- commit_txn_mvcc iterates all databases with active MVCC transactions
- rollback handles attached MVCC transactions before clearing state
- Removed hardcoded MVCC block in ATTACH translation
- Removed @skip-file-if mvcc from ATTACH test files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:03:40 -06:00
Glauber Costa
b3eeabf38d add SQL language reference documentation
Comprehensive SQL reference at docs/sql-reference/ covering all
supported statements, functions, expressions, PRAGMAs, and
extensions. Includes mdBook-based local preview (./preview.sh).

Turso-specific features (CDC, materialized views, custom types,
MVCC, vector search, FTS, encryption) are integrated inline with
callouts. Experimental features link to a dedicated page with
enablement instructions for the CLI and all SDKs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 14:05:32 -06:00