44 Commits

Author SHA1 Message Date
Turso Agent
177f1e6204 postgres: map schema names in schema.table.column references
Fixes #9890
2026-10-14 17:21:48 +00:00
Amp
625eff2fc8 postgres: describe native languages and unsupported object catalogs
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-14 16:54:43 +00:00
Amp
41e7cbd73a postgres: distinguish built-in functions during dump discovery
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-14 14:34:45 +00:00
Amp
3f40e8f929 postgres: describe live object dependencies
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-14 14:08:17 +00:00
Jussi Saurio
5f6fa808c9 Merge 'postgres/frontend: add information_schema.schemata catalog table' from app/turso-github-handyman
`SELECT * FROM information_schema.schemata` failed with `no such table:
schemata`. The PostgreSQL frontend drops the `information_schema`
qualifier, and no catalog table for `schemata` existed. Tools such as
Tabularis use this query to list schemas.

This adds a virtual catalog table with PostgreSQL's columns
(`catalog_name`, `schema_name`, `schema_owner`,
`default_character_set_*`, `sql_path`). It is registered under the
internal name `pg_information_schema_schemata`, and the translator maps
to it only when the query writes `information_schema.schemata`. A plain
`schemata` still refers to a user table of that name, so existing
databases with such a table keep working. `pg_namespace` and the new
table now get their schema list from one shared helper, so both report
the same schemas.

```sql
CREATE SCHEMA extra;
SELECT schema_name FROM information_schema.schemata ORDER BY schema_name;
-- before: ERROR:  Parse error: no such table: schemata
-- after:  extra, information_schema, pg_catalog, public
```

Fixes #9771

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.

To have Autofixer address review feedback, leave your comments and then
mention @turso-github-handyman; it handles all unanswered comments from
maintainers in one round.

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

Closes #9802
2026-10-14 15:21:47 +03:00
Jussi Saurio
32e595a3ad Merge 'postgres/parser: name coalesce, greatest, least, nullif and CASE select items like PostgreSQL' from app/turso-github-handyman
Unaliased `coalesce`, `greatest`, `least`, `nullif` and `CASE` select
items were named `?column?`. PostgreSQL names them after the keyword:

```
SELECT coalesce(1,2), greatest(1,2), nullif(1,2), CASE WHEN true THEN 1 END;
-- before: ?column? | ?column? | ?column? | ?column?
-- after:  coalesce | greatest | nullif   | case
```

