Commit Graph

20967 Commits

Author SHA1 Message Date
Glauber Costa
e6f0981b43 simulator: correct MVCC rowid assumptions and validation
Under MVCC, implicit rowid allocation behaves like a sequence: the next
value comes from a high-water mark that a rollback does not lower, so an
aborted insert consumes its rowid for good and the next insert skips
past it. This is deliberate — we do not guarantee that a rolled-back
allocation is handed back, matching PostgreSQL sequences, where nextval
is never rolled back and aborted transactions leave permanent gaps.
(AUTOINCREMENT already behaved this way; the same rule now covers plain
INTEGER PRIMARY KEY rowids.) WAL mode, like SQLite, reuses the freed
value.

The simulator makes exact-row assertions, and it cannot predict a
post-rollback rowid without modeling that watermark. Rather than model
it, generate explicit integer primary keys in MVCC INSERT and UPSERT
workloads, so the assertions no longer assume rolled-back allocations
come back. WAL mode keeps generating implicit keys.

Check MVCC integrity with Turso, which can read the logical-log state
SQLite cannot, and keep the SQLite integrity check for WAL. Export the
logical log from the in-memory I/O so a retained failure artifact
includes committed state.

Tests: 21 generator tests, the MVCC profile regression, and
deterministic integrity and export regressions pass.
2026-10-12 19:56:09 -05:00
Jussi Saurio
809c89b1c4 Merge 'core/vdbe: resume the commit when RELEASE re-enters after I/O' from app/turso-github-handyman
In MVCC mode with `PRAGMA mvcc_checkpoint_threshold = 0`, releasing the
outer savepoint reported an error even though the transaction was
committed. An application that retried after the error wrote the rows
twice.

```sql
PRAGMA journal_mode='mvcc';
PRAGMA mvcc_checkpoint_threshold = 0;
CREATE TABLE a(id INTEGER PRIMARY KEY, v TEXT);
SAVEPOINT s1;
INSERT INTO a(v) VALUES ('x');
RELEASE s1;            -- before: Transaction error: no such savepoint: s1
SELECT count(*) FROM a; -- 1
```

`RELEASE` removes the savepoint and then commits through
`op_auto_commit`. With threshold 0, that commit runs a checkpoint, which
waits on I/O. When the instruction runs again, `RELEASE` looked up the
savepoint from the start, but the savepoint was already removed, so it
returned `NotFound`.

Now, if a commit is already in progress when `RELEASE` runs, it goes
straight back to `op_auto_commit` to finish that commit.
`op_auto_commit` already handles resuming a commit this way.

Fixes #9748

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9762
2026-10-12 16:13:06 +03:00
Jussi Saurio
0331ed5bb6 Merge 'core: add days to dates and subtract dates with + and -' from app/turso-github-handyman
The built-in `date` type defined only `<`, so `+` and `-` fell back to
standard numeric arithmetic on the date text, and `'2025-01-05'` was
read as 2025:

```sql
CREATE TABLE t(a date, b date);
INSERT INTO t VALUES ('2025-01-05', '2025-01-01');
SELECT a + 1, a - 1, a - b FROM t;
-- before: 2026 | 2024 | 0
-- after:  2025-01-06 | 2025-01-04 | 4
```

`date` now declares `'+' date_plus` and `'-' date_minus`. `date_minus`
checks at run time whether the right side is a number of days, which
returns a date, or another date, which returns the number of days
between them, as PostgreSQL does. `integer + date` works too. `date +
1.5` and `integer - date` raise an error.

