41 Commits

Author SHA1 Message Date
Jussi Saurio
13854a23a4 sqlite: add merged USING column expressions
In `t1 FULL JOIN t2 USING(a)`, a row can be missing from either table, so
an unqualified `a` is t1.a when that is not NULL and t2.a otherwise. The
value equals coalesce(t1.a, t2.a), but comparisons treat it like the
column t1.a: it takes t1.a's affinity and collation. A user-written
coalesce() has no affinity and can take its collation from any argument.
With t1.a INTEGER and a row only in t2 whose a is the text '7', `a = 7`
is true but `coalesce(t1.a, t2.a) = 7` is false.

Add Expr::MergedColumn for this value, so code that handles user
coalesce() calls cannot apply to it by accident. SQLite gets the same
effect by marking its internal coalesce call with SQLITE_AFF_DEFER. Name
binding creates the node in the next commits.
2026-10-07 06:55:08 +03:00
Pekka Enberg
735cdd83a1 Merge 'core: implement PRAGMA wal_autocheckpoint' from
Turso ignores `PRAGMA wal_autocheckpoint`: COMPAT.md lists it as not
supported, and an unknown pragma name does nothing. An application that
turns automatic checkpoints off, to run them itself, still gets a
checkpoint inside any commit that leaves more than 1000 frames in the
WAL.