`derived_column_name` only handled function calls, column references,
casts and SQL value functions. It now handles these expressions too.
PostgreSQL treats some names as weak: a cast's type name and `case`. An
enclosing cast or CASE replaces a weak name, so `derived_column_name`
now also returns whether the name is weak. A CASE takes its ELSE
expression's name unless that name is weak, so `CASE WHEN true THEN 1
ELSE abs(1) END` is named `abs` but `CASE WHEN true THEN 1 ELSE 1::int
END` is named `case`. Nested casts now go through the same rule, which
replaces the old loop that skipped over inner casts.

Fixes #9823

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.

To have Autofixer address review feedback, leave your comments and then
mention @turso-github-handyman; it handles all unanswered comments from
maintainers in one round.

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

Closes #9824
2026-10-14 15:09:50 +03:00
Turso Agent
6f4758f9ca postgres/frontend: simplify information_schema.schemata support
Review found the schemata change added too many helpers for one catalog
table. The rows now come from pg_namespace's rows, and the translator only
renames information_schema.schemata, aliasing it to the name the user wrote.

Tests: make -C postgres/conformance run

Autofixer-Repair: review
2026-10-14 11:46:00 +00:00
Turso Agent
8ebc731032 postgres/parser: split cast and CASE fallback names from expression names
Result column naming passed a (name, is_fallback) tuple through a second
recursive function. Split it into expression_name, which casts and CASE pass
through, and cast_or_case_name, used only when no expression name exists.

Autofixer-Repair: review
2026-10-14 11:40:11 +00:00
Turso Agent
66c42010bf postgres/parser: keep the fallback flag out of derived_column_name callers
derived_column_name returned a fallback flag that its only caller ignored.
Callers now get just the name; the flag stays in a helper used for nested casts and CASE.

Tests: cargo test -p turso_pg_tests test_pg_derived_result_column_names

Autofixer-Repair: review
2026-10-14 11:13:09 +00:00
Turso Agent
5f5affe8fe postgres/frontend: add information_schema.schemata catalog table
Fixes #9771
2026-10-13 22:35:55 +00:00
Amp
f9a975c0a7 postgres: expose an empty extension discovery catalog
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-13 19:50:35 +00:00
Amp
6d76b6bbde postgres: accept dump transaction setup options
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-13 16:47:55 -03:00
Amp
39cabd3201 postgres: report connection search paths in pg_settings
Separate this behavior and its existing regression coverage from PR #9701.

Preserve the published combined source while placing catalog columns and
types before dump session setup.

Tests: existing regressions fail without this behavior; cumulative
PostgreSQL integration and server suites pass at this layer.

Amp-Thread-ID: T-01a121dc-2358-77c8-951b-d84ef7dd5a0e
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
2026-10-13 16:47:54 -03:00
Turso Agent
35f9244848 postgres/parser: name coalesce, greatest, least, nullif and CASE select items like PostgreSQL
Fixes #9823
2026-10-13 18:38:08 +00:00
Jussi Saurio
7641fad25b Merge 'postgres/parser: name cast select items like PostgreSQL' from app/turso-github-handyman
The PostgreSQL frontend named every unaliased cast column `?column?`,
while PostgreSQL names it after the cast expression, or after the target
type when the expression has no name of its own.

```
CREATE TABLE t(a int); INSERT INTO t VALUES (1);
SELECT a::int, CAST(a AS text), 1::int, 1::int::text FROM t;
```

Before: `?column? | ?column? | ?column? | ?column?` PostgreSQL and now
Turso: `a | a | int4 | text`

`derived_column_name` now handles `TypeCast` the way PostgreSQL's
FigureColname does. It skips nested casts and uses the name of the inner
expression (a column, function, or keyword like `current_user`). If that
expression has no name, it uses the last part of the outermost type
name. Column references were added so a cast can take their name.

Fixes #9810

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.

To have Autofixer address review feedback, leave your comments and then
mention @turso-github-handyman; it handles all unanswered comments from
maintainers in one round.

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

Closes #9811
2026-10-13 21:13:04 +03:00
Pedro Muniz
50e44b4c8c Merge 'postgres: report boolean catalog column types' from Pedro Muniz
Part 2 of 22 in the pg_dump feature series, stacked on
https://github.com/tursodatabase/turso/pull/9716 (`postgres-pgdump-
catalog-tableoid`). Review this diff against its immediate parent.

Declare existing catalog boolean fields as BOOLEAN instead of INTEGER,
so PostgreSQL clients receive the expected column types. Stored row
values remain unchanged. tableoid comes from the preceding layer.

This is one of ten smaller layers extracted from the former combined PR
#9701. Catalog system columns and boolean types now come before session
setup. The combined source and existing regression tests are unchanged;
early layers do not claim complete pg_dump support.

Reorganized with Amp under Pedro's direction, preserving the published
combined source and running before/after regressions plus cumulative
checks at every new layer.

Closes #9717
2026-10-13 13:54:24 -03:00
Turso Agent
929531b02b postgres/parser: name cast select items like PostgreSQL
Fixes #9810
2026-10-13 13:18:33 +00:00
Amp
33aeddbd23 postgres: implement set_config with connection-local state
pg_dump sets search_path to an empty string before reading catalogs. Store
search_path in the injected connection state so native set_config calls
and SET statements update the same session setting during execution.
Keep an explicitly empty path distinct from the default and preserve
access to qualified public tables and implicit PostgreSQL catalogs.

Support session-scoped search_path only. Reject transaction-local settings
and unsupported parameters; transaction rollback restoration and separate
wire-client sessions are not implemented in this change.

Tests: eight new WAL/MVCC regression cases fail before and pass afterward;
424 PostgreSQL integration, 22 frontend, 181 parser, and four wire-protocol
search-path tests pass. CLI build and formatting checks pass.

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-12 22:51:23 +00:00
Turso Agent
2616bfce73 postgres/parser: name unaliased select items ?column?
Fixes #9773
2026-10-12 18:32:33 +00:00
Turso Agent
89a4498876 postgres: convert values when casting to date, time and timestamp types
Fixes #9607
2026-10-12 14:16:34 +00: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
Turso Agent
9bcbf0bbc8 postgres/parser: keep enum and domain type names in casts
Fixes #9613
2026-10-09 16:49:32 +00:00
Turso Agent
68e9733174 postgres: add pg_catalog.pg_indexes
Fixes #9687
2026-10-09 14:58:25 +00:00
Claude
1abb25bc2b postgres: keep the order of a join that follows a comma
The translator flattened a comma item such as `b JOIN c ON ...` by adding
the joins of the item before the item itself. Thus `FROM a, b JOIN c ON
b.y < c.z` failed with "no such table: b", and `FROM a, b CROSS JOIN c`
returned the columns of c before the columns of b.

A RIGHT or FULL join after a comma gives different rows when the
translator flattens it, so the translator rejects it instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DEYrdboehDFy2H6f5w5BVz
2026-10-08 18:38:36 +00:00
Jussi Saurio
e57f82a2c2 parser: box large and rare parts of Expr
An Expr was 240 bytes: Exists, InSelect and Subquery stored a whole
Select inline, and every FunctionCall stored its OVER window definition
inline. Every expression is as large as its largest variant, and the code
that parses, clones, drops and translates expressions recurses once per
level, building an Expr in its stack frame at each level. For example,
the derived Clone of Expr needed an 880-byte frame, and the optimizer
clones the WHERE clause, so a long OR chain in a WHERE clause spent its
stack there.

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

A variant of AggregateRewrite that holds an Expr is no longer large
enough for clippy::large_enum_variant, so its expectation is removed.
2026-10-05 15:52:51 +03:00
Joe
c7cd6aa0dd postgres: fix wiring for WITHIN GROUP 2026-09-07 17:53:59 -07:00
Joe
04f6691cdb support current date and time expressions in tursopg 2026-08-22 14:40:20 -07:00
Claude
b9f79af18d core,parser: add EXPLAIN QUERY PLAN FORMAT=JSON
The machine-readable query plan was only reachable from the Rust API
(Statement::query_plan_json), so users of the CLI, bindings, and drivers
had no way to get it. EXPLAIN QUERY PLAN FORMAT=JSON returns the plan as
one row with one TEXT column (plan_json) holding the whole JSON
document, ready to pipe into tools like the plan visualizer. FORMAT=TEXT
(or no clause) keeps the classic four-column rows, and the statement is
still only prepared, never executed.

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

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

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

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

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

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

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

Tests: check_constraint.sqltest covers verbatim text, reopen, names, dequoting,
comments, and ALTER TABLE rewrites.
2026-08-11 13:01:27 +03:00
Pekka Enberg
f0a1b0e6ac Merge 'core, sqlite/parser: reject LIMIT and ORDER BY on DELETE and UPDATE' from Pekka Enberg
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

Closes #8315
2026-08-11 10:41:01 +03:00
Pekka Enberg
1e21c2beb6 core, sqlite/parser: reject LIMIT and ORDER BY on DELETE and UPDATE
Turso accepted DELETE/UPDATE ... LIMIT unconditionally, while a default
SQLite build only allows it with SQLITE_ENABLE_UPDATE_DELETE_LIMIT. Worse,
the support was a half-implementation: LIMIT/OFFSET executed but
ORDER BY ... LIMIT was rejected at translate time, so the upstream
wherelimit tests ran and failed spuriously instead of skipping.

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

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

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

Fixes #6076
2026-08-10 17:01:33 +03:00
Mikaël Francoeur
4d5c2577d6 postgres/parser: add test for EXPLAIN with no inner statement
The "EXPLAIN missing statement" branch in translate_explain has no
coverage because PostgreSQL's own grammar rejects a bare EXPLAIN before
translation, so no SQL input can reach it. Build the two degenerate
protobuf shapes directly and check that both report the error.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 10:43:34 -07:00
Rajat Venkatesh
3c3be41f8d postgres: explain simple queries
Translate simple PostgreSQL EXPLAIN statements to SQLite EXPLAIN QUERY PLAN so the postgres frontend can return plan rows through tursopg.

Reject EXPLAIN options until their PostgreSQL output semantics are implemented, so unsupported forms fail clearly instead of falling through.

Tests: cargo test -p turso_pg_parser explain --offline; make -C postgres/conformance run-one FILE=pg-sqltests/explain.sqltest; cargo fmt --check; git diff --check; cargo test -p tursopg --offline explain
2026-08-06 10:42:01 -07:00
haze518
1f1e71ef9e postgres: honor search_path for unqualified table lookup 2026-07-31 16:39:38 -04:00
theFestest
e9ac51bd6d postgres: implement session information functions
Adds version(), current_database(), current_schema(), pg_backend_pid(),
quote_ident(), quote_literal(), and NULL stubs for
obj_description()/col_description() to the frontend dialect. The bare
current_schema and current_catalog keywords translate to the same
functions. Zero-argument session functions in FROM position desugar
into a one-row subselect (cast to TEXT because bare subselect columns
wire as bytea) since core's TableCall path resolves only table-valued
functions.

Result columns without an explicit alias are now named after the
function or keyword as PostgreSQL derives them (FigureColname). This
also fixes count(*) reporting as "count (*)" instead of "count".

quote_ident classifies keywords with pg_query's scanner, so reserved
keywords quote and unreserved ones stay bare. version() reports the
same major version as the server_version startup parameter pgwire
advertises.

Tests: postgres/tests/integration/postgres/functions.rs;
pg-sqltests/functions.sqltest validated case-by-case against stock
PostgreSQL 16.
2026-07-30 19:26:53 -04:00
Jussi Saurio
d95edf7b40 Merge 'WITH RECURSIVE' from Jussi Saurio
Implement `WITH RECURSIVE` using the same iterative queue algorithm as
SQLite:
```sql
WITH seq(x) AS (
  VALUES (1) -- initial query
  UNION ALL
  SELECT x + 1 FROM seq WHERE x < 3 -- recursive query
)
SELECT x FROM seq;
```
The algorithm is essentially:
- Run the initial query `VALUES (1)` once and put `1` in a work queue.
- Remove `1` from the queue and return it.
- Make `1` visible to the recursive query as the single row of `seq`.
- Run the recursive query, producing `2`, and add it to the queue.
- Repeat for `2` and `3`.
- Stop when the queue is empty.
A CTE may contain multiple recursive queries:
```sql
WITH seq(x) AS (
  VALUES (1)
  UNION ALL
  SELECT x + 1 FROM seq WHERE x < 3
  UNION ALL
  SELECT x + 10 FROM seq WHERE x < 3
)
SELECT x FROM seq;
```
Each time a row is removed from the queue, every recursive query runs
against that same single row. When `1` is removed, the two recursive
queries produce `2` and `11`, and both are added to the queue.
With `UNION`, the engine also remembers (via an ephemeral index) every
row that has ever been added to the queue:
```sql
WITH cycle(x) AS (
  VALUES (1)
  UNION
  SELECT CASE x WHEN 1 THEN 2 ELSE 1 END FROM cycle
)
SELECT x FROM cycle;
```
Processing `1` produces `2`. Processing `2` produces `1` again, but that
row is discarded because it has already been seen, so the queue becomes
empty and execution stops.
`UNION ALL` does not perform this duplicate check. It adds every
generated row to the queue, so a cycle continues indefinitely unless
stopped by a condition or `LIMIT`.
### Joining the recursive row with other tables
The recursive query can join the current recursive row with ordinary
tables:
```sql
WITH seq(x) AS (
  VALUES (1)
  UNION ALL
  SELECT seq.x + 1
  FROM seq
  JOIN users ON users.id = seq.x
  WHERE seq.x < 3
)
SELECT x FROM seq;
```
For each row removed from the queue, `seq` behaves as a one-row table
containing that row. The recursive query then runs the join normally:
- Remove `1` from the queue and expose it as the single row of `seq`.
- Look up the matching `users` row and run the recursive query.
- Add the produced row to the queue.
- Repeat with the next queued row.
The real-table access is repeated for every queued row. If the join uses
an index, such as the primary key on `users.id`, this normally means one
index probe per recursive step. Without a usable index, it may mean
scanning the table again for every step.

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

Closes #8050
2026-07-30 11:30:53 +03:00
Jussi Saurio
3c1a5389ed postgres: reject SEARCH and CYCLE clauses on common table expressions
pg_query parses SEARCH/CYCLE on a recursive CTE, but the translator
silently dropped them, so queries relying on them ran with different
semantics - a CYCLE clause is often what makes the traversal terminate,
so a cyclic-graph query hung forever instead. Reject both clauses until
they are implemented.

Tests: translator unit tests for SEARCH and CYCLE rejection
2026-07-30 09:49:53 +03:00
theFestest
75879c7a30 postgres: evaluate = ANY(array) and <> ALL(array) instead of stubbing to false
The AexprOpAny arm replaced the entire expression with literal 0, so
dynamic IN-list idioms like those that psycopg2/3 document and asyncpg
requires (`id = ANY($1)`) silently returned no rows, and <> ALL errored.

Literal ARRAY[...] operands lower to IN/NOT IN (exact PG NULL
semantics); other operands (bound parameters, columns) lower to
array_contains(array, elem), whose NULL result is equivalent in WHERE
position. Other ANY/ALL operators now error loudly instead of
misevaluating. The stub existed so pg_catalog introspection queries
(attnum = ANY(conkey), where conkey is space-separated TEXT, not an
array) would not error; those now evaluate to NULL and still match no
rows.

Tests: pg-sqltests cases for the literal, NULL-element, and subquery
forms (validated against PostgreSQL 16); translator unit tests; bound
text-array parameter and pg_catalog regression coverage in
postgres/tests/integration/postgres/dialect.rs.
2026-07-29 15:22:25 +03:00
Pekka Enberg
ba5bfa8eb5 Merge 'postgres: honor NULLS FIRST/LAST in ORDER BY' from Oliver Rice
Adds Postgres dialect support for:
```sql
order by ... nulls first/last`
```
### Enables:
- Simple select statements
- Compound selects (unions)
- Window functions
### Does not enable:
- Ordering within aggregate e.g. `array_agg` *1
- raw `values ... order by` *2
*1 already tracked in COMPAT.md
*2 standalone `values ... order by` is rejected by the engine by
`core/translate/select.rs` with "ORDER BY clause is not allowed with
VALUES clause"). The new translator unit test confirms the translation
itself is correct, but there is no accompanying integration test for
that reason.
## Implementation
`turso_parser` already supported `NULLS FIRST/LAST` end to end.
`PostgreSQLTranslator::translate_order_by` in
`postgres/parser/translator.rs` was hardcoded `nulls: None` when
building the translated AST, which silently discards the clause. The
core change is 12 LOC. Everything else is tests/docs.
`translate_order_by` is shared by four AST nodes: plain `SELECT`, window
`ORDER BY`, compound `SELECT` (UNION/INTERSECT/EXCEPT), and standalone
`VALUES ... ORDER BY`. This fix covers all four. Each has a parser unit
test.
`COMPAT.md` has been updated to reflect everything above.
- Improve compatibility for the postgres path
- Remove silently incorrect behavior
## Test plan
Translator unit tests:
- `test_order_by_nulls_ordering`: plain `SELECT` ORDER BY, `ASC`/`DESC`
combined with `NULLS FIRST`/`NULLS LAST`, and the no-clause default.
- `test_window_order_by_nulls_ordering`: inline `OVER (ORDER BY ...
NULLS LAST)`.
- `test_compound_select_order_by_nulls_ordering`: `UNION ... ORDER BY
... NULLS LAST`.
- `test_values_order_by_nulls_ordering`: standalone `VALUES ... ORDER BY
... NULLS LAST` (translation only, see note above).
Integration tests:
- `test_postgres_order_by_nulls_first_last`: plain `SELECT`, ASC/DESC
combined with FIRST/LAST against a table with NULLs.
- `test_postgres_window_order_by_nulls_first_last`: `ROW_NUMBER() OVER
(ORDER BY v NULLS LAST)`.
- `test_postgres_compound_select_order_by_nulls_first_last`: `UNION ...
ORDER BY ... NULLS FIRST/LAST`.
Shamelessly assisted by Claude code. Extensively edited and reviewed by
me.