Adding the operators was not enough on its own. A custom type's
arithmetic operator only ran for another column of the same type or for
a literal compatible with the type's `value` input. So `date + 1`, `date
+ -1`, `date + int_col` and `date + ?` never reached it. For types whose
DECODE returns the stored value unchanged, such as `date`, arithmetic
operators now also run for any other operand that is not a column of a
different custom type, and the operand is passed unencoded. Types whose
DECODE changes the value, such as `numeric` or a user-defined `cents`,
keep the old behavior, because an unencoded operand would not match the
format of the other arguments. Comparisons are unchanged.

One difference from PostgreSQL remains: `date + '1'` raises an error. A
quoted literal matches `date`'s text input, so it goes through the
`date` encode step and is read as a date, not as the integer 1.

Fixes #9608

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9715
2026-10-12 16:12:36 +03:00
Jussi Saurio
509a083af3 Merge 'core/dialect: refuse postgres frontend tables in the sqlite dialect' from app/turso-github-handyman
tursopg stores table SQL in `sqlite_schema` as `/*
turso_frontend:postgres */ CREATE TABLE ...`. The SQLite dialect passed
this text straight to `BTreeTable::from_sql`. The marker is an ordinary
SQL comment, so tursodb read the PostgreSQL DDL as a plain SQLite table:
`serial` was no longer the rowid alias and `numeric(10,2)` accepted any
value. Writes from tursodb then stored values tursopg cannot read:

```
$ tursodb -q -m list t.db "INSERT INTO t(n) VALUES ('zz'); SELECT id, typeof(n) FROM t"
|blob
|text
$ tursopg -q t.db "SELECT * FROM t"
Error: numeric_decode: expected blob, got "zz"
```

sqlite3 refuses this file with `malformed database schema (t)`. The
SQLite dialect now does the same: `parse_table_sql`,
`parse_table_sql_ast` and `table_sql_for_replay` return a corrupt-schema
error for text that starts with the marker. The marker string now lives
in `turso_core::dialect` and the postgres frontend uses it, so the two
cannot drift apart. The postgres dialect only uses the SQLite parsing
for text without the marker, so tursopg is unaffected.

Fixes #9610

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9700
2026-10-12 16:12:11 +03:00
Jussi Saurio
b9d2c7cf82 Merge 'postgres/parser: keep enum and domain type names in casts' from app/turso-github-handyman
A cast to a type name that is not on the built-in list, such as an enum
or a domain, lost its type. `pg_type_name_to_ast_type` returned `None`
for these names, so the cast had no type and converted the value to a
number:

```sql
CREATE TYPE mood AS ENUM ('sad', 'happy');
CREATE DOMAIN dd AS date;
SELECT 'happy'::mood;      -- was 0, now happy
SELECT '2024-01-01'::dd;   -- was 2024, now 2024-01-01
SELECT 'xyz'::mood;        -- was 0, now error: invalid input value for enum mood
```

The engine already handles casts to custom types: it checks enum labels,
applies the parent type's conversion for a domain, and checks domain
constraints. The translator now passes names that are not on the list
through unchanged, so those checks run. A name that is not a known type
at all is still converted by its name, as before.

Fixes #9613

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9698
2026-10-12 16:11:52 +03:00
Pekka Enberg
0d7ebc500e Merge 'perf/tatp: add the TATP benchmark for SQLite and Turso' from Pekka Enberg
The SQLite VLDB paper (Gaffney et al., "SQLite: Past, Present, and
Future", PVLDB 15) uses TATP as the benchmark for online transaction
processing so let's add that to the tree. The reference TATP is a C
program that talks to the database over ODBC, which Turso does not have,
so we created a Rust version of it to make running it simpler. The
commit also includes a vendored copy of the original TATP sources
(release 1.1.1, Common Public License 1.0, without the prebuilt solidDB
binaries).

The Rust version follows the TATP specification and, where the
specification leaves something open, the reference code: the same
schema, population, non-uniform subscriber keys and 80/20 read/write
transaction mix. It runs SQLite in WAL mode and Turso in MVCC mode with
`BEGIN CONCURRENT`.

`perf/tatp/scripts/run.sh` follows the paper's setup: 10K, 100K and 1M
subscribers, a 10 s warmup and 60 s measured, and a 1 GB page cache per
connection. It runs the paper's single client and also 4 and 16
connections, three runs each, in about two hours plus population. The
main figure draws MQTh (TATP's throughput number) against database size,
one panel per connection count and one bar per engine; the panel for one
connection is the paper's Figure 2. A second figure shows the response
time of each transaction against connections at 100K subscribers.

Each engine's database is populated once per size, and every run starts
from its own copy with the database file in the operating system's
cache. The script asks for the sudo password up front and keeps it
fresh, so a long sweep never stops at a password prompt.

Some things worth knowing:

- SQLite write transactions can wait tens of seconds for the write lock,
  because SQLite's busy handler is not fair to a waiting writer. A write
  that times out starts over, counts as a restart, and keeps the whole
  wait in its response time.
- Populating 1M subscribers takes about 1 minute for SQLite and about 7
  minutes for Turso on a RAM disk.
- The specification says GET_NEW_DESTINATION finds a row 23.9% of the
  time, but its own rules give about 15%, which is what both engines
  measure. The README explains this.
- `perf/tatp/upstream/` is excluded from aristo, which fails on the
  vendored C source because it is not UTF-8.

Closes #9549
2026-10-12 10:56:52 +03:00
Pekka Enberg
a4d624d882 Merge 'core: Pass connection settings to Database::connect as ConnectOpts' from Pekka Enberg
Database had five public ways to open a connection: connect,
connect_with_encryption, connect_with_page_codec, connect_async and
connect_with_encryption_async. Every new connection setting needs more
variants, and the async path doubles them again.

Database::connect and Database::connect_async now take a ConnectOpts
that holds the encryption key and the page codec, and the other three
variants are removed. ConnectOpts has no Default, so every caller goes
through ConnectOpts::new() and a required argument added there later
makes the compiler find every call site.

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

Closes #9792
2026-10-12 10:39:37 +03:00
Pekka Enberg
4de24b0c62 core: Pass connection settings to Database::connect as ConnectOpts
Database had five public ways to open a connection: connect,
connect_with_encryption, connect_with_page_codec, connect_async and
connect_with_encryption_async. Every new connection setting needs more
variants, and the async path doubles them again.

Database::connect and Database::connect_async now take a ConnectOpts
that holds the encryption key and the page codec, and the other three
variants are removed. ConnectOpts has no Default, so every caller goes
through ConnectOpts::new() and a required argument added there later
makes the compiler find every call site.
2026-10-12 10:05:12 +03:00
Pekka Enberg
0ccc778732 Merge 'core/json: return JSONB containers from jsonb_extract' from Ikki Nishihara
Return JSONB blobs from jsonb_extract when the result is an array or
object, including root and multiple-path results. Preserve SQL scalar
types and the text output of json_extract.

Turso currently converts extracted containers to JSON text. SQLite
returns JSONB for these containers, so typeof(jsonb_extract(...)) and
downstream binary JSON consumers otherwise see the wrong type.

Refs #9039.

Validated against main `be5bab8164d233ad20b0fd6b73512a7fb32986ac` with
Turso 0.8.0, Rust 1.88.0, sqltest 0.1.0 and SQLite CLI 3.54.0. Container
scenarios failed before the change and agreed with SQLite. Afterward,
JSON coverage passed in native, MVCC and CLI modes. Disposable file
databases containing extracted arrays and objects were read successfully
by both Turso and SQLite, with matching content, binary JSON validation
and integrity checks. The native SQL corpus excluding snapshots, SQL
test syntax, formatting, diff checks and focused core/CLI Clippy with
all features and targets passed.

Full `make test` was not run (missing Yarn and required Tcl 8.6). Full
snapshots were not run. Whole-workspace Clippy was not repeated after an
earlier branch encountered an uncached dependency during `hegeltest-c`
header generation.

Codex researched the issue, implemented the fix and regression coverage,
executed local validation and reviewed the diff and commit metadata.
This contribution was primarily AI-driven. No independent human review
is claimed.

Closes #9787
2026-10-12 09:40:31 +03:00
Pekka Enberg
d7008c2f54 Merge 'core: Fix build without uuid and json features' from Lars Brubaker
`turso_core` does not compile with `default-features = false` unless the
`uuid` and `json` features are turned back on:

```
cargo check -p turso_core --no-default-features --features fs
```

fails with two kinds of errors:

- `core/incremental/dbsp.rs` uses `uuid::Uuid` for `Hash128`, but the
`uuid` crate is only pulled in by the `uuid` feature.
- `core/vdbe/execute.rs`: the `#[cfg(not(feature = "json"))]` branches
of `TableColumnsJsonArray` and `BinRecordJsonObject` return
`Err(LimboError)` where a boxed error is expected.