This implements it as SQLite documents it
(https://sqlite.org/pragma.html#pragma_wal_autocheckpoint):
- `PRAGMA wal_autocheckpoint;` returns the connection's threshold, 1000
by default;
- `PRAGMA wal_autocheckpoint = N;` sets it for this connection only and
returns N;
- N <= 0, or a value outside the 32-bit int range, turns automatic
checkpoints off and reads back as 0;
- closing the last connection still checkpoints the WAL, as in SQLite.

The first commit moves the fixed threshold from `WalFile` to
`Connection` with no behaviour change, so the setting also holds on a
connection that has no WAL file. The second adds the pragma, the tests,
COMPAT.md and the docs.

Known differences from SQLite: `OFF` or `'abc'` are an error, as with
Turso's other integer pragmas, where SQLite reads 0; `1e3` reads as 1000
where SQLite reads 1.

Tests:
- 3 integration tests (`pragma_wal_autocheckpoint`: off keeps every
frame in the WAL, a small threshold checkpoints after a commit, the
setting is per connection) and 5 sqltest cases fail on main and pass
with the change;
- the same 5 sqltest cases pass on sqlite3 3.40.1 (`--backend cli`);
- `pragma::` and `wal::` integration tests: 39 passed; `turso_core`
`storage::` unit tests: 458 passed;
- `cargo fmt --check` and `cargo clippy --workspace --all-features
--all-targets -- --deny=warnings` are clean.

Reviewed-by: Pekka Enberg <penberg@iki.fi>
Reviewed-by: Avinash Sajjanshetty (@avinassh)

Closes #9510
2026-10-06 16:20:25 +03:00
Pekka Enberg
6fd4e37e0c Merge 'docs: fix 'cargo doc' warnings' from Raminder Singh
This PR fixes many warnings when build docs with the `cargo doc
--workspace --no-deps` command.

I was building the docs to understand the codebase better but found many
warnings. The major types of warnings fixed were the following:

* `this URL is not a hyperlink`: this was due to missing < and > around
a hyperlink in docs.
* `redundant explicit link target`: this was because explicit target in
( and ) was not needed. E.g. in
`[`Error::BatchStatementFailed`](crate::Error::BatchStatementFailed)`.
* `unresolved link to `turso::params`: these kinds of warnings were due
to links not resolving to actual code elements. There were many reasons
for this e.g. the code element's path was incorrect or it ware renamed
etc.
* `unclosed HTML tag`: this was due to < and > character used in docs
for purposes other than an html tag.

Many of the low hanging fruit like html tags warnings were fixed by
hand. AI was used to find correct references to the right code element.
E.g. to figure out that `[`get_timestamp`]` was actually at
`[`LogicalClock::get_timestamp`]` or to fix a couple of broken code
examples in docs.

Closes #9458
2026-10-06 10:40:34 +03:00
Raminder Singh
8dd0caac4e docs: fix 'cargo doc' warnings
`cargo doc --workspace --no-deps` reported many rustdoc warnings. Fix
them without changing what any comment says:

- Wrap bare URLs in `<` and `>` so rustdoc renders them as links.
- Drop explicit link targets that only repeat the link text.
- Point intra-doc links at the item's real path, or write names that
  rustdoc cannot resolve as plain code text.
- Escape `<` and `>` that are not HTML tags.
- Add the braces rustdoc needs to parse the example code blocks.

Tests: cargo doc --workspace --no-deps reports no rustdoc warnings

Co-authored-by: Pekka Enberg <penberg@iki.fi>
2026-10-06 10:18:26 +03:00
Jussi Saurio
e57f82a2c2 parser: box large and rare parts of Expr
An Expr was 240 bytes: Exists, InSelect and Subquery stored a whole
Select inline, and every FunctionCall stored its OVER window definition
inline. Every expression is as large as its largest variant, and the code
that parses, clones, drops and translates expressions recurses once per
level, building an Expr in its stack frame at each level. For example,
the derived Clone of Expr needed an 880-byte frame, and the optimizer
clones the WHERE clause, so a long OR chain in a WHERE clause spent its
stack there.

Box the Select of those variants, the table name of `x IN tablename`, and
the OVER clause, like SQLite, which keeps them behind pointers. An Expr
is now 128 bytes.

A variant of AggregateRewrite that holds an Expr is no longer large
enough for clippy::large_enum_variant, so its expectation is removed.
2026-10-05 15:52:51 +03:00
Jussi Saurio
e8530d0911 parser: keep the frames of recursive expression parsing small
parse_expr_inner() and parse_expr_operand() recurse once per level of a
nested expression such as NOT NOT ... x, (((x))), CASE WHEN ... or
abs(abs(...)), and each needed a 1440-byte frame in a release build.
SQLite's LALR parser does not recurse at all, so this is where turso spent
most of its stack on nested expressions.

The frames held the stack slots of every operator and operand, rare or
not, and of the unexpected-token error that peek_expect! built inline at
every use. Now:

- peek_expect! and the "expression tree is too large" checks build their
  errors in cold functions that are never inlined.
- The binary operators that need no further parsing share one arm that
  looks the operator up from the token, instead of one arm each.
- IS, BETWEEN, IN, LIKE, subscripts, and the CASE, CAST, RAISE, EXISTS,
  subquery, parenthesized, bracket-quoted name, and name or function call
  operands are parsed in functions that are never inlined.

parse_expr_inner() now needs 544 bytes and parse_expr_operand() 624.
2026-10-05 15:52:51 +03:00
Iann29
d195edd38c core: implement PRAGMA wal_autocheckpoint
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-*'
2026-10-03 12:17:13 -03:00
Pekka Enberg
9e385a6c3d Remove inferno crate from the dependency tree
inferno is licensed under CDDL-1.0, which is not allowed in the source
tree. It was pulled in only by the flamegraph feature of pprof, which
the core and SQL parser benches used to write a flamegraph during
cargo bench --profile-time.

Drop the profiler from those benches and remove pprof from the core
and parser dev-dependencies. The FTS benchmark tool keeps pprof
without the flamegraph feature, since it writes collapsed stacks
itself and does not depend on inferno.

The codspeed and non-codspeed criterion groups in most benches
differed only by the profiler, so they are merged into one group
where the result is identical.
2026-09-28 17:42:03 +03:00
Pekka Enberg
034b51d62f Update pprof dependency version
Declare pprof once in the workspace dependency table so core, the SQL
parser, and the FTS benchmark tool all use the same version. The core
and parser benches were on 0.14.0 while perf/fts was on 0.15.0, so the
lockfile had two copies. Unify on 0.15.0, which still uses criterion
0.5 for its criterion feature.
2026-09-28 17:34:40 +03:00
roboturso
bd5ddf12e3 sqlite/parser: quote identifiers that start with a digit when rendering names
`ALTER TABLE t RENAME TO "1a"` wrote the new name into every affected
sqlite_schema row as a bare `1a`. A bare identifier cannot start with
a digit, so the rewritten CREATE TABLE and CREATE INDEX text no longer
parsed: the next ALTER in the same session failed with `bad number '1'`
and neither Turso nor SQLite could open the file afterwards.

The rename paths in the VM rebuild the renamed table's name with
`ast::Name::exact`, which has no remembered quote style, and rely on
`Name::as_ident()` to decide whether the name needs quotes. That check
treated any value made only of alphanumerics and underscores as safe
to write unquoted, so a leading digit slipped through. Add the missing
rule to `as_ident()` so a name that starts with a digit is always
double-quoted. Fixing the predicate in the one place all rename paths
(table, index, trigger, foreign key target) render through covers them
together, and it matches SQLite, which stores `CREATE TABLE "1a"(a)`.

Tests: sqlite-sqltests/alter-rename-table-to-digit-leading-name.sqltest
now passes; full sqlite-sqltests conformance run, turso_parser unit
tests and clippy, and ALTER-related core and integration tests pass.

Fixes #8700
2026-09-22 22:14:47 +03:00
roboturso
bcc4e16d88 core/translate: decode blob literals in materialized view plans
A hex blob literal such as x'FF' in a materialized view definition came
back as the text of its hex digits rather than the blob it stands for.
The logical plan builder copied the literal's hex characters straight
into the blob value instead of decoding them, so x'FF' became the two
bytes 0x46 0x46 ("FF") and SELECT hex(...) FROM mv printed 4646.
Earlier this wrong value was also fed back through a hex string that
failed to parse, which is the ParseIntError panic reported in the issue.

Three other places already decoded blob literals correctly, each with
its own copy of the same hex-pair loop. Move that loop into one shared
ast::blob_literal_bytes helper next to blob_literal_hex and use it from
expression emission, index defaults, ALTER TABLE defaults, and the
logical plan builder, so there is a single decoder for every path.

Tests: turso-sqltests/matview_blob_literal.sqltest, all materialized
view sqltests, cargo test -p turso_core blob/literal/incremental tests.

Fixes #7355
2026-09-22 17:06:28 +03:00
Glauber Costa
c340222f60 sqlite/parser: keep GENERATED ALWAYS in rendered schema text
Turso stores schema SQL by re-rendering the statement from the AST, and
the AST did not record whether the user wrote GENERATED ALWAYS AS or the
bare AS form, so the keywords vanished from sqlite_master. SQLite keeps
the original spelling, and tools that round-trip schema text depend on
it.

Record the spelling on the generated-column constraint, emit it from
both renderers (the AST token stream used by RENAME, and the column
metadata renderer used by ADD COLUMN), and only where the user actually
wrote it — bare AS stays bare.

Tests: spelling round-trip coverage through CREATE and the ALTER paths
in gencol.sqltest.

Fixes #6155

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 15:15:48 +00:00
Glauber Costa
f16c853097 sqlite/parser: reject invalid generated-column clauses
SQLite refuses a column that mixes DEFAULT with a generated clause, a
generated clause followed by a type token other than STORED/VIRTUAL, and
more than one generated clause on the same column. Turso's constraint
loop accepted all three, silently swallowing the unknown token and
letting the last generated clause win, so invalid schemas round-tripped
into sqlite_schema.

Guard the constraint loop the same way the existing duplicate
PRIMARY KEY check does, and only consume the trailing STORED/VIRTUAL
identifier when it is one of the two legal spellings. Error messages
match SQLite's, including the asymmetry where DEFAULT-then-AS reports
'error in generated column' but AS-then-DEFAULT reports 'cannot use
DEFAULT on a generated column'.

Tests: rejection coverage in gencol.sqltest plus parser unit coverage
for the accept/reject matrix in CREATE and ALTER forms.

Fixes #7058
Fixes #7059
Fixes #7060

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-15 09:55:15 -04:00
Preston Thorpe
0c6843d300 Merge 'core/fts: merge segments on the write path past a threshold' from Preston Thorpe
## Why
In the segment-registry design (#8517) every flushed statement publishes
one
immutable segment, so without write-path maintenance N single-row
commits
leave N segments behind and read cost degrades without bound. Manual
`OPTIMIZE INDEX` exists, but an index should not need babysitting to
stay
queryable.
## What
After a statement flush publishes a segment, if the visible segment set
exceeds `PRAGMA fts_merge_threshold` (default 32, 0 disables, per
connection) the cursor takes the maintenance lease and stages a merge
**in
the same transaction**. A `Busy` / `WriteWriteConflict` refusal skips
the
merge silently: a writer must never fail because maintenance was
contended —
the merge simply re-arms on the next flushed statement.
Below the threshold a flushed statement pays exactly one atomic load of
a
shared segment-count estimate, so the insert fast path stays scan-free.
The
estimate is a heuristic only (bumped by publishes, reset by merges,
reconciled by every full registry scan); the merge itself always
recomputes
the true visible set from its own snapshot.
Candidacy is tiered, ParadeDB-style (layers at 100KB / 1MB / 100MB /
1GB):
- clean segments merge only within the smallest layer holding at least
two
  of them, so one huge clean segment is not rewritten on every trigger;
- a segment at least half tombstoned is always a candidate — rewriting
it
  reclaims dead space no matter its size.
`OPTIMIZE INDEX` keeps its "compact everything now" semantics, with no
tier
exemptions.
## Concurrency
The merge runs under the existing per-index lease (the merge mutex from
#8517) and the same deleter-admissibility rules as OPTIMIZE, so
concurrent
appenders are unaffected and concurrent deleters are never lost. The
auto-merge's own transaction's deleter registration is exempt from the
admissibility check, so single-connection UPDATE traffic still merges
itself. The `auto_merge_pending` flag survives I/O yields, so the check
resumes exactly once per flushed statement and a yield inside the merge
publication resumes through the ordinary publish path without re-
evaluating
the trigger.
OPTIMIZE under sustained deleter churn is live but contended (7–159
retries
measured); the docs layer of this stack records the retry guidance.

Reviewed-by: Pedro Muniz (@pedrocarlo)
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>

Closes #8611
2026-09-09 12:53:08 -03:00
project-cerebro
747c3f6eb7 sqlite/parser: match existing generated-column DEFAULT error wording
The parser-layer rejection of a DEFAULT clause on a generated column
now uses the same "cannot have a DEFAULT value" wording expected by the
existing `gencol_error_default_virtual` and the new
`gencol_alter_add_column_default_after_generated_rejected` tests in
sqlite/conformance/sqlite-sqltests/gencol.sqltest, and consistent with
the engine-layer error at core/schema.rs:4873.

No behavior change. The symmetric rejection of DEFAULT+AS and AS+DEFAULT
on a single column is unchanged.
2026-09-05 04:55:25 -04:00
project-cerebro
61f167953d sqlite/parser: reject DEFAULT clause on generated columns
SQLite's documented rule is that generated columns may not use
the DEFAULT clause, regardless of constraint order. The parser
previously accepted both:

ALTER TABLE t ADD COLUMN b DEFAULT 5 AS (a+1)
ALTER TABLE t ADD COLUMN b AS (a+1) DEFAULT 5

Track whether DEFAULT and GENERATED/AS have each been seen while
walking a column's constraints and reject the combination in either
order.

Tests cover both ALTER TABLE orderings, both CREATE TABLE orderings,
and the existing skipped sqltest regression.

Fixes #7058
2026-09-05 01:57:39 -04:00
PThorpe92
e4a1a8d01f core/fts: merge segments on the write path past a threshold
Without write-path maintenance, N single-row commits leave N segments
and reads degrade without bound. After a statement flush publishes a
segment, if the visible set exceeds PRAGMA fts_merge_threshold (default
32, 0 disables, per connection) the cursor takes the maintenance lease
and stages a merge in the same transaction; Busy/WriteWriteConflict skip
silently -- writers never fail because maintenance was contended. Below
the threshold a flushed statement pays one atomic load of a shared
segment estimate, keeping the insert fast path scan-free.

Candidacy is tiered (layers at 100KB/1MB/100MB/1GB): clean segments
merge only within a layer holding at least two, and segments at least
half tombstoned are always candidates, so one huge clean segment is not
rewritten on every trigger. OPTIMIZE keeps merging everything. OPTIMIZE
under sustained deleter churn is live but contended (7-159 retries
measured); FTS_REDESIGN.md section 5 documents the retry guidance.

Measured on the churn benchmark: 64 single-row commits 82.0ms off vs
81.5ms on; 256 commits 394ms off vs 371ms on.

Tests: cargo test -p core_tester --features fts --test integration_tests fts_auto_merge
Tests: cargo test -p core_tester --features fts --test integration_tests fts_optimize_succeeds_under_concurrent_update_churn
Tests: cargo check -p turso_core --features fts --benches

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-02 09:37:39 -07:00
Pere Diaz Bou
856e974ed3 feat(mvcc): batch concurrent logical-log commits behind one fsync
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)
2026-09-01 08:41:39 +00:00
Pekka Enberg
2096a3b638 sqlite/parser: report bad parameter names as unrecognized tokens
SQLite marks a parameter with no identifier bytes ("$", "$::") or an
unterminated "(...)" suffix ("$abc(") as TK_ILLEGAL, so its error is
unrecognized token: "$abc(". We reported a Turso-only "bad variable
name" message instead. Report these through UnrecognizedToken, drop
the now-unused BadVariableName variant, and change the UnrecognizedToken
message to SQLite's exact wording, quotes included.

Tests: main-3.2.9, main-3.2.10, main-3.2.13 and bind-11.1 in
sqlite/conformance/upstream now pass, and so does main-3.2.7 (blob
literal with an odd number of hex digits), which already used
UnrecognizedToken and only had the wrong wording.
2026-08-24 12:29:05 +03:00
Pekka Enberg
050d485ce0 sqlite/parser: accept a "(...)" suffix in parameter names like SQLite
TCL array elements reach SQL as `$arr(elem)`. SQLite's tokenizer lets
one "(...)" suffix end a parameter name once at least one identifier
byte has been read; the suffix must be closed and may not contain
whitespace, otherwise the whole thing is an unrecognized token. Copy
that rule so such parameters bind as one name.

The suffix ends the token, so `$a(b)(c)` lexes as the parameter `$a(b)`
followed by `(c)` and fails to parse, as it does in SQLite.
2026-08-20 20:35:36 +03:00
Pekka Enberg
bac04166d7 sqlite/parser: accept "::" in parameter names like SQLite
The upstream TCL suite passes TCL variables into SQL as `$`-parameters,
and the interesting ones are namespace-qualified: `$::ii`, `$ns::var`.
SQLite's tokenizer (sqlite3GetToken, CC_VARALPHA) lets a "::" pair
continue a parameter name anywhere — leading, middle or trailing. Ours
stopped at the first non-identifier byte and failed the statement with
"bad variable name", 3,289 times across the suite (in2, date5,
tkt-38cb5df375, json102).

Copy SQLite's rule: the name is identifier bytes plus "::" pairs, and
needs at least one identifier byte. A `:` starts a parameter when an
identifier byte or a "::" pair follows it (`:name`, `:::name`); any
other `:` stays a standalone colon so slices like `a[1:2]`, `a[:2]` and
`a[1::hi]` lex as before. That is the one place we keep deviating from
SQLite, which has no slice syntax and reads `:2` as a parameter.

Consequence, same as SQLite would lex the bytes: an unspaced slice with
a parameter lower bound, `a[$lo::hi]`, is now the single name `$lo::hi`.
Write `a[$lo : :hi]` or `a[$lo:$hi]`. Nothing in the repo uses the
unspaced spelling.
2026-08-20 20:35:33 +03:00
Pekka Enberg
6804c11db6 sqlite/parser: split eat_var into numbered and named parameter scans
The next commits teach the lexer SQLite's rules for named parameters
("::" in the name and a trailing "(...)" suffix). Moving the `$`, `@`
and `:` arm of eat_var into its own function first keeps that change
to one self-contained loop instead of a diff inside a match arm.

No behavior change.
2026-08-20 20:35:28 +03:00
Claude
b9f79af18d core,parser: add EXPLAIN QUERY PLAN FORMAT=JSON
The machine-readable query plan was only reachable from the Rust API
(Statement::query_plan_json), so users of the CLI, bindings, and drivers
had no way to get it. EXPLAIN QUERY PLAN FORMAT=JSON returns the plan as
one row with one TEXT column (plan_json) holding the whole JSON
document, ready to pipe into tools like the plan visualizer. FORMAT=TEXT
(or no clause) keeps the classic four-column rows, and the statement is
still only prepared, never executed.

FORMAT is not a SQL keyword and no statement can start with a bare
identifier, so the parser can treat it as a soft keyword after QUERY
PLAN with no grammar ambiguity; the syntax mirrors MySQL's EXPLAIN
FORMAT=JSON. Cmd::ExplainQueryPlan and QueryMode::ExplainQueryPlan carry
the requested format, and the JSON mode gets its own one-shot step
function instead of iterating Explain insns row by row.

The JSON format is documented in docs/eqp-json.md.

Tests: parser cases in sqlite/parser/src/parser.rs, end-to-end coverage
in tests/integration/query_processing/test_query_plan_json.rs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011oxKodW4hQ5ZLBmihTuDeU
2026-08-17 15:24:46 -04:00
Pekka Enberg
87ca731e40 core: preserve CHECK source text in errors and rebuilt SQL
SQLite reports an unnamed failed CHECK constraint with the expression's
source text exactly as written between the parentheses, whitespace-trimmed:
CHECK(x<5) fails with `CHECK constraint failed: x<5`. Turso re-rendered
the parsed expression, producing `x < 5`. SQLite also dequotes the
captured text, so a constraint whose text starts with a quoted token is
reported by that token alone (`CHECK("x" < +5)` fails with just `x`).

Capture the between-parentheses text in the CHECK AST and carry it through
schema::CheckConstraint to the constraint-failure description. Turso stores
canonically re-rendered SQL in sqlite_schema, unlike SQLite, which stores the
user's text, so both the canonical formatter and schema rebuilding preserve
the captured text inside CHECK(...). Closed block comments remain intact. If
the source contains a line-comment marker, place the generated closing
parenthesis on a new line so the comment cannot swallow it.

Every path that rewrites a CHECK expression in place, including ALTER TABLE
renames of tables and columns, clears the captured text so stale spelling is
never reported or stored. Those paths fall back to pretty-printing, matching
the re-rendered SQL they store.

The PostgreSQL frontend builds these AST nodes from its own AST without Turso
SQL source text and keeps its pretty-printed messages.

Tests: check_constraint.sqltest covers verbatim text, reopen, names, dequoting,
comments, and ALTER TABLE rewrites.
2026-08-11 13:01:27 +03:00
Pekka Enberg
dc2b3383a4 core: report name collisions on CREATE the way SQLite does
SQLite reports a duplicate CREATE TABLE/VIEW/TRIGGER by echoing the new
object's name token exactly as written, quotes included: `CREATE TABLE
"t2"` fails with `table "t2" already exists`. Duplicate index names are
reported without quotes (`index idx1 already exists`), and a clash
between the index and table namespaces gets its own shape ("there is
already an index named x" / "there is already a table named x"). Turso
stripped quotes everywhere and used its own spellings ("Trigger t
already exists", "Table t already exists" for virtual tables, "Error:
index with name 't' already exists.", and a runtime backstop that
always double-quoted the name).

The parser now remembers bracket quoting in ast::Name (previously
`[t]` lost its brackets and re-rendered double-quoted), so
Name::as_ident can reproduce any quoted token as written. A new
util::identifier_token_for_error wraps that for error messages, and the
schema-level conflict backstop takes the kind of object being created
so it can pick between the "already exists" and "there is already a..."
shapes.

Tests: sqlite/conformance/sqlite-sqltests/already-exists-error-message.sqltest
(9 of 12 cases fail without this change); testing/system/vtab.test
expectations updated to the SQLite spelling.
2026-08-11 12:35:48 +03:00
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
Glauber Costa
3ea5725541 bindings/c: statement introspection, column conversions, and a C API oracle
Implements sqlite3_sql, sqlite3_expanded_sql and sqlite3_stmt_busy
(backing SQLite3Stmt::getSQL() and busy() in PHP's ext/sqlite3), SQLite
conversion semantics for the column accessors, and a randomized
differential oracle for the C API.

Introspection:
- sqlite3_sql: original text, retained on the statement, valid until
  finalize.
- sqlite3_expanded_sql: SQL with each parameter marker replaced by its
  bound value's literal (NULL when unbound). Implemented in core as
  Statement::expanded_sql so any binding can expose it; the text is
  re-tokenized with the lexer, and each TK_VARIABLE resolves its index
  from its own text (?N carries the number, names are looked up, bare ?
  is largest-so-far + 1). Does not reuse Value::exec_quote: SQLite
  renders quote() and expanded SQL differently (X'..' vs x'..' blobs).
- sqlite3_stmt_busy: delegates to the statement's busy state in core.

Column accessors: column_int64/int/double/text/blob/bytes apply SQLite's
conversion table when the requested representation differs from the
stored type, via Value::exec_cast and the SQLite-compatible text
rendering. Converted results are cached per column for pointer
stability; column_blob returns NULL for zero-length results.

C API semantics:
- sqlite3_last_insert_rowid returns int64 per its prototype.
- sqlite3_bind_parameter_name returns NULL for anonymous ? and "?N" for
  numbered markers; numbered markers are tracked by a flag on the AST
  variable and in the parameter table, their "?N" name derived from the
  index on demand, so registering one allocates nothing and prepare cost
  for ?N-heavy statements stays flat. bind_parameter_index("?N")
  resolves, as in SQLite. Returned names
  are cached on the statement (valid until finalize).
- The prepare tail points at the first byte past the terminating ';'.
- sqlite3_data_count returns 0 when no row is available.

Oracle: tests/oracle.rs dlopens the system libsqlite3 and the built
cdylib side by side (verifying the export table via dlsym) and drives
both through identical seeded scenarios, comparing every observable in
lockstep. Failures abort with seed + operation trace;
TURSO_ORACLE_SEED/TURSO_ORACLE_ITERS reproduce and extend. Not
exercised (reference behavior is build-dependent, noted in the oracle):
step after SQLITE_DONE (auto-reset vs SQLITE_OMIT_AUTORESET; core
auto-reset is follow-up work) and long values in expanded SQL
(SQLITE_TRACE_SIZE_LIMIT).

Directed tests in sqlite3_tests.c pin the introspection contracts
byte-for-byte against both libraries; a core unit test covers
expanded_sql.

Numbered parameters remain pattern placeholders: index-method patterns
use ?N to share one captured argument across call sites (an FTS pattern
binds the same query text to fts_score and fts_match), and the
placeholder guards in try_capture_parameters/try_substitute_parameters
accept positional markers (Variable::is_positional). The .NET binding's
missing-parameter message takes its position branch for anonymous
markers, which its test asserts. The oracle is excluded on Windows like
the compat suite: no system SQLite to compare against.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 13:27:31 -05:00
Pekka Enberg
833bb50548 Revert "bindings/c: statement introspection, column conversions, and a C API oracle"
This reverts commit a74680049f. It breaks the shit out of everything.
2026-08-07 18:20:57 +03:00
Glauber Costa
a74680049f bindings/c: statement introspection, column conversions, and a C API oracle
Implements sqlite3_sql, sqlite3_expanded_sql and sqlite3_stmt_busy
(backing SQLite3Stmt::getSQL() and busy() in PHP's ext/sqlite3), SQLite
conversion semantics for the column accessors, and a randomized
differential oracle for the C API.

Introspection:
- sqlite3_sql: original text, retained on the statement, valid until
  finalize.
- sqlite3_expanded_sql: SQL with each parameter marker replaced by its
  bound value's literal (NULL when unbound). Implemented in core as
  Statement::expanded_sql so any binding can expose it; the text is
  re-tokenized with the lexer, and each TK_VARIABLE resolves its index
  from its own text (?N carries the number, names are looked up, bare ?
  is largest-so-far + 1). Does not reuse Value::exec_quote: SQLite
  renders quote() and expanded SQL differently (X'..' vs x'..' blobs).
- sqlite3_stmt_busy: delegates to the statement's busy state in core.

Column accessors: column_int64/int/double/text/blob/bytes apply SQLite's
conversion table when the requested representation differs from the
stored type, via Value::exec_cast and the SQLite-compatible text
rendering. Converted results are cached per column for pointer
stability; column_blob returns NULL for zero-length results.

C API semantics:
- sqlite3_last_insert_rowid returns int64 per its prototype.
- sqlite3_bind_parameter_name returns NULL for anonymous ? and "?N" for
  numbered markers; the parser records "?N" as the parameter's name,
  which also makes bind_parameter_index("?N") resolve. Returned names
  are cached on the statement (valid until finalize).
- The prepare tail points at the first byte past the terminating ';'.
- sqlite3_data_count returns 0 when no row is available.

Oracle: tests/oracle.rs dlopens the system libsqlite3 and the built
cdylib side by side (verifying the export table via dlsym) and drives
both through identical seeded scenarios, comparing every observable in
lockstep. Failures abort with seed + operation trace;
TURSO_ORACLE_SEED/TURSO_ORACLE_ITERS reproduce and extend. Not
exercised (reference behavior is build-dependent, noted in the oracle):
step after SQLITE_DONE (auto-reset vs SQLITE_OMIT_AUTORESET; core
auto-reset is follow-up work) and long values in expanded SQL
(SQLITE_TRACE_SIZE_LIMIT).

Directed tests in sqlite3_tests.c pin the introspection contracts
byte-for-byte against both libraries; a core unit test covers
expanded_sql.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 16:49:28 -05:00
Pekka Enberg
f5c823bc43 Merge 'sqlite/parser: match SQLite error for ORDER BY before compound operator' from roboturso
When an ORDER BY or LIMIT clause appears before a compound operator,
as in `SELECT 1 ORDER BY 1 UNION SELECT 2`, the parser stopped the
compound-select loop at the clause and then failed on the leftover
operator token with a generic `near "UNION": syntax error`. SQLite
instead reports `ORDER BY clause should come after UNION not before`,
so error-message compatibility tests failed.
After parsing a select's ORDER BY and LIMIT clauses, peek at the next
token: a compound operator there can only mean one of those clauses cut
the compound-select loop short, so report SQLite's message instead.
As in SQLite, ORDER BY takes precedence over LIMIT when both are
present and UNION ALL is named in full.
This removed the last failures in the upstream conformance files
selectE.test and subquery2.test, so promote both from "fail" to "pass"
in sqlite/conformance/upstream/all.test.
Tests: sqlite-sqltests/compound-select-order-by-before-operator-
error.sqltest,
tclsh sqlite/conformance/upstream/all.test (selectE and subquery2 now
blessed), cargo test in sqlite/parser, full sqltest corpus via
make -C sqlite/conformance run-rust.
Fixes #8201

Closes #8208
2026-08-06 15:39:11 +03:00
Pekka Enberg
4a506afaab Merge 'testing/differential: make differential fuzzer reliable enough to run in CI, and run it in CI' from Jussi Saurio
# Make the differential fuzzer reliable enough to run in CI, and run it
in CI
## What's the differential fuzzer bro
It runs generated SQL against Turso and SQLite, then compares the
results and database state and expects them to match.
## The Problem ™️
 We haven't been running the fuzzer in CI because it always fails
somewhere.
## The Solution ©️
This PR fixes that in two ways:
- **Fix Turso bugs.** Some differences are real Turso bugs. They are
fixed here, each with a test.
- **Make the fuzzer avoid SQL with more than one allowed answer.** Some
SQL is allowed to give different results in different engines. Comparing
those results tells us nothing, so the fuzzer stops generating them.
## Bonus features
It also adds tooling:
- Statement weight profiles, so CI covers several statement mixes
instead of one.
- Automatic minimization of failures: every failure now comes with a
small reproduction script.
- The SQLite TCL conformance runner now runs every test file in its own
process, so one crashing file can't kill the whole run — and seven
previously known-bad files now fully pass and are pinned green.
---
## Turso bugs fixed
**A TEMP trigger stopped running after its table was renamed.**
```sql
CREATE TABLE t(x);
CREATE TEMP TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO log VALUES (1); END;
ALTER TABLE t RENAME TO t2;
INSERT INTO t2 VALUES (1);
-- SQLite: trigger fires. Turso: trigger never fired again.
```
Turso updated the stored SQL but kept the trigger under the old table
name in memory. The rename now updates both.
**`DROP COLUMN` missed trigger references written as `alias.column`.**
```sql
CREATE TABLE t(a, b);
CREATE TRIGGER tr BEFORE UPDATE ON t WHEN t.b > 0 BEGIN SELECT 1; END;
ALTER TABLE t DROP COLUMN b;
-- SQLite: error "no such column: t.b". Turso: allowed the drop.
```
References spelled `t.b` or `main.t.b` were not checked. Such drops are
now rejected.
**A `BEFORE INSERT` trigger could make the outer insert pick a wrong
automatic rowid.**
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, v);
CREATE TRIGGER tr BEFORE INSERT ON t BEGIN INSERT INTO t VALUES (100, 'x'); END;
INSERT INTO t(v) VALUES ('a'), ('b');
```
The outer insert chose its automatic rowid from a stale cursor position,
as if the trigger's row didn't exist. Rowid lookup now seeks to the
actual largest rowid first.
**An unqualified TEMP trigger could forget which database its table came
from.**
```sql
CREATE TABLE t(x);                 -- in main
CREATE TEMP TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
CREATE TABLE aux.t(x);             -- same name in aux
DROP TABLE main.t;
INSERT INTO aux.t VALUES (1);
-- Turso: the temp trigger could fire on aux.t, or survive the drop of main.t.
```
Turso now remembers the correct database.
**`UPDATE` skipped `NOT NULL` checks when the table's only trigger was
`AFTER UPDATE`.**
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, n TEXT NOT NULL);
INSERT INTO t VALUES (1, 'keep');
CREATE TRIGGER tr AFTER UPDATE ON t BEGIN SELECT 1; END;
UPDATE t SET n = NULL;
-- SQLite: error "NOT NULL constraint failed". Turso: stored NULL.
```
The check is deferred so `BEFORE` triggers can run first. But it was
skipped for *any* trigger and only re-added when a `BEFORE` trigger
existed, so a table with only an `AFTER` trigger lost the check
entirely.
**`UPDATE OR FAIL` inside a trigger rolled back too much.**
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY);
INSERT INTO t VALUES (-1);
CREATE TRIGGER tr BEFORE INSERT ON t BEGIN
  UPDATE OR FAIL t SET id = 807742 WHERE (SELECT id FROM t LIMIT 1);
END;
INSERT INTO t VALUES (1), (2);
-- Both engines report a UNIQUE error.
-- SQLite table afterwards: {1, 807742}. Turso: {-1} — everything rolled back.
```
`OR FAIL` means: keep the rows already changed. That worked in a plain
statement, but when the conflict happened inside a trigger, Turso
applied the outer statement's rollback instead. SQLite keeps the earlier
changes; now Turso does too.
**`UPDATE ... RETURNING` showed values written by the `AFTER` trigger.**
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, val INTEGER);
INSERT INTO t VALUES (1, 10);
CREATE TRIGGER tr AFTER UPDATE ON t BEGIN
  UPDATE t SET val = val + 100 WHERE id = NEW.id;