Closes #8030
2026-07-27 09:55:58 +03:00
roboturso
db964725a9 postgres: support CREATE TABLE AS and SELECT INTO
Translate PostgreSQL CREATE TABLE AS and its legacy SELECT ... INTO
spelling into Turso's CREATE TABLE ... AS SELECT so the pg frontend can
create tables from query results. WITH NO DATA creates the table from
the SELECT's shape without copying rows, IF NOT EXISTS is honored, and
INTO in nested or compound positions is rejected rather than silently
dropped. The server reports completion as `SELECT n` like PostgreSQL,
except WITH NO DATA which keeps the plain CREATE TABLE AS tag.

Explicit column lists on CTAS are rejected because the engine derives
column names from the SELECT and cannot override them.

Tests: postgres/conformance/pg-sqltests/table.sqltest covers CTAS and
SELECT INTO behavior; postgres/cli/tests/tursopg.rs covers the wire
command tags; postgres/tests/integration covers the rejection paths
where Turso intentionally diverges from PostgreSQL.

Co-authored-by: theFestest <theFestest@users.noreply.github.com>
2026-07-26 21:58:00 +03:00
Oliver Rice
fb37f82e63 postgres: honor NULLS FIRST/LAST in ORDER BY
The engine has always supported ORDER BY ... NULLS FIRST/LAST end to
end (turso_parser's ast::SortedColumn.nulls, and the full translate/
sort pipeline in core), and the PostgreSQL grammar (pg_query) already
reports it via SortBy.sortby_nulls. But
PostgreSQLTranslator::translate_order_by hardcoded `nulls: None` when
building the translated AST, silently discarding the clause and
producing the wrong row order with no error.