The fix:

- `uuid` becomes a regular dependency of `turso_core`, because
incremental view maintenance always needs it. The `uuid` feature still
controls whether the SQL uuid functions and the `uuid` type are
registered.
- The two non-JSON branches convert the error with `.into()`, as the
JSON branches next to them already do.

A new CI job runs `cargo check -p turso_core --no-default-features
--features fs` so this combination keeps building.

We embed `turso_core` with `default-features = false, features = ["fs",
"pure-rust-crypto"]` to keep the build pure Rust, and had to add `uuid`
and `json` only to make it compile.

Claude Code found the errors, wrote the fix and the CI job, and checked
that the build fails before the change and passes after it. I asked for
this change and am submitting it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes #9730
2026-10-12 08:52:51 +03:00
Pekka Enberg
1e8e26593d core/json: fix TextSubtype typo in json_string_to_db_type doc comment 2026-10-12 08:43:52 +03:00
Pekka Enberg
13d2488c76 docs: describe which SQL types jsonb_extract returns
The docs said jsonb_extract always returns BLOB. Scalars come back as
INTEGER, REAL, TEXT or NULL; only arrays, objects and multi-path
results come back as JSONB blobs.
2026-10-12 08:43:52 +03:00
Pekka Enberg
8906537f81 sqlite/conformance: compare jsonb_extract container bytes against SQLite
The container tests only checked typeof() and json() of the result.
json() re-parses the blob, so a blob with a wrong header could still
pass. Compare hex() of the blob so the exact JSONB bytes must match
SQLite for text input, JSONB input and multiple paths.
2026-10-12 08:43:52 +03:00
larsbrubaker
f2da7b98b7 core: build without the uuid and json features
turso_core failed to compile with default-features = false unless uuid
and json were enabled again. Incremental view maintenance hashes with
uuid::Uuid, so the uuid crate is now a regular dependency; the uuid
feature still controls the SQL uuid functions and type. The non-JSON
branches of table_columns_json_array and bin_record_json_object now box
their error like the JSON branches do.

Tests: added a CI job that checks turso_core with --no-default-features
--features fs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 07:49:12 +03:00
Pekka Enberg
cb4a748a85 Merge 'core/translate: report missing partial index entries in IdxDelete, don't silently ignore corruption' from Jussi Saurio
TLDR: a debugging hack ignoring missing index entries was left in
production code and could silently ignore missing partial index entries.

### Background

Before deleting a row's entry from a partial index, DML evaluates the
index's WHERE for that row. If the row is in the index, its entry must
exist. If it doesn't, `IdxDelete` should report corruption, as SQLite
does.

### Problem

For partial indexes, `IdxDelete` never reported it
(`raise_error_if_no_matching_entry: index.where_clause.is_none()`):

```sql
-- p was built with WHERE c0 > 5, then its WHERE was changed to c0 > 0.
-- Row 1 (c0 = 1) belongs in p but has no entry.
DELETE FROM t WHERE id = 1;
-- SQLite: database disk image is malformed
-- Turso:  deletes the row
```

The flag was left over from debugging in #3228 and was later copied into
INSERT OR REPLACE, UPDATE OR REPLACE and UPSERT. Only UPDATE OR REPLACE
depended on it, because it deleted the conflicting row from every index
without checking the WHERE:

```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, k TEXT UNIQUE, c0 INT);
CREATE INDEX p ON t(c0) WHERE c0 > 5;
INSERT INTO t VALUES (1, 'a', 1), (2, 'b', 9);
UPDATE OR REPLACE t SET k = 'a' WHERE id = 2;  -- row 1 is not in p
```

### Fix

- `IdxDelete` reports a missing entry for partial indexes too.
- UPDATE OR REPLACE checks the WHERE before it deletes from a partial
index.
- The four copies of the WHERE check are now one helper. It reads the
table cursor, which is on the row being deleted.

Found while reviewing #9768.

Claude Code traced the flag's origin, removed it, found the UPDATE OR
REPLACE path that relied on it, and wrote the fix and tests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes #9769
2026-10-12 07:47:18 +03:00
Pekka Enberg
d4e396c5bc Merge 'core/translate: collect rowids first when UPDATE changes the scanned index' from Jussi Saurio
## TLDR

`DmlSafety` was not properly used in `UPDATE` when checking whether a
partial index cursor is valid to use for iteration during the `UPDATE`.
An index can only be used as the iterator if its own rows can't change
during the UPDATE.

### Background

An UPDATE can find its rows by scanning an index. If it also changes
entries of that index, it must not do that during the scan. A delete
moves the scan cursor, and reads from that cursor then see the wrong
row.

So the planner checks this. If the scanned index changes, UPDATE first
collects the rowids, then updates the rows.

A partial index changes in two ways. A key column changes, or a column
in its WHERE changes. With `CREATE INDEX i1 ON t(k) WHERE c0 > -2`,
setting `c0 = -4` removes the row from `i1`.

### Problem

The planner checked only the key columns. It missed the WHERE.

```sql
CREATE TABLE t (id INTEGER PRIMARY KEY, k TEXT, c0 INT);
CREATE UNIQUE INDEX i0 ON t(length(k)) WHERE c0 >= -1;
CREATE UNIQUE INDEX i1 ON t(k) WHERE c0 > -2;
INSERT INTO t VALUES (1, 'fizz', 2), (2, 'bb', 7);
UPDATE t SET c0 = -4 WHERE c0 > -2;
```

1. The WHERE clause matches the condition of `i1`, so the UPDATE scans
`i1`. The first entry is `('bb', 2)`.
2. `c0` is not a key column of `i1`, so the planner does not collect
rowids first.
3. `c0 = -4` removes the row from `i1`. UPDATE deletes `('bb', 2)`. The
`i1` cursor moves to `('fizz', 1)`.
4. UPDATE builds the old key of `i0`. It reads `k` from the `i1` cursor
and gets `'fizz'`. The key is `(4, 2)`. The real entry is `(2, 2)`.
5. The delete finds nothing: `Corrupt database: IdxDelete: no matching
index entry found for key [4, 2]`.

SQLite runs this UPDATE without an error.

