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.
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
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
`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>
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.
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.
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-*'
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.
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.
`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
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
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>
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#7058Fixes#7059Fixes#7060
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
## 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
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.
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
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>
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)
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.
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.
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.
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.
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
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.
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.
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
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>
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>
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#8201Closes#8208
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
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
`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)
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
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
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
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
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>
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