END;
UPDATE t SET val = 20 WHERE id = 1 RETURNING val;
-- SQLite returns 20 (what the UPDATE wrote). Turso returned 120.
-- The final table holds 120 in both engines.
```
Turso now fires `AFTER` triggers after RETURNING has captured the row.
Two existing tests pinned the old behavior as intentional; they now
expect SQLite's behavior.
**`x IN ((SELECT ...))` returned NULL for an empty subquery.**
```sql
SELECT 5 IN ((SELECT 1 WHERE 0));
-- SQLite: 0. Turso: NULL.
```
Turso parsed the double parentheses as a value list containing one
scalar subquery, and an empty scalar subquery is NULL. SQLite reads it
the same as `x IN (SELECT ...)`: an empty subquery means "not in", never
NULL.
**`OR REPLACE` stored a NULL default into a `NOT NULL` column.**
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, c BLOB NOT NULL DEFAULT (NULL));
INSERT INTO t VALUES (1, X'AA');
UPDATE OR REPLACE t SET c = NULL;
-- SQLite: error "NOT NULL constraint failed". Turso: stored NULL.
```
`OR REPLACE` fixes a `NOT NULL` violation by swapping in the column
default — but the default can itself be NULL. Turso never re-checked the
swapped-in value. Now it does.
**`EXISTS` kept `ORDER BY` and `DISTINCT` that SQLite throws away.**
`EXISTS` only asks whether a row comes back, so SQLite deletes `ORDER
BY` and `DISTINCT` inside it. Turso kept them, which showed up in two
ways:
```sql
-- 1. An ORDER BY term that fails at runtime:
SELECT EXISTS (SELECT x FROM t ORDER BY ABS(-9223372036854775807 - 1));
-- SQLite: 1 (the term is never evaluated). Turso: error "integer overflow".

-- 2. DISTINCT changing what OFFSET counts (t has rows 1, 1, 2):
SELECT EXISTS (SELECT DISTINCT x FROM t ORDER BY x LIMIT 5 OFFSET 2);
-- SQLite: 1 (OFFSET skips 2 of 3 plain rows). Turso: 0 (OFFSET skipped both distinct rows).
```
Turso now drops both clauses in `EXISTS`. Name errors in the dropped
clauses still surface, matching SQLite.
**A backward scan with a text bound returned a phantom row from an empty
table.**
```sql
CREATE TABLE b(id INTEGER PRIMARY KEY);
SELECT 1 FROM b WHERE id <= '' ORDER BY id DESC;
-- SQLite: no rows. Turso: one row. The table is empty.
```
Every integer sorts before every text value, so `id <= ''` is true for
all rows and the seek turns into "jump to the last row". On an empty
table there is no last row, but Turso reported the seek as successful
anyway, and the scan emitted one garbage row. Found by this PR's own CI
setup: the `ddl` profile hit it, and the minimizer cut the failure down
to a two-line reproduction on its own.
**An index seek ignored a subquery's column type and compared an integer
as text.**
```sql
CREATE TABLE a(t TEXT UNIQUE);
INSERT INTO a VALUES ('4x');
SELECT 1 FROM a WHERE t < (SELECT 602393 AS i);
-- SQLite: no rows (the integer sorts before all text).
-- Turso: one row ('4x' < '602393' compared as strings).
```
When both sides of a comparison have a type, and one is numeric, the
comparison is numeric — so the integer keeps its type and sorts before
the text. Turso's optimizer couldn't see the subquery's INTEGER type
when building the index seek key, treated it as typeless, and let the
TEXT column win: the seek converted the integer to text and string-
compared. Only the index seek was wrong; a full table scan compared
correctly. Also found by this PR's own CI setup: the `writes` profile
hit it as a DELETE that removed a row SQLite kept, and the minimizer
reduced it to five lines.
**An aggregate over an outer column ran against the wrong table.**
```sql
CREATE TABLE t(a); INSERT INTO t VALUES (1), (2), (3);
SELECT (SELECT count(t.a)) FROM t;
-- SQLite: one row, 3. Turso: three rows, 1 1 1.
```
An aggregate whose argument references a column from an outer query
belongs to that outer query, not the subquery it is written in — the
outer query becomes an aggregate query and collapses to one row. Turso
bound every aggregate to the innermost query it was written in, so
`count(t.a)` counted the subquery's own rows (a single correlated row)
instead of the outer query's. The fix mirrors SQLite name resolution:
when a subquery resolves an aggregate whose columns belong to the
enclosing query, it moves the aggregate up to that query during
resolution. Found by the `balanced` and `writes` profiles.
**A CASE with no ELSE was treated as never producing NULL.**
```sql
CREATE TABLE t(k INTEGER PRIMARY KEY, c REAL);
INSERT INTO t VALUES (1, -47175.8);
CREATE INDEX i ON t(c);
SELECT 1 FROM t WHERE CASE WHEN '' THEN 1 END <= c;
-- SQLite: no rows. Turso: one row.
```
An index range seek guards its seek key with an "is it NULL?" jump,
because a NULL comparison is never true. Turso decided whether to emit
that guard with a helper that wrongly reported a CASE with no ELSE as
never-NULL — but such a CASE yields NULL when no WHEN matches. The seek
then ran on a NULL key and returned rows. A CASE is non-null only when
it has an ELSE and every branch is non-null. Found by the `balanced`
profile.
**A DELETE trigger inherited an outer `OR REPLACE` it should not have.**
```sql
CREATE TABLE t(pk INTEGER PRIMARY KEY, x);
CREATE TABLE t2(pk INTEGER PRIMARY KEY, y);
INSERT INTO t VALUES(1,0); INSERT INTO t2 VALUES(1,0);
CREATE TRIGGER t2_bd BEFORE DELETE ON t2 FOR EACH ROW BEGIN
  INSERT INTO t2(pk,y) VALUES(1,1),(1,2); END;
CREATE TRIGGER t_au AFTER UPDATE ON t FOR EACH ROW BEGIN
  DELETE FROM t2 WHERE pk=1; END;
UPDATE OR REPLACE t SET x=9;
-- SQLite: UNIQUE constraint failed: t2.pk. Turso: silently succeeded.
```
A statement's `OR REPLACE` policy propagates into the triggers it fires,
but a DELETE is an exception: it always fires its triggers with the
default (ABORT) policy. Turso propagated the outer REPLACE through a
delete-fired trigger, so a plain INSERT that duplicated a key was
quietly resolved instead of raising the error SQLite raises. Found by
the `triggers` profile; reduced from a three-trigger cascade to the two-
trigger case above.
**A trigger's `WHEN` reused a stale subquery result on every firing
after the first.**
```sql
CREATE TABLE tt (pk INTEGER PRIMARY KEY, d INTEGER);
CREATE TRIGGER trg AFTER INSERT ON tt FOR EACH ROW
  WHEN EXISTS (SELECT 1 FROM tt WHERE EXISTS (SELECT 1 FROM tt WHERE d) IN (1))
  BEGIN INSERT INTO tt (pk, d) VALUES (1, 0); END;
INSERT INTO tt (pk, d) VALUES (1, 0), (2, 1), (3, 1);
-- SQLite: UNIQUE constraint failed (the WHEN turns true at row 2, the body re-inserts pk=1).
-- Turso: silently succeeded (the WHEN stayed false for every row).
```
A trigger body is inlined and re-run once per inserted row. An
uncorrelated subquery is normally evaluated once and its result cached —
but the cache is only valid within one run of the query. Turso kept the
cache across trigger firings, so the inner `EXISTS` — false at the first
firing, when no `d = 1` row exists yet — was reused as false forever,
even after later rows made it true. The fix clears that "already
evaluated" state at the start of each firing, so each firing re-
evaluates against the current table. This matches SQLite, which gives
every trigger firing a fresh start. It was not limited to `EXISTS`: a
nested `IN (SELECT …)`, whose lookup table is also built once, went
stale the same way. Found by the `triggers` profile; reduced from a
large nested subquery to the five lines above.
## Harness fix 1: only run statements both engines can prepare, using
EXPLAIN
The flow is:
1. Generate a statement.
2. Run `EXPLAIN` in both engines.
3. If either engine rejects it, run it in neither.
4. Otherwise, run it in both and compare the results.
5. After writes, compare the database contents and schema, including
triggers.
Without this check, a statement accepted by only one engine could change
only one database and spoil every later comparison. `EXPLAIN` checks
acceptance without changing either database.
- Skipped statements are reported separately from failures.
- We may miss some real accept/reject bugs this way. That's a fair
tradeoff: those can be tested elsewhere, while this fuzzer is most
useful for comparing execution after both engines accept the same
statement.
## Harness fix 2: avoid updates where row order decides the result
```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, value INTEGER UNIQUE);
INSERT INTO t VALUES (1, 10), (2, 20);
UPDATE OR IGNORE t SET value = 30;
-- Whichever row is visited first gets 30. Both answers are allowed.
```
`UPDATE OR FAIL` has the same problem: it keeps the rows changed before
the conflict, so the survivors depend on visit order.
`UPDATE ... FROM` has a related one:
```sql
UPDATE t SET v = s.val FROM s WHERE s.k = t.id;
-- If several s rows match one t row, either engine may pick any of them.
-- Turso often scans s through an index while SQLite scans the table,
-- so they pick different rows.
```
What the generator does now:
- `UPDATE OR IGNORE` and `UPDATE OR FAIL` are not generated. `UPDATE OR
REPLACE`, `OR ABORT`, and `OR ROLLBACK` still are — their results don't
depend on visit order.
- `UPDATE ... FROM` is limited to one source table, and the generator
writes `NOT INDEXED` on the target and the source. That forces a plain
table scan in both engines, so they visit rows in the same order and
pick the same matching row.
- Joins and self-joins in `UPDATE ... FROM` are not generated. `NOT
INDEXED` only controls how a table is scanned; Turso may still build a
temporary index to run a join, and then the match order differs again.
- Subquery sources are not generated either, because `NOT INDEXED`
cannot be written on a subquery.
This loses some random coverage. It is the price of a fuzzer that only
flags real differences. These forms can still be covered by focused
tests where the expected result is known.
## Harness fix 2b: make scalar subqueries pick a deterministic row
A scalar subquery carries `LIMIT 1`, and both engines must pick the same
row for the comparison to mean anything. Two generated shapes left the
pick to engine scan order:
```sql
-- Sort key can tie: rows with equal k are ordered by scan order.
(SELECT v FROM t ORDER BY k DESC LIMIT 1)

-- DISTINCT collapse: which duplicate's ORDER BY key survives is the
-- engine's choice.
(SELECT DISTINCT v FROM t ORDER BY k LIMIT 1)

-- A constant ORDER BY term ties everything.
(SELECT v FROM t ORDER BY REPLACE('a', 'b', 'c') LIMIT 1)
```
What the generator does now:
- ORDER BY terms must reference a column; constant terms are replaced
with a column reference.
- Scalar subqueries get the table's primary key appended as a final
ORDER BY tiebreaker. Grouped ones order by every GROUP BY expression
instead — groups are distinct combinations of those, so that is already
a total order.
- Scalar subqueries no longer use DISTINCT; no tiebreaker can be added
through the deduplication.
## Harness fix 2c: generate blob literals as valid UTF-8
```sql
SELECT HEX(CAST(X'96' AS TEXT));
-- SQLite: 96 (text is a plain byte string; the byte passes through).
-- Turso:  EFBFBD (text is a Rust string; the invalid byte becomes U+FFFD).
```
This is a real, documented Turso limitation (see the new Limitations
section in COMPAT.md), not fuzzer noise: Turso's text type must be valid
UTF-8, and blobs reach text through many doors — `CAST`, `UPPER`,
`TRIM`, `REPLACE`, `||`. The fuzzer hit it as an UPDATE whose WHERE was
`HEX(CAST(<blob> AS TEXT))`: the hex string starts with a digit in
SQLite (truthy) and with 'E' in Turso (falsy), so one engine updated
every row and the other none.
The generator now produces blob bytes from printable ASCII, so every
blob is valid UTF-8 and both engines see the same characters. Deciding
whether Turso should store text as raw bytes like SQLite is a separate
design question.
## Harness fix 3: use matching column types in compound queries
```sql
WITH values_cte(x) AS (
  SELECT real_column FROM real_table
  UNION ALL
  SELECT integer_column FROM integer_table
)
SELECT x, typeof(x) FROM values_cte;
-- SQLite may take the type from either arm: 7.0 as REAL or 7 as INTEGER.
```
The generator now uses matching declared types in every arm. This keeps
`UNION`, `UNION ALL`, `INTERSECT`, and `EXCEPT` coverage while giving
the fuzzer one answer to compare.
## Harness fix 4: don't rename tables or columns when SQLite would re-
check the schema
SQLite re-resolves *every* stored index and trigger during a table
rename, column rename, or column drop. Turso does not, so it can accept
a rename that SQLite rejects. Two schemas trigger this.
**A trigger that uses a table that was dropped earlier.** SQLite allows
dropping a table a trigger still uses:
```sql
CREATE TRIGGER source_trigger AFTER INSERT ON source BEGIN
  INSERT INTO log VALUES (new.x);
END;
DROP TABLE log;   -- fine in both engines; the trigger errors when it next runs
```
A later rename then fails in SQLite (it re-checks the now-broken
trigger) but can succeed in Turso.
- The fuzzer knows which table owns a trigger, but not every table used
inside its body.
- So it cannot tell whether an earlier drop broke a remaining trigger.
**A TEMP table shadowing a permanent table of the same name.** SQLite
resolves the shared name to the temp table, so re-checking an index on
the permanent table fails against the temp table, which lacks the
column:
```sql
CREATE TABLE a(id INTEGER PRIMARY KEY, c INTEGER);
CREATE UNIQUE INDEX ia ON a(c);
CREATE TEMP TABLE a(x INTEGER PRIMARY KEY);   -- shadows main.a, no column c
CREATE TABLE b(z);
ALTER TABLE b RENAME TO b2;   -- unrelated rename
-- SQLite: error "error in index ia after rename: no such column: c". Turso: succeeds.
```
What the generator does now:
- It avoids table/column renames and column drops whenever any trigger
exists, or any table name is shadowed across database scopes. `ADD
COLUMN` stays enabled.
- Focused tests still cover renames with valid schemas.
## Harness fix 5: don't generate `PRAGMA foreign_key_list('some_table')`
before a table exists
The fuzzer run would abort during SQL generation because there were no
tables to choose from.
## Harness fix 6: skip statements over 64 KiB
```text
Statement skipped because it is 367502 bytes; the limit is 65536 bytes
```
A generated expression can branch into several subqueries at each level,
and occasionally the result is hundreds of kilobytes of SQL. Preparing
that recurses deep enough to blow the process stack before either engine
can return an error. Statements over 64 KiB are now skipped and counted
separately. They add almost no coverage.
The fuzzer also runs on a thread with a 256 MiB stack: debug-build
parser frames are large enough that even a statement inside Turso's
expression depth limit could overflow the default 8 MiB stack.
Statements over the depth limit still get the parser's clean "expression
tree is too large" error and are skipped. (The engine itself still can't
prepare near-limit expressions on a default thread in debug builds; that
needs its own parser fix.)
## Harness fix 7: print nested negation with a space
```sql
SELECT --5;    -- "--" starts a comment; the rest of the line is gone
SELECT - -5;   -- what the generator now prints
```
The SQL printer wrote nested minus as `--value`, silently turning the
rest of the statement into a comment.
## New: statement weight profiles
The fuzzer used one fixed mix of statement types, so every run stressed
the same things. A new `--profile` flag picks a named mix:
- `balanced` — the old default: mostly reads and writes, a little DDL
- `ddl` — heavy table, index, and alter churn
- `triggers` — heavy trigger creation, so triggers fire often
- `writes` — heavy insert/update/delete, for constraint and conflict
paths
The profiles are fixed weight tables, not random, so a failing run
reproduces with the same `--seed` and `--profile`. Most of the bugs
above were found by the heavier mixes; the old default mix never hit
them.
## New: failures come with a small reproduction
When a comparison fails, the fuzzer now:
1. Writes `turso-state.sql` and `sqlite-state.sql` — scripts that
recreate each engine's full state (all tables and rows, including temp
and attached) plus the failing statement.
2. Shrinks the failing statement using the SQL parser: parse it,
simplify one AST node — drop a clause (WHERE, LIMIT, an ORDER BY term, a
select column, a CTE, a join), or replace an expression with `1`, `''`,
or one of its own children — and print the tree back to SQL. Every
candidate is valid SQL, so no time is wasted on candidates that don't
parse.
3. Deletes every state line the shrunken statement doesn't need.
4. Writes the result to `minimized.sql`.
A change is kept only if the same failure still happens — the same
engine failing with the same error, or the same kind of result
difference. That stops the shrinking from wandering onto a different
bug.
In practice this turns a 10 KB statement on top of 200 setup statements
into a repro of a few lines. For example, the `EXISTS` bug above was
found as a 10,610-byte subquery; shrinking it exposed the one load-
bearing expression:
```sql
-- before: 10,610 bytes of nested CASE/EXISTS/aggregate expressions
-- after:
SELECT EXISTS (SELECT x FROM t ORDER BY ABS(-9223372036854775807 - 1));
```
## Enable the differential fuzzer in CI
The fuzzer runs as a matrix over the four profiles, but a random seed on
every run would make it non-deterministic: a pull request could go red
because of a newly generated statement unrelated to its change, and a
green run wouldn't promise the next one passes. So CI runs it two ways:
- **Pull requests** run a fixed set of seeds per profile. The generated
SQL is identical every time, so a green run stays green and any failure
blocks the merge and reproduces exactly:
  ```bash
  cargo run -p differential-fuzzer --bin differential_fuzzer -- \
    --seed <seed> --profile <profile> -n 1000
  ```