With one row, there is no next entry, so the cursor points at no entry.
Debug builds panic with `attempt to multiply with overflow`. MVCC reads
NULL and returns the same corruption error.

### Fix

UPDATE already has the list of indexes it changes. That list includes
partial indexes whose WHERE reads an updated column. The planner now
collects rowids first when the scanned index is in that list. This
replaces its own check of the key columns.

SQLite does the same. It marks a partial index as changed when its WHERE
reads an updated column (`indexWhereClauseMightChange`). It turns off
its one-pass UPDATE when the scanned index is one of the changed
indexes.

Found by `partial_index_mutation_and_upsert_fuzz_mvcc` in CI: https://gi
thub.com/tursodatabase/turso/actions/runs/38046818837/job/114197920631

Claude Code reproduced the CI failure from its seed, reduced it to the
example above, found the cause in the bytecode, compared the planner
rule with SQLite's `update.c`, and wrote the fix and tests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes #9768
2026-10-12 07:45:59 +03:00
Pedro Muniz
c5dc0e59c4 Merge 'core/mvcc: report aborted FTS reads as dependency failures' from Pedro Muniz
- Mark dependent transactions for abort before publishing the writer's
`Aborted` state, so a speculative reader cannot see its row disappear
before receiving the abort notification.
- Return `CommitDependencyAborted` when an MVCC cursor reads after its
dependency aborted, rather than reporting a missing FTS payload as
database corruption.
- Before publishing a SQL result row, reject an MVCC transaction whose
dependency has already aborted. This does not wait for unresolved
dependencies; waiting remains at COMMIT. The added SQL-only Shuttle
assertion catches a stale `COUNT(*)` that the previous draft returned
after the writer aborted.
- The SQL-only Shuttle regression uses the public Rust API,
`memory_yield` I/O, and a seeded PCT schedule. It reproduces `FTS cursor
has no record payload` on the original unfixed checkout and passes with
the fix. No MVCC internals or yield injector are used by the test.

Investigates
[ENG-429](https://linear.app/turso/issue/ENG-429/investigate-corrupt-
error-in-antithesis-fts-workload). A concurrent FTS reader can
speculatively read a writer in `Preparing`; if that writer aborts, its
row disappears. The regression confirms this failure mode produces the
exact error seen in Antithesis. The captured Antithesis interleaving
itself was not established, and the test does not independently isolate
the rollback-ordering change from the cursor change.

The new result-row check handles a further reproduced post-abort read
without waiting for a pending writer. It runs once per returned row; its
performance cost has not been measured. Other possible cursor failure
paths were not proven or changed in this PR.

Investigation thread:
https://ampcode.com/threads/T-01a10d02-4107-776b-a78e-7e02b105ede8

Amp investigated the Antithesis report, developed the SQL-only Shuttle
reproducer and changes, and ran the checks above. The contributor
reviewed the test's use of public SQL APIs and requested preservation of
the existing Hekaton comment; both requests are reflected here. Please
review the concurrency ordering, output-time check, and test coverage
before merging.

Reviewed-by: Pere Diaz Bou <pere-altea@homail.com>

Closes #9628
2026-10-11 18:36:11 -03:00
Amp
c62cf66d5a core/vdbe: leave dependency checks at cursor and commit
ResultRow need not reject provisional rows under the commit-only dependency contract. Keep the cursor checks that prevent the FTS missing-payload error and remove the extra row check and its assertion.

Tests: RUSTFLAGS="--cfg=shuttle" cargo test -p turso_stress --locked --test shuttle_mvcc shuttle_fts_aborted_writer_does_not_report_corruption
Amp-Thread-ID: https://ampcode.com/threads/T-01a10d02-4107-776b-a78e-7e02b105ede8
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-11 21:06:22 +00:00
Jussi Saurio
120511cb97 Merge 'core/translate: resolve distinct label in simple count' from
Resolve the SELECT DISTINCT conflict label when the simple count fast
path returns early. The fast path keeps using the Count opcode.

`SELECT DISTINCT count(*) FROM t` jumps to a label that the fast path
never resolved, so the statement failed. The subquery, scalar, CTE and
LIMIT forms failed the same way.

```sql
CREATE TABLE t(x);
INSERT INTO t VALUES (1),(2),(3);
SELECT DISTINCT count(*) FROM t;
-- Before: Reference to undefined or unresolved label in HashDistinct: 5
-- After: 3
```

Closes #9517

AI helped with code inspection, the fix, and validation against SQLite.

I am new to open source, and this pull request was made with AI
assistance.

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

Closes #9781
2026-10-11 13:30:19 +03:00
haranishi
0501263763 core/json: return JSONB containers from jsonb_extract 2026-10-11 08:50:00 +00:00
Jerry Xiao
206898cd14 core/translate: resolve distinct label in simple count
SELECT DISTINCT count(*) FROM t takes the simple count fast path, which
returns right after emitting the result row. The HashDistinct jump target
for a duplicate row was never resolved, so the statement failed with
"Reference to undefined or unresolved label in HashDistinct".

Resolve the distinct conflict label at the same spot the regular
aggregation path does, so the Count opcode is still used.

Tests: added a SELECT DISTINCT count(*) regression case covering plain,
subquery, scalar, CTE, LIMIT and empty-table forms

Fixes #9517
2026-10-11 05:46:21 +00:00
Jussi Saurio
8b1387dd0f core/translate: report missing partial index entries in IdxDelete
DML evaluates a partial index's WHERE before it deletes a row's entry,
so a missing entry for a row that is in the index means the index is
corrupt. IdxDelete never reported that for partial indexes: the flag
was where_clause.is_none(), left over from debugging when partial
indexes were added, and later copied into INSERT OR REPLACE, UPDATE OR
REPLACE and UPSERT. SQLite reports it.

UPDATE OR REPLACE relied on the flag. It deleted the conflicting row
from every index without checking the WHERE. It now checks it first.

