The docs said jsonb_extract always returns BLOB. Scalars come back as
INTEGER, REAL, TEXT or NULL; only arrays, objects and multi-path
results come back as JSONB blobs.
Applications that run checkpoints themselves, or that want the WAL to
grow more or less than 1000 pages, set PRAGMA wal_autocheckpoint as
SQLite documents it. Turso ignored the pragma as an unknown name, so a
connection that turned automatic checkpoints off still got one after
any commit that left more than 1000 frames in the WAL.
PRAGMA wal_autocheckpoint returns the connection's threshold, 1000 by
default. PRAGMA wal_autocheckpoint = N sets it for this connection only
and returns the new value. Zero, a negative value, or a value too large
for a 32-bit int turns automatic checkpoints off and reads back as 0,
as in SQLite.
Closing the last connection still checkpoints the WAL: SQLite runs that
checkpoint whatever this setting is. Like SQLite, the pragma has no
pragma_wal_autocheckpoint table-valued function.
Tests: cargo test -p core_tester --test integration_tests pragma_wal_autocheckpoint
Tests: sqltest run sqlite-sqltests/pragma/memory.sqltest -f 'pragma-wal-autocheckpoint-*'
Wrap the open-database map in an OpenHandles type whose only insertion
path enforces the cap, so nothing can push it past --sync-max-databases.
Restrict database names to lowercase so that one name is one file and
one handle on case-insensitive filesystems too. Drop the Windows
reserved device name list: opening such a name simply fails.
Open directory databases with the caller's options as given instead of
the CLI shell options, which turn on extension loading.
Keep the server error message free of CLI flag names, tighten the help
text for --sync-max-databases, use TempDir in the unit tests, and trim
the docs and README to the essentials. Note that VACUUM INTO can write
outside the served directory alongside the existing ATTACH caveat.
Tests: cargo test -p turso_cli sync_server; cargo clippy --workspace
--all-features --all-targets; cargo check -p turso --features sync --tests
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y1uLrzBq9CGq6yUDpiqHnJ
Cover the URL shape, on-disk layout, database-name rules, and the current
limitations: server-wide request serialization, inherited WAL retention, an
unbounded handle cache, and no authentication
durable_through and written_through are a dense owned prefix. A retry
hole must not be covered when a later ticket is written, or a waiter
acks EndCommitLogicalLog with no record.
A waiter dropped after log_tx is issued must not roll back. The leader
owns those bytes and finishes the commit. Discard before own still
retries or rolls back.
Tests: cargo test -p turso_core --lib group_commit
Each concurrent MVCC commit currently appends and fsyncs its own record
under pager_commit_lock. PRAGMA mvcc_group_commit queues those records
so the lock holder writes the batch and fsyncs once. The pragma is off
by default. Exclusive transactions still commit alone.
Tests: cargo test -p turso_core --lib group_commit (13 passed)
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
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
Add nth_value(value, position), which returns the value at a chosen place in the ordered rows.
Read the position again for every result row, as SQLite does. This lets the position change from row to row, even when rows have equal sort values. Check the position only when returning that row, so LIMIT and OFFSET handle errors the same way as SQLite.
Reject whole-number decimals that are too large instead of letting rounding turn them into a valid position.
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
The sqlean-time port represents a time value as an opaque 13-byte BLOB,
but the extensions reference table listed every time value as INTEGER.
Correct the parameter/return columns, add the missing registered
functions (make_date, make_timestamp, to_timestamp, time_round), and
document that time values are BLOBs with the STRICT-table workaround.
Fixes#7665
Adds reference entries for the new scalar functions and PostgreSQL-
compatible aliases:
* math.mdx: gcd(A, B), lcm(A, B)
* array.mdx: array_upper, and the now-honored dimension argument
to array_length
* scalar.mdx: repeat(X, N), lpad/rpad (2- and 3-arg forms),
reverse / string_reverse, plus the PG-compatible
aliases chr, strpos, btrim, char_length, character_length
Each new function gets a table entry in the overview and a dedicated
detail section with semantics (NULL propagation, overflow, character-
vs-byte counts, sign handling) and runnable examples. Aliases are
folded into the canonical function's section rather than duplicated.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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
Implement the SQL-standard ordered-set aggregate syntax
`f(args) WITHIN GROUP (ORDER BY x)` for mode(), percentile_cont() and
percentile_disc() as first-class core aggregates, documented under
docs/sql-reference/functions/aggregate.mdx.
WITHIN is a context-sensitive keyword (only after `)` + GROUP), so it
remains usable as an identifier. The planner rewrites the ordered-set
form into uniform aggregate args and rejects unsupported variants
(DESC/NULLS, multi-column ORDER BY, DISTINCT) with clear errors rather
than returning wrong results.
The percentile fraction is a direct argument: it must be constant with
respect to the aggregated rows. A reference to the query's own input
columns (directly or via a subquery) is rejected, while an outer
(correlated) column is allowed, matching PostgreSQL. A constant fraction
is folded and range-checked at compile time, so an out-of-range fraction
errors regardless of row count (empty / all-NULL / all-filtered input).
Text ordered sets are collation-aware: mode() and percentile_disc() sort
using the value's collation (explicit COLLATE, column-declared collation,
or the BINARY default), recorded in the aggregate payload at step time
and applied when sorting at finalize.
Validated against PostgreSQL 18 across the accept-path plus corner cases
(subqueries, CTEs, FILTER, HAVING, correlated references including an
outer-column fraction, constant-expression fractions, expression/CASE
order keys, and attached databases). The BINARY default matches PG
`COLLATE "C"`; NOCASE / column collations are honored consistently with
ORDER BY. Extension-registered Custom collations fall back to BINARY at
finalize, consistent with the engine's other connection-less comparison
paths.
Tests wrap percentile_cont (REAL) results in CAST(... AS TEXT) so the
whole-number float comparison is stable across the rust, cli and js test
backends (the js backend renders 3.0 as "3").
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
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>
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>
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>
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>
Add documentation for the tursodb CLI as a new top-level section in the
existing reference book. Covers command-line flags, all dot commands with
tested examples, output modes, and server modes.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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>
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>