- **Pushes to main** additionally run random seeds, so new SQL keeps
turning up divergences without gating unrelated pull requests:
  ```bash
  cargo run -p differential-fuzzer --bin differential_fuzzer -- \
    --profile <profile> -n 1000 loop 10
  ```
A failure prints its seed and profile, which reproduce it locally. The
fixed seed set is a green baseline on this branch; it widens as more
divergences are fixed.
## TCL conformance: crash-proof runner, seven files blessed
The engine fixes above made previously-failing upstream SQLite tests
pass, which surfaced two things in the TCL conformance suite.
**Each test file now runs in its own process.** Before, `all.test`
sourced every file into one tclsh process. A file that hard-crashed the
engine — a segfault, a stack overflow, the OOM killer — took the whole
run down with it: no summary, no hint of which file died or why. Now
every file runs as a separate tclsh process, so:
- A crash is contained to its own file. The runner reports `CRASH in
<file>.test: killed by signal SIGSEGV` (the signal tells apart a stack
overflow, a panic, and an OOM kill), keeps going, and still prints the
full summary.
- Test files can no longer leak state into each other, so each file's
result reflects that file alone.
**Seven known-bad files now fully pass and are blessed.** The suite
marks each file `pass` (must stay green) or `fail` (known-bad, failures
tolerated) — and it fails the run if a known-bad file goes fully green,
so the known-bad list only ever shrinks. This branch tripped exactly
that check:
- `tkt3731` passes because of the engine fixes in this PR.
- `rowvalue2`, `rowvalueA`, `tkt-c694113d5`, `tkt-d11f09d36e`,
`tkt3992`, and `walbig` pass once files stop leaking state into each
other.
All seven are now marked `pass`, so any future failure in them fails CI.