The four copies of the WHERE check are now one helper. It reads the
columns from the table cursor, which is on the row being deleted.
2026-10-10 16:51:31 +03:00
Jussi Saurio
c6e6d54bd5 core/translate: collect rowids first when UPDATE changes the scanned index
An UPDATE that scans an index must not change entries of that index in
place. The planner checked only the index's key columns. It missed a
partial index whose WHERE reads an updated column. Then UPDATE deleted
entries from the index it scanned, and each delete moved the scan
cursor to the next entry. The old key of an expression index was then
computed from the next row: IdxDelete found no entry and returned a
corruption error, or, with no next entry, debug builds panicked.

SQLite turns off its one-pass UPDATE when the scanned index is one of
the indexes it must change, including through the partial WHERE
(indexWhereClauseMightChange). Do the same: require a stable write set
when the scanned index is in indexes_to_update, which already includes
partial WHERE changes.
2026-10-10 16:36:13 +03:00
Jussi Saurio
be5bab8164 Merge 'core/mvcc: return an error instead of panicking when a reader's transaction was rolled back' from app/turso-github-handyman
When a statement on the same connection rolls back the MVCC transaction
(`INSERT OR ROLLBACK` that fails, or `ROLLBACK` after `BEGIN`) while a
`SELECT` is still open, the next read panics with `transaction should
exist in txs map`. This happens when the reader reaches a B-tree row
that has an MVCC version over it.

```sql
PRAGMA journal_mode = 'mvcc';
CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT);
INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c');
CREATE TABLE other(id INTEGER PRIMARY KEY);
INSERT INTO other VALUES (6);
PRAGMA wal_checkpoint(TRUNCATE);
UPDATE t SET v = 'z' WHERE id = 3;
-- step `SELECT id FROM t` once, then:
INSERT OR ROLLBACK INTO other VALUES (6); -- UNIQUE constraint failed
-- keep stepping the SELECT: panic
```

The rollback removes the transaction and releases its read lock, but the
open cursor still holds the old transaction ID. `find_visible_version`
already returns `NoSuchTransactionID` in this case. The B-tree
visibility checks (`chain_leaves_btree_row_valid`,
`index_chain_invalidates_btree`) called `expect` instead.

Those checks and their callers in the MVCC cursor now return
`Result<bool>`, and the reader stops with `NoSuchTransactionID` instead
of crashing the process. The connection works normally afterwards.
SQLite lets the read continue and returns 1, 2, 3. Turso can't do that
without keeping the reader's snapshot and read lock alive after the
rollback.

Fixes #9620

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

Reviewed-by: Mikaël Francoeur (@LeMikaelF)

Closes #9694
2026-10-10 13:59:32 +03:00
Turso Agent
d7e1732ea7 core/vdbe: resume the commit when RELEASE re-enters after I/O
Fixes #9748
2026-10-10 10:58:36 +00:00
Jussi Saurio
87cf8e3f4c Merge 'core/translate: find SQLite's mixed-case sqlite_sequence rows' from Lars Brubaker
When turso inserts into an AUTOINCREMENT table of a database written by
SQLite, it does not find the table's `sqlite_sequence` row if the table
name has upper-case letters. turso reissues ids that SQLite already used
and adds a second `sqlite_sequence` row for the same table.

Reproduction:

```sql
-- with sqlite3
CREATE TABLE T1(a INTEGER PRIMARY KEY AUTOINCREMENT, b);
INSERT INTO T1(a, b) VALUES(40, 0);
DELETE FROM T1;
-- then with turso on the same file
INSERT INTO T1(b) VALUES(1);
SELECT a FROM T1;   -- turso: 1, sqlite3: 41
```

SQLite stores the declared name (`T1`) in `sqlite_sequence`. turso keeps
table names lowercased in memory and compared them to the stored name
case-sensitively.

The fix compares the names with NOCASE in the two places INSERT reads
`sqlite_sequence`, and keeps the stored spelling when it updates the
row, so SQLite still finds it afterwards. A regression test creates the
file with rusqlite, inserts with turso (single-row and multi-row), and
checks the ids, the `sqlite_sequence` contents, and that SQLite's next
id follows on.

We open existing SQLite databases (written by sqlite-net, which declares
tables like `"UserSetting"`) with turso. Ids that the old app had
already used came back after a delete.

Related: #5809 (same lowercasing, for tables created by turso; not fixed
here).

Claude Code traced the lookup, wrote the fix and the test, and confirmed
the test fails before the change and passes after it. I asked for this
change and am submitting it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Closes #9731
2026-10-10 13:55:48 +03:00
Jussi Saurio
29703718ec Merge 'core/translate: Fix DROP TABLE with mixed case names' from Ethan Urbanski
Hey Turso team - I’ve been a fan since @glommer came on the Database
School Podcast. I’m excited to make my first contribution!