translate_order_by is shared by four AST shapes: plain SELECT, window
ORDER BY, compound SELECT (UNION/INTERSECT/EXCEPT), and standalone
VALUES. Decode sortby_nulls the same way CREATE INDEX's existing
translation path already does, and add a translator unit test per call
site rather than relying on "it's the same function so it must work."

Standalone VALUES ... ORDER BY has no integration test: the engine
rejects ORDER BY on a bare VALUES clause entirely, independent of NULLS
ordering (core/translate/select.rs:785, "ORDER BY clause is not
allowed with VALUES clause"). The translator unit test still confirms
the translation itself is correct, which will matter if that
restriction is ever lifted. Documented in COMPAT.md, and split the
standalone-VALUES ORDER BY/LIMIT restriction into its own row so it
reads as an unsupported feature rather than a caveat on "Multirow
VALUES".

Tests: translator unit tests assert the translated AST carries the
correct ast::NullsOrder for each of the four call sites (plain SELECT,
window, compound SELECT, VALUES); tursopg integration tests, each with
an MVCC variant, cover plain SELECT, window ROW_NUMBER(), and compound
SELECT ORDER BY NULLS FIRST/LAST end to end.
2026-07-25 09:35:06 -05:00
Rajat Venkatesh
3fb5a5b184 postgres: accept COMMENT ON as a no-op
Allow PostgreSQL clients and migrations to issue COMMENT ON statements without persisting comment metadata. Return the COMMENT wire completion tag so clients do not observe the internal no-op statement.

Tests: cargo fmt --all -- --check; git diff --check
2026-07-17 20:38:10 +05:30
Pekka Enberg
02a7ae3967 postgres/parser: rename turso_parser_pg crate to turso_pg_parser
Match the turso_pg / turso_pg_server naming used by the other
PostgreSQL crates in the workspace.
2026-07-16 12:40:03 +03:00
Glauber Costa
09b4826ed8 postgres/parser: add PostgreSQL parser crate
Standalone turso_parser_pg crate wrapping pg_query: parses PostgreSQL
SQL and translates it to the SQLite AST used by the engine.

Co-authored-by: Pekka Enberg <penberg@iki.fi>
2026-07-16 12:40:03 +03:00