Closes #8115
2026-08-06 15:10:03 +03:00
Pekka Enberg
7140860659 Merge 'core/translate: route CREATE TEMP VIEW to the temp schema' from roboturso
The parser set temporary=true on Stmt::CreateView, but the dispatch in
translate_inner destructured it away with `..`, so a temp view was
created as a regular persistent view in the main schema. A user asking
for a session-scoped view durably polluted the shared sqlite_schema.
Wire the flag through to translate_create_view and resolve temp views
to TEMP_DB_ID, the same way translate_create_table handles temp tables.
The read path already searches temp before main and the temp schema is
per-connection, so lookup and drop-on-close need no extra work.
Two adjacent gaps had to close for temp views to behave like SQLite:
- translate_drop_view resolved unqualified names straight to main, so
  DROP VIEW could never find a temp view. Use the temp-first search
  order (resolve_existing_table_database_id_qualified), matching
  DROP TABLE.
- The parser now rejects CREATE TEMP VIEW with a database name other
  than "temp" ("temporary table name must be unqualified"), mirroring
  parse_create_table and SQLite.
Tests: sqlite-sqltests/temp-view.sqltest regression test; new DROP VIEW
coverage in sqlite-sqltests/views.sqltest; full sqlite-sqltests suite,
cargo test -p turso_core -p turso_parser -p core_tester all pass.
Fixes #8175

Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>