I’ve been hacking on [celld](https://github.com/denoland/celld) and
wanted to see how far I could get by swapping SQLite for Turso. I got
far enough to stumble upon a `DROP TABLE` bug.

There's some prior history --
[#3682](https://github.com/tursodatabase/turso/issues/3682) and
[#3683](https://github.com/tursodatabase/turso/pull/3683) addressed
schema cleanup.
[#5807](https://github.com/tursodatabase/turso/issues/5807) and
[#6055](https://github.com/tursodatabase/turso/pull/6055) addressed
leftover autoincrement state in a similar case.

I hit this issue with a file created by SQLite because it keeps the
original casing of table names in its catalog. The broader naming
differences are tracked in
[#5781](https://github.com/tursodatabase/turso/issues/5781) and
[#5730](https://github.com/tursodatabase/turso/issues/5730).

The repro is to create `T(x)` with SQLite, close the file, then open it
with Turso and run `DROP TABLE T`. The `T` row survives in
`sqlite_schema`

The cause appears to be that Turso turns the requested `T` into `t` and
then compares it with SQLite’s stored `T` without `NOCASE`. That causes
it to skip the catalog row but still frees the table’s page.  When
another table reuses the freed page, SQLite can also read that table’s
row through the old name `T`.

The patch uses ASCII `NOCASE` to find the table’s rows in
`sqlite_schema`. For `sqlite_sequence` -- it takes the table name stored
in `sqlite_schema` and uses an exact match.

As mentioned above, I found this while testing celld’s [`_cf_FACETS` tab
le](https://github.com/denoland/celld/blob/bad4649d01f0db84cdc9093527e72
e64ca7a14bf/crates/celld/storage.rs#L424-L429) with Turso. The migration
succeeded but a fresh SQLite process couldn’t reopen the file. I checked
`sqlite_schema` and found the old facet table still there.

I was hacking on Celld with Codex when I found this bug.

PS: does the goat @PThorpe92 respond?

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

Closes #9390
2026-10-10 13:47:51 +03:00
Jussi Saurio
8cad30ea0a Merge 'core/translate: drop SQLite-created mixed-case indexes' from Lars Brubaker
`DROP INDEX` on an index that SQLite created with a mixed-case name
frees the index's b-tree but leaves its row in `sqlite_schema`. The next
table that reuses the page corrupts the file.

Reproduction:

```sql
-- with sqlite3
CREATE TABLE t(a); CREATE INDEX Idx_A ON t(a); INSERT INTO t VALUES(7);
-- with turso
DROP INDEX Idx_A;
-- with sqlite3
SELECT count(*) FROM sqlite_schema WHERE type = 'index';  -- 1, expected 0
CREATE TABLE t2(b); INSERT INTO t2 VALUES(9);
PRAGMA integrity_check;  -- fails
```

turso searched `sqlite_schema` for the lowercased name (`idx_a`) with a
case-sensitive comparison, so SQLite's stored `Idx_A` never matched. The
fix compares the name with NOCASE. A regression test runs the steps
above for `Idx_A`, `idx_a`, `"Idx_A"` and `IF EXISTS`.

#9390 makes the same change for `DROP TABLE`.

Fixes #8373.

Claude Code found the comparison, wrote the fix and the test, and
confirmed the test fails before the change and passes after it. I asked
for this change and am submitting it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-by: Mikaël Francoeur (@LeMikaelF)

Closes #9732
2026-10-10 13:38:02 +03:00
Jussi Saurio
f009058175 Merge 'core/translate: reuse INSERT virtual columns in AFTER triggers' from Mikaël Francoeur
INSERT computes the virtual columns of the new row before it checks NOT
NULL and CHECK constraints. Before AFTER INSERT triggers fired, it
computed all of them again from the same registers. This PR removes the
second computation.

INSERT into `t(a, b, c AS (a + b), d AS (c * 2))` with an AFTER INSERT
trigger: 27 → 21 instructions.

Split from #9244. Part 1 of a stack of 11 PRs. Base: `main`. #9740 needs
this change.

Claude Code split this change from #9244 and rebased it on `main`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01QUXG6wGrx5f5bqgyRWWGxK

Closes #9735
2026-10-10 13:37:16 +03:00
Jussi Saurio
2dbd91d66d Merge 'core/mvcc: track dropped sequence backing table roots for integrity_check' from app/turso-github-handyman
In MVCC mode, `PRAGMA integrity_check` reported `Page N: never used`
after `DROP TABLE` of a checkpointed AUTOINCREMENT table, and kept
reporting it until the next checkpoint.

```sql
PRAGMA journal_mode='mvcc';
CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, a INT);
PRAGMA wal_checkpoint(TRUNCATE);
DROP TABLE t1;
PRAGMA integrity_check;
-- before: *** in database main ***\nPage 5: never used
-- after:  ok
```

In MVCC mode a dropped B-tree's pages are not freed until checkpoint, so
`DropTable` and `DropIndex` add the dropped root pages to
`schema.dropped_root_pages`. That way integrity_check still counts those
pages as used. `DropSequence` removes an AUTOINCREMENT table's internal
sequence table from the schema, but it did not record that table's root
page. The page was left out of the check.

`DropSequence` now records the sequence table's root page the same way
when it is checkpointed (positive root page). This also covers `DROP
SEQUENCE`.

Fixes #9750

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9761
2026-10-10 13:33:28 +03:00
Jussi Saurio
73f4547ebd Merge 'core/translate: skip objects dropped in the transaction in MVCC integrity_check' from app/turso-github-handyman
In MVCC mode, `PRAGMA integrity_check` builds its checks from the
database-wide schema, because its root pages match the database file.
Inside a transaction that dropped a checkpointed index, that schema
still lists the index. The row checks read the table through the
transaction, so they see values the dropped index was never updated
with, and report rows missing from it.

```sql
PRAGMA journal_mode='mvcc';
CREATE TABLE t1(id INTEGER PRIMARY KEY, b TEXT);
CREATE INDEX i2 ON t1(b);
INSERT INTO t1 VALUES (480, 'y');
PRAGMA wal_checkpoint(TRUNCATE);
BEGIN;
DROP INDEX i2;
UPDATE t1 SET b = 'q1' WHERE b = 'y';
PRAGMA integrity_check;
```

Before: `row 1 missing from index i2`. After: `ok`, the same as SQLite
and WAL mode.

The page-level check of the file still uses the database-wide schema.
The row checks now skip any table or index whose root page is not in the
connection's own schema. Matching on root page also covers an index that
was dropped and re-created under the same name in the transaction.

Fixes #9751

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9760
2026-10-10 13:32:48 +03:00
Jussi Saurio
dca085b15d Merge 'core/translate: accept rowid names in triggers when dropping a column' from app/turso-github-handyman
`ALTER TABLE ... DROP COLUMN` failed when a trigger referred to a
table's rowid by any of its names (`rowid`, `_rowid_`, `oid`). SQLite
accepts the statement.

```sql
CREATE TABLE t(id INTEGER PRIMARY KEY, a INT, b TEXT);
CREATE TABLE audit(rid INT);
CREATE TRIGGER tr1 AFTER DELETE ON t BEGIN INSERT INTO audit VALUES(OLD.rowid); END;
ALTER TABLE t DROP COLUMN b;
-- before: Parse error: error in trigger tr1: no such column: OLD.rowid
-- after: column is dropped
```

After dropping a column, triggers are checked again for references to
columns that no longer exist. The lists of valid names used in that
check held only declared columns, so `NEW.rowid`/`OLD.rowid`,
`t._rowid_` and bare `rowid`/`oid` were all rejected.

Both places that build these lists now use one helper. It adds the rowid
names when the table has a rowid and no declared column already uses the
name. `WITHOUT ROWID` tables still reject them, as in SQLite.

Fixes #9753

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9757
2026-10-10 13:32:02 +03:00
Turso Agent
22630d2997 core/mvcc: track dropped sequence backing table roots for integrity_check
Fixes #9750
2026-10-10 06:27:02 +00:00
Turso Agent
0b8dce7736 core/translate: skip objects dropped in the transaction in MVCC integrity_check
Fixes #9751
2026-10-10 06:01:34 +00:00
Jussi Saurio
00424b645c Merge 'postgres: add pg_catalog.pg_indexes' from app/turso-github-handyman
The PostgreSQL frontend had no `pg_indexes` catalog view, so any client
that lists indexes failed with `no such table: pg_indexes`. DuckDB's
postgres extension runs this query on `ATTACH`, so it could not connect
at all:

```sql
SELECT pg_namespace.oid, tablename, indexname
FROM pg_indexes
JOIN pg_namespace ON (schemaname=nspname)
ORDER BY pg_namespace.oid;
```

This adds `pg_indexes(schemaname, tablename, indexname, tablespace,
indexdef)` using the same snapshot pattern as `pg_tables`. It lists the
same indexes in the same order as `pg_class` and `pg_index`. The `CREATE
INDEX` text built by `pg_get_indexdef()` is moved into a shared helper,
so `pg_indexes.indexdef` and `pg_get_indexdef()` always return the same
definition. The table is also added to the catalog name list, so INSERT,
UPDATE and DELETE on it are rejected like on the other catalog tables.

Fixes #9687

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9691
2026-10-10 08:37:53 +03:00
Jussi Saurio
9c5f5557f6 Merge 'postgres: stop a qualified column at the nearest table with its name' from app/turso-github-handyman
In a subquery, `t2.a` can match a table `t2` in the subquery and another
`t2` in an outer query. PostgreSQL uses only the nearest table named
`t2` and reports an error if that table has no column `a`. tursopg used
the SQLite rule instead: it kept searching outer queries and read the
outer `t2.a`. So it accepted queries that PostgreSQL rejects.

```sql
CREATE TABLE t1(a INT);
INSERT INTO t1 VALUES (1), (2);
SELECT t2.a, (SELECT t2.a + b FROM (SELECT 100 AS b) AS t2) FROM t1 AS t2;
```

Before: `1|101`, `2|102`. PostgreSQL: `ERROR: column t2.a does not
exist`. tursopg now returns an error too.

This adds a `Dialect` method,
`qualified_column_uses_nearest_table_only`. It is false by default and
true for the PostgreSQL dialect. When it is true, qualified name lookup
stops at the nearest query that has a table with the given name, whether
that is the current query or an outer one. The SQLite dialect keeps the
SQLite rule.

Fixes #9626

Autofixer wrote this change with Claude Code in an isolated sandbox. A
separate verifier agent tested and reviewed it in its own container
before this PR was opened. A maintainer must review it before merge.

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

Closes #9685
2026-10-10 08:36:28 +03:00
Amp
6ea8839966 core/vdbe: reject rows from aborted MVCC dependencies
A speculative reader can keep executing after its writer aborts and return a normal count from an invalid transaction without fetching a record. Check the existing abort flag before publishing a result row, without waiting for unresolved dependencies before COMMIT.

Extend the SQL-only Shuttle FTS scenario to keep that reader open across writer rollback and require the dependency error instead of a stale count.

Tests: SQL-only Shuttle regression (failed before, passed after); MVCC and FTS unit suites; cargo fmt --check
Amp-Thread-ID: https://ampcode.com/threads/T-01a10d02-4107-776b-a78e-7e02b105ede8
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-10 05:11:38 +00:00
Pedro Muniz
df9005a14e Merge 'core: add typed access to connection-local context' from Pedro Muniz
Stacked on #9627. Add caller-provided context to the existing, non-
generic core `Connection`.

```rust
let conn = db.connect_with_context(Arc::new(MyContext::default()))?;
let context = conn.context::<MyContext>();
```

`connect_with_context` accepts `Arc<C>` where `C: Any + Send + Sync`.
The connection stores one opaque value before connect-time queries run.
`context::<C>()` returns a borrowed value after a checked downcast, or
`None` when no context is present or the type does not match.

Connection clones and helper statements use the same context. Different
connections receive different values unless the caller deliberately
shares an `Arc`. The context remains alive while a connection owner or
statement retains it, and callers can use locks or atomics to mutate its
contents.

There is no setter, type-indexed map, or additional lock around the
stored value. This adds only the synchronous core API; PostgreSQL
session handling and public driver APIs remain unchanged.

#9627 gives native scalar calls access to the executing connection.
Extensions also need access to caller-provided data that belongs to that
connection, such as frontend session settings.

Making `Connection<C>` generic would require changes throughout
statements, programs, extension traits, and bindings. Keeping the stored
value opaque allows typed construction and lookup without changing those
interfaces.

pedrocarlo and Amp discussed a generic connection type versus an opaque
connection-local value. Pedro approved the opaque-value design and asked
Amp to implement it as a separate stacked PR. Amp inspected connection
ownership and native extension interfaces, implemented the core API, and
ran the new tests before and after context storage was added, followed
by broader compatibility checks.

Amp thread:
https://ampcode.com/threads/T-01a11786-6662-751d-925e-4ec4fecf16b3

Reviewed-by: Mikaël Francoeur (@LeMikaelF)

Closes #9632
2026-10-09 18:49:49 -03:00
Turso Agent
bdca32c49c core/translate: accept rowid names in triggers when dropping a column
Fixes #9753
2026-10-09 21:00:10 +00:00
Mikaël Francoeur
e0dbb3995a one more slop keyword 2026-10-09 16:31:00 -04:00
Claude
6425e6d569 core/translate: reuse INSERT virtual columns in AFTER triggers
INSERT computes the virtual columns of the new row before it checks
NOT NULL and CHECK constraints. Before AFTER INSERT triggers fired, it
computed all of them again from the same registers. Nothing between the
two points writes those registers, so the second pass only repeated the
work of the first.

Tests: gencol_insert_after_trigger_reuses_virtual_columns bytecode
snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014eW565TkmUCmrsGZSaPgGT
Claude-Session: https://claude.ai/code/session_01QUXG6wGrx5f5bqgyRWWGxK
2026-10-09 19:41:55 +00:00
larsbrubaker
9f19041f47 core/translate: find SQLite's mixed-case sqlite_sequence rows
INSERT looked up an AUTOINCREMENT table's sqlite_sequence row with a
case-sensitive comparison against the lowercased table name. A file
written by SQLite stores the name as declared ("T1"), so the row was not
found and turso reissued ids that SQLite had already used, and added a
second row for the same table.

Match the row with NOCASE, and keep the stored spelling when the row is
updated so SQLite still finds it afterwards.

Tests: added an INSERT regression test on a SQLite-created file

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:35:20 -07:00
larsbrubaker
3abae79e70 core/translate: drop SQLite-created mixed-case indexes
DROP INDEX looked for the index's sqlite_schema row with a case-sensitive
comparison against the lowercased name. For an index created by SQLite
with a mixed-case name, the row was kept while its b-tree was freed, so
the next table that reused the page corrupted the file.

Match the row by name with NOCASE, as SQLite treats index names.

Tests: added a DROP INDEX regression test on a SQLite-created file

Fixes #8373

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:28:19 -07:00
Mikaël Francoeur
b1c4445747 Merge 'agentic instructions' from Mikaël Francoeur
Reviewed-by: Pedro Muniz (@pedrocarlo)

Closes #9728
2026-10-09 15:17:19 -04:00
Mikaël Francoeur
2fe5838d95 instructions 2026-10-09 15:15:02 -04:00
Amp
2b04bfebb0 core: rename connection-local state to context
Use context for the opaque caller-provided connection value, matching the review on #9632. Preserve typed lookup, ownership, and existing connect behavior.

Tests: context API tests fail to compile against the old API; 17 external API tests and 35 native extension tests pass after the rename.

Amp-Thread-ID: https://ampcode.com/threads/T-01a12186-0296-70d3-bf4c-b139823d52ab
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-09 15:49:22 -03:00
Amp
a289432784 core: add typed access to connection-local state
Let callers supply an Arc of application state when connecting without
making Connection, statements, or extension traits generic. Store the
state before connect-time queries and expose it through checked typed
lookups.

Connection clones and helper queries share the same value. Separate
connections remain independent unless the caller explicitly shares the
Arc. Keep state identity fixed and leave existing connect APIs unchanged.

Tests: five new cases fail without state storage and pass with it;
2555 core, 416 PostgreSQL integration, and 17 external API tests passed.
Formatting, diff checks, and CLI serde compilation passed.

Amp-Thread-ID: https://ampcode.com/threads/T-01a11786-6662-751d-925e-4ec4fecf16b3
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-09 15:49:22 -03:00
Pedro Muniz
7d6c464700 Merge 'postgres: migrate scalars to native extensions' from Pedro Muniz
Stacked on #9545. Register all 29 PostgreSQL scalar functions through
the native Rust extension API alongside the catalogs.

- Reuse the grouped declarations from #9538 for names, accepted argument
counts, and determinism. Keep the trait implementations separate from
the declaration macro.
- Pass the executing connection and borrowed arguments to each
`ScalarCall::step`. The existing opaque call object retains progress
while waiting for I/O.
- Support exact, multiple, and variadic argument counts, including
registry and catalog metadata.
- Remove PostgreSQL's dialect scalar dispatch and C-ABI timestamp
registration.

Connection-local state injection is not included. Timestamp behavior and
the C-extension ABI remain unchanged.

#9545 moves PostgreSQL catalogs to native extensions, but scalar
functions still use separate execution paths. This extends the existing
native API with what the scalar migration needs instead of adding a
second dialect callback and state system.

## Validation

- `cargo test -p turso_core --lib -- --test-threads=1`: 2,554 passed, 17
ignored.
- `cargo test -p turso_pg_tests --test integration_tests --no-default-
features --features test_helper -- --test-threads=1`: 416 passed,
including WAL and MVCC variants. Re-run after separating the trait
implementations.
- `cargo test -p turso_pg --lib`: 22 passed.
- `cargo test -p core_tester --test integration_tests --no-default-
features --features test_helper external_apis:: -- --test-threads=1`: 13
passed.
- Four PostgreSQL regression tests failed before the migration and
passed afterward.
- Native tests cover borrowed arguments across I/O, the executing
connection, accepted argument counts, helper-query resumption, and
nested-trigger cancellation in WAL and MVCC modes.
- `cargo fmt --check`, `git diff --check`, and `cargo check -p turso_cli
--features turso_core/serde`: passed.

Strict Clippy stops on an existing, unchanged lint expectation in
`core/json/cache.rs:107`. Regular `cargo clippy -p turso_core -p
turso_pg --lib` finishes with only that warning.

pedrocarlo directed Amp to inspect #9545, #9538, and the native
extension API, then implement the scalar migration without connection-
local state injection. Amp added and ran regression tests, checked the
broader core and PostgreSQL suites, and separated the trait
implementations from the declarations following review feedback.

Amp thread:
https://ampcode.com/threads/T-01a11786-6662-751d-925e-4ec4fecf16b3

Reviewed-by: Mikaël Francoeur (@LeMikaelF)

Closes #9627
2026-10-09 15:49:18 -03:00
Turso Agent
686da452f4 core: add days to dates and subtract dates with + and -
Fixes #9608
2026-10-09 18:46:38 +00:00
Amp
ea305e1f9f postgres: migrate scalars to native extensions
Register PostgreSQL scalar functions through the native extension API
alongside the catalogs. Reuse the existing opaque per-call state instead
of adding a second dialect callback system.

Pass the executing connection and borrowed arguments on each step, and
support exact, multiple, and variadic argument counts. Keep timestamp
behavior unchanged and omit connection-local state injection.

Tests: 2554 core, 416 PostgreSQL integration, 22 frontend unit, and 13 C
extension API tests passed. Four PostgreSQL regressions fail before the
migration and pass after it. Formatting and CLI serde checks passed.

Amp-Thread-ID: https://ampcode.com/threads/T-01a11786-6662-751d-925e-4ec4fecf16b3
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-09 18:12:01 +00:00