Closes #8176
2026-08-06 14:27:13 +03:00
roboturso
4b0a56455e core/translate: route CREATE TEMP VIEW to the temp schema
The parser set temporary=true on Stmt::CreateView, but the dispatch in
translate_inner destructured it away with `..`, so a temp view was
created as a regular persistent view in the main schema. A user asking
for a session-scoped view durably polluted the shared sqlite_schema.

Wire the flag through to translate_create_view and resolve temp views
to TEMP_DB_ID, the same way translate_create_table handles temp tables.
The read path already searches temp before main and the temp schema is
per-connection, so lookup and drop-on-close need no extra work.

Two adjacent gaps had to close for temp views to behave like SQLite:

- translate_drop_view resolved unqualified names straight to main, so
  DROP VIEW could never find a temp view. Use the temp-first search
  order (resolve_existing_table_database_id_qualified), matching
  DROP TABLE.
- The parser now rejects CREATE TEMP VIEW with a database name other
  than "temp" ("temporary table name must be unqualified"), mirroring
  parse_create_table and SQLite.

Tests: sqlite-sqltests/temp-view.sqltest regression test; new DROP VIEW
coverage in sqlite-sqltests/views.sqltest; full sqlite-sqltests suite,
cargo test -p turso_core -p turso_parser -p core_tester all pass.

Fixes #8175
2026-08-06 11:33:32 +03:00
Jussi Saurio
417b371140 core/parser: treat a parenthesized subquery in IN as subquery membership
`x IN ((SELECT ...))` parsed as a value list holding one scalar subquery, so
an empty subquery made the whole IN evaluate to NULL. SQLite treats a single
(possibly nested) parenthesized bare SELECT on the right of IN as subquery
membership, exactly like `x IN (SELECT ...)`, where an empty subquery yields 0
(or 1 for NOT IN), never NULL.

When the IN value list is a single bare subquery, emit InSelect instead of
InList. A list of two or more values, or a subquery embedded in a larger
expression, stays a value list.

Tests: sqlite-sqltests/in-parenthesized-subquery.sqltest (cross-checked
against sqlite3 3.53.3)
2026-08-06 08:30:11 +03:00
roboturso
0f27dd6f76 sqlite/parser: match SQLite error for ORDER BY before compound operator
When an ORDER BY or LIMIT clause appears before a compound operator,
as in `SELECT 1 ORDER BY 1 UNION SELECT 2`, the parser stopped the
compound-select loop at the clause and then failed on the leftover
operator token with a generic `near "UNION": syntax error`. SQLite
instead reports `ORDER BY clause should come after UNION not before`,
so error-message compatibility tests failed.

After parsing a select's ORDER BY and LIMIT clauses, peek at the next
token: a compound operator there can only mean one of those clauses cut
the compound-select loop short, so report SQLite's message instead.
As in SQLite, ORDER BY takes precedence over LIMIT when both are
present and UNION ALL is named in full.

This removed the last failures in the upstream conformance files
selectE.test and subquery2.test, so promote both from "fail" to "pass"
in sqlite/conformance/upstream/all.test.

Tests: sqlite-sqltests/compound-select-order-by-before-operator-error.sqltest,
tclsh sqlite/conformance/upstream/all.test (selectE and subquery2 now
blessed), cargo test in sqlite/parser, full sqltest corpus via
make -C sqlite/conformance run-rust.

Fixes #8201
2026-08-05 17:40:19 +03:00
roboturso
15e689343b core: implement PRAGMA count_changes
PRAGMA count_changes was not recognized at all, so it silently did
nothing. In SQLite, with this pragma on, each INSERT, UPDATE and DELETE
returns one row with the number of rows it changed.

Add a CountChanges pragma name and a per-connection flag, and a new
ChangeCount opcode that writes the number of rows the current statement
has changed into a register. When the pragma is on, top-level
INSERT/UPDATE/DELETE programs end with ChangeCount + ResultRow, using
SQLite's column names ("rows inserted"/"rows updated"/"rows deleted").
The count comes from the VM's per-statement change counter, which
already excludes trigger and foreign-key-action changes because those
run in subprograms, so the returned value matches changes(). Trigger
bodies, FK actions, nested statements and statements with RETURNING
never return count rows, matching SQLite.

This was the last gap in the upstream insert2.test conformance file, so
enable it in sqlite/conformance/upstream/all.test (29/29 tests pass).

Tests: sqlite/conformance/sqlite-sqltests/pragma-count-changes.sqltest,
upstream insert2.test via tclsh all.test, and differential checks
against sqlite3 covering INSERT..SELECT, OR IGNORE, zero-row UPDATE,
full-table DELETE, triggers, RETURNING and FK cascades.

Fixes #8203
2026-08-05 11:24:28 +03:00
Claude
03c525b8e1 core: support NULLS FIRST/LAST in table PRIMARY KEY constraints
A table-level PRIMARY KEY definition uses the same sorted-column
grammar as CREATE INDEX, so the clause now flows into the automatic
primary key index instead of being rejected: UniqueSet carries a
per-column NULLS list parallel to its collation overrides, and
automatic_from_primary_key stamps it onto the index columns, after
which ordering elision, placement-aware range seeks, the min/max fast
path and unique enforcement all apply to the primary key index through
the existing machinery. Rowid tables keep the SQLite rule that a
non-INTEGER primary key admits NULLs, and multiple NULL keys stay
distinct, so the declared placement is observable there; on rowid-alias
and WITHOUT ROWID primary keys the key columns are NOT NULL and the
clause is accepted but has no observable effect. Table UNIQUE
constraints and UPSERT conflict targets still reject the clause, and
the differential test asserting PRIMARY KEY rejection is removed since
the behavior now intentionally diverges from SQLite.

Tests: turso-sqltests cover schema round-trip, sort elision through
the automatic index, range seeks, min/max, NULL-key distinctness,
row maintenance with integrity check, upsert targeting, and the inert
rowid-alias and WITHOUT ROWID cases, in default and MVCC modes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VpGXUdx42eQrq5ZXEqCRNz
2026-08-03 19:19:40 +00:00
Claude
c456f8920c introduce method
core: implement NULLS FIRST/LAST in indexes

CREATE INDEX now honors a per-column NULLS FIRST/LAST clause. The
declared placement is stored on IndexColumn and flows into the index
key metadata, moving the NULL block to the requested end of the index
b-tree: record comparisons apply the NULLS order instead of the
ASC/DESC reversal whenever exactly one side of a key comparison is
NULL, matching the sorter's cmp_with_sort semantics. The CREATE INDEX
refill sorter receives the same NULLS order so bulk-loaded and
row-at-a-time maintained indexes agree on the physical layout, and
compare_immutable applies it too so MVCC in-memory index ordering
stays consistent with the b-tree.

The optimizer consumes an ORDER BY term against an index column by
comparing the requested placement (explicit, or the ASC/DESC default)
with the placement the chosen scan direction delivers, so sort elision
works with non-default indexes in both directions and is refused on
any mismatch, including default ORDER BYs over non-default indexes.
The same requested-versus-delivered rule fixes subquery intrinsic
order matching for reversed scans. Range constraints only become seek
keys on index columns with the default placement, because seek bound
emission skips or terminates at the NULL block based on the default
layout; equality seeks are placement-agnostic and remain allowed, so
non-default columns still fall back to a scan with a residual filter
rather than leaking or dropping the NULL block.

Tests: turso-sqltests/create-index-nulls-first-last.sqltest covers
schema round-trip, scan and seek correctness, sort elision and its
guards, min/max, unique enforcement, and index maintenance; passes in
both default and MVCC modes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VpGXUdx42eQrq5ZXEqCRNz
2026-08-03 19:12:53 +00:00
martian56
b56f7b8657 parser: preserve blob literal prefix case
pragma_table_info's dflt_value rendered a blob-literal column default in
fixed uppercase, so a default of x'00' was reported as X'00'. SQLite
preserves the literal's as-typed case.

The lexer dropped the x/X prefix and quotes, keeping only the hex payload,
and the formatter re-emitted a hardcoded uppercase prefix. Keep the full
literal text (including the prefix and quotes) in Literal::Blob, add a
blob_literal_hex helper to recover the payload where bytes are needed, and
emit the stored text verbatim.

Fixes #7554

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 13:41:00 +04:00
roboturso
8011555c64 sqlite/parser: bound expression depth to prevent translator stack overflow
Deeply nested or very wide expression trees could reach the recursive
translator/optimizer and overflow the native stack (issue #5071).

Add a fixed expression-depth limit in the parser, our equivalent of
SQLite's SQLITE_MAX_EXPR_DEPTH but lower, since our translator uses larger
stack frames per nesting level. The limit is enforced in two places while
the AST is built, so over-deep input fails deterministically with a parse
error before any recursive pass sees it:

- parse_expr bounds the parser's own recursion depth, catching deeply
  nested shapes (CASE, subqueries, parenthesized terms) during parsing;
- last_expr_height tracks expression height bottom-up (1 + max child
  height, like SQLite's Expr.nHeight) and is checked against the limit,
  catching wide left-deep chains such as 1 OR 1 OR ... that the parser
  consumes iteratively.

The height check runs up front on each operand (so an operand that is
already over the limit and not followed by an operator is still rejected),
and function-call height folds in the ORDER BY / WITHIN GROUP / FILTER /
OVER clauses (including FunctionCallStar), since later passes walk
expressions inside those clauses too.

Add an in-process regression test that generates each recursion vector
(OR/AND/arithmetic chains, nested parens, CASE, scalar subquery, function
nesting, FILTER and window clauses) from the limit constant, runs it on a
thread with a controlled stack, and asserts the exact error at the limit
while parsing cleanly one below it. Add a Turso-only conformance test
generated from the limit, and bound the clique-join fuzz test to sizes
whose WHERE predicate stays within the limit.

Fixes #5071
2026-07-02 12:14:11 +03:00
Pekka Enberg
c1a6034a48 Move SQLite parser to sqlite/parser directory
In preparation for merging pgmicro, move SQLite parser to `sqlite/parser` directory.
2026-06-23 13:17:55 +03:00