Repository navigation
feat(extension): utopia-php/query in Rust: classifiers, tokenizers, Query, AST, schemas and builders - #15734
Conversation
toRawSql(), the schema builder and the AST serializer each hand-rolled their own escaping. The schema builder and AST serializer doubled backslashes for every dialect, which PostgreSQL (standard_conforming_strings) and SQLite read literally, so the stored or compared value gained a backslash; the AST path is executed SQL through fromAst(). StringLiteral gives one case per dialect: Backslash (MySQL/MariaDB) escapes backslashes, Extended (PostgreSQL) switches to E'' when a backslash is present, Standard (SQLite) only doubles quotes, Unicode (ClickHouse) escapes both. A backslash right after a byte >= 0x80 is refused on MySQL, MariaDB and PostgreSQL, since a GBK/BIG5/SJIS/GB18030 lead byte swallows the escaping backslash and lets the value close its literal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MySQL and MariaDB escaped LIKE wildcards with a backslash without an ESCAPE clause, so under NO_BACKSLASH_ESCAPES the backslash was no escape and an escaped % or _ matched as a wildcard. They now escape with ! and declare ESCAPE '!', which holds in every sql_mode and leaves backslashes literal. SQLite has no default LIKE escape, so it now declares ESCAPE '\' for the backslash escaping it already used. setJsonRemove's JSON_SEARCH matches a LIKE pattern too, so its value is escaped and the escape character passed. Every LIKE emit goes through compileLikePredicate so a dialect declares its escape in one place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JSON_SEARCH returns NULL for a value that is not in the array (and on MySQL for any non-string value), and JSON_REMOVE with a NULL path returns NULL, so removing a missing tag wiped the column or failed on a NOT NULL column in strict mode. COALESCE falls back to the original column. The LIKE escape character is now quoted through the dialect's StringLiteral in both the ESCAPE clause and JSON_SEARCH, and the identical MySQL/SQLite likeEscape() overrides collapse into one base implementation gated by DECLARES_LIKE_ESCAPE. PostgreSQL and ClickHouse still emit no ESCAPE clause, and the ClickHouse LIKE fallback reuses compileLikePredicate(). SQLite's LIKE index optimization stays available because the backslash escape is ASCII. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unicode suggested PostgreSQL's U&'' literals, but the case is backslash escaping without the multibyte lead-byte refusal, so it is now BackslashUtf8. Per-case behaviour moves into exhaustive match methods (escapesBackslash, refusesBackslashAfterHighByte, refusesNul, escapePrefix) so adding a case fails to compile until each is decided, replacing the default arm and the scattered identity checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The MySQL, MariaDB and ClickHouse builders built the base AST serializer, leaving their dialect serializer classes unused and free to drift; each now builds its own, as PostgreSQL and SQLite already did. Those classes add no behaviour beyond the literal, so output is unchanged. PostgreSQL::quoteJsonKey hard-coded StringLiteral::Extended instead of the builder's literal, and was a private one-line wrapper, so it is inlined. Enum quoting in the MySQL and PostgreSQL schema builders passes quote(...) as a first-class callable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The serializer quotes per dialect but the tokenizer treated a backslash as an escape everywhere and the parser undid only '' and \', so the two disagreed: SQLite's 'C:\' was reported unterminated, PostgreSQL's plain 'a\' swallowed the closing quote and E'..' was not one token, and a MySQL 'a\\b' parsed to a\\b and re-serialized doubled. toAst() also parsed CTE bodies with a bare MySQL-flavoured tokenizer. StringLiteral gains unquote(), the inverse of quote(), which decodes the dialect's escapes (MySQL keeps \% and \_ as MySQL does; PostgreSQL's E'' octal, hex and Unicode escapes; ClickHouse's \xHH) and refuses a malformed literal. Tokenizer and Parser take a StringLiteral, each dialect tokenizer defaulting to its own, and builders tokenize and parse CTEs with their dialect's tokenizer and literal. The SQLite tokenizer no longer narrows identifier quoting to double quotes: its builder emits backticks, which SQLite accepts, so CTE bodies from it failed to parse once toAst() used the SQLite tokenizer. No existing tokenizer or parser test encoded the old backslash behaviour, so none needed changing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under NO_BACKSLASH_ESCAPES MySQL and MariaDB read a backslash literally, so a schema comment or default with one is stored with it doubled. The '' doubling holds in both modes, so this is wrong data rather than an injection, but callers running that mode need to know. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Creates a table whose string default, table comment and column comment hold a backslash and a quote through the schema builder, then reads them back with obj_description, col_description and an inserted row, so the E'' quoting is checked against the server rather than against a string. LikeEscapeTest is made final like the other test classes added here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
toAst() re-parses CTE bodies, and the parser stopped at ESCAPE without complaint, so MySQL, MariaDB and SQLite CTEs lost their ESCAPE clause while the bindings stayed escaped. The parser now reads ESCAPE after LIKE, ILIKE and their negations into Binary::$escape, and parse() rejects any token left after the statement (one trailing semicolon aside) so an unknown clause can no longer vanish. toAst() escapes the LIKE values it builds and declares the dialect's escape character, and fromAst() decodes patterns with the declared or implicit escape, keeping anything it cannot map raw with its clause. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mast fromAst() dropped an OR operand it could not turn into a Query, which now happens for a LIKE with an unusable ESCAPE value, so the remaining operand widened the filter. Such operands are kept as raw conditions. A LIKE whose escape character is itself a wildcard was decoded with the leading % read as a wildcard before the escape check; it now stays raw. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gexes The repository avoids regular expressions; an explicit scan reads each dialect's escapes with the same rules and is easier to review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unchanged from feat/rust-utopia-conversion at a962288. Nothing uses it yet. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…_LIBRARIES=query The first part of packages/query on the utopia extension: the Classifier interface, Classifier\SQL, MySQL, PostgreSQL and MongoDB, and the Type enum they return. Every other class of the package stays PHP. The parity corpus is identical on both implementations but for one asserted difference (the enum does not report itself final), and packages/query/tests pass on the extension. run.sh leaves out the package's E2E tests, which need database servers. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
# Conflicts: # crates/extension/src/lib.rs
Security rulesWARNING (1 new) — review signal only; does not fail the job.
|
Tokenizer\Tokenizer and its MySQL, MariaDB, PostgreSQL, SQLite and ClickHouse dialects, behind _APP_EXTENSION_LIBRARIES=query. Token and TokenType stay PHP: tokenize() returns the package's own objects. Five MySQL tokenizer tests reached a private method by reflection; they now go through tokenize(), so they run on both implementations. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
The rewritten MySQL tokenizer tests read a string back from tokenize(), so assertIsString() on it is always true at the package's PHPStan level. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Utopia\Query\Query over the extension's NativeQuery, behind _APP_EXTENSION_LIBRARIES=query. The package declares Query over it to keep the two constants that are arrays. A query's values stay PHP values, so nested queries keep their identity. Subclasses keep working: new static makes the called class, the methods Query.php reaches through static run a subclass's own, and so do toArray() and shape(). Utopia\Database\Query depends on all three. One test read contains()'s #[\Deprecated] attribute by reflection; it now asserts the deprecation the call raises. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The AST serializer dropped the parentheses of a right operand of equal precedence for every operator but -, / and %, so `a = (b = c)` was written as `a = b = c`, which reads back as `(a = b) = c`. Only the same associative operator (+, *, ||, AND, OR) may drop them. The change is the one on feat/rust-utopia-conversion, which crates/utopia/query was ported from. Co-Authored-By: Eldad Fux <eldad.fux@gmail.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
AST\Grammar, AST\Parser and AST\Serializer with its five dialects, over crates/utopia/query, behind _APP_EXTENSION_LIBRARIES=query. The node classes, the walker and the visitors stay PHP. The parser returns the package's node objects and the serializers read them, both through property slots whose layout is checked once a request. A tree deeper than 32 levels is worked on a stack allocated for its depth, so the extension takes every tree PHP takes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Schema, Schema\SQL and the dialects MySQL, PostgreSQL, SQLite, ClickHouse and MongoDB compile with crates/utopia/query when _APP_EXTENSION_LIBRARIES names query, with the 16 Schema\Feature interfaces they implement. The blueprints (Table, Column, ForeignKey, Index and the rest) and the enums stay PHP: a schema reads a blueprint through its property slots and returns the package's Builder\Statement. The crate gets definition_mut() on Table and Column, so a blueprint read from elsewhere can be set without the fluent methods. The parity corpus adds 1,231 lines for the schemas and is identical on PHP and the extension. Six known differences are asserted in it and listed in the README. This part is not faster: a statement takes 6% to 45% longer than PHP's, 1 to 4 microseconds. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A native schema statement took 13% to 35% longer than PHP's on the Alpine image. It now takes 7% to 22% less. - mimalloc is the extension's allocator. More than half of a compileCreate() was malloc and free, and musl's are slow. The local_dynamic_tls feature is what a library loaded with dlopen needs on musl. - The crate writes a column definition into one string, where it joined a list of parts. - A Statement is made by setting its property slots, which is all its constructor does. Columns are read straight into the table's list. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
toString() built a PHP array and called json_encode() on it, which took 60% longer than PHP's own. It now writes the JSON itself when the query holds only nulls, booleans, integers, UTF-8 strings and queries like it, and leaves anything else to json_encode() as before. The corpus runs both paths over escapes, invalid UTF-8, floats, arrays, objects and deep nesting. A string default is also cheaper to describe: ext-php-rs formats every default on every call of a method that has one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Checks run against the builders on 2026-11-23, and what they found. Fixed
Found, not fixed
Passed, on the Alpine image built for arm64
Still open before production: a staging canary ( |
…lues() and geometryToWkt() A build called the native ones whatever a subclass declared. They are steps now, 77 in all. quote() takes the builder mutably like every other step, so an override that calls back into the builder cannot alias a field the build is reading; the sites that quoted a field of the builder copy it first. PHP asks getLikeKeyword() before likeEscape(), and so does the crate now. A new object knows its owner before any method runs, so getBindings() called first reaches the override, and the savepoint methods and executeMerge() record it for a clone. The corpus overrides the four in every helper build and adds 40 cases of its own: 181 cases differ on the commit before this one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
The override gap from the comment above is closed in fed6849. A build now calls a subclass's The corpus overrides the four in every helper build and adds 40 cases: 15,827 cases match PHP, and 181 differ on the commit before. The package tests, utopia-php/database 10.2.3's suite and the coroutine test give the same results as before, and the benchmark is unchanged. Not rerun for this commit: valgrind, the soak and the local E2E. |
main added the `utopia.libraries` setting and the compression library. `query` and `query-builders` join its names, and naming the builders brings `query`, whose classes they take and return. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Merged main in 1f9d4e9. main added the Rerun on the merged build, on the Alpine image for arm64:
Not rerun: the local E2E with the switch on. |
|
Staging canary started.
Baseline before the switch, staging |
|
After the switch:
Staging traffic is thin, so this shows it loads and runs, not that every path was hit. Roll back by removing |
The builders had a switch of their own, query-builders, while they were being moved. They pass the same checks as the rest now, so query names all of Utopia\Query and the second name is gone: one switch to roll out, and no combination that does nothing. run.sh runs the builder and coroutine corpora under query. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
After the rollout:
Seen in passing, not ours: utopia-php/database 10.2.3's SQLite builder writes |
Code review
This pull request adds an opt-in Rust-backed implementation of the query package’s classifiers, tokenizers, Query, AST, schemas, and builders, while retaining PHP value objects and the PHP fallback. It adds PHP bindings and bootstrap integration, parity and regression coverage, and crate documentation and benchmarks. The Composer build stage now uses a pinned Composer image digest. Latest changes: The newest commit pins the Composer stage to the Composer 2.11.2 image digest; its embedded Alpine CA bundle includes the 20261020-r0 update. Note Not approving while a bug finding is open: Query getter overrides are bypassed during grouping Fix with agent prompt### Issue 1
crates/extension/src/query/value.rs:1571
**Query getter overrides are bypassed during grouping**
PHP's `Query::groupByType()` calls `getMethod()`, `getValues()`, and `getAttribute()`, but this path reads the native fields directly; the same bypass occurs in `getByType()`, `getCursorQueries()`, `merge()`, and `validate()`. A `Query` subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.
### Issue 2
crates/extension/src/query/schema.rs:1405-1408
**Validate collation keys before converting values**
This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as `['bad key' => new stdClass()]`, PHP raises the key `ValidationException`, while this binding raises a `TypeError` for the value instead.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Walkthrough (11)
Still open from earlier reviews (2)
Fixed since the last review (1)
Reviewed the commits since Tip Comment |
| for zval in queries.values() { | ||
| let Some(query) = query_of(zval) else { continue }; | ||
| let first = || query.values.array().and_then(|values| values.get_index(0)).filter(|value| !value.is_null()); | ||
| match query.method { |
There was a problem hiding this comment.
Query getter overrides are bypassed during grouping
PHP's Query::groupByType() calls getMethod(), getValues(), and getAttribute(), but this path reads the native fields directly; the same bypass occurs in getByType(), getCursorQueries(), merge(), and validate(). A Query subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.
Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/extension/src/query/value.rs
Line: 1571
Comment:
**Query getter overrides are bypassed during grouping**
PHP's `Query::groupByType()` calls `getMethod()`, `getValues()`, and `getAttribute()`, but this path reads the native fields directly; the same bypass occurs in `getByType()`, `getCursorQueries()`, `merge()`, and `validate()`. A `Query` subclass that overrides one of these getters therefore gets different filtering or grouping results with the extension enabled.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
There was a problem hiding this comment.
Known and documented (crates/extension/README.md, "Utopia\Query\Query"): no Query subclass in Appwrite, Cloud, Edge or utopia-php/database 10.2.3 overrides getMethod(), getAttribute() or getValues().
There was a problem hiding this comment.
That confirms no current in-repository subclass is affected, but the behavior remains reachable for downstream subclasses. For example, CustomQuery::limit(7) can override getMethod() to return Method::Equal: PHP’s groupByType() dispatches that override, while the extension reads the stored Limit method directly and groups it as a limit. PHP’s factory returns static (Query.php); the PHP grouping path calls the getters (Query.php), whereas the extension reads the native fields (value.rs).
Documenting the limitation and noting no current internal subclass uses it doesn’t make the two implementations behave alike for subclasses. I’m keeping the finding open.
The commit before this takes #15328 (per-dialect string literals and a declared LIKE escape) back out of the PHP package, so this pull request changes no PHP behaviour. With utopia-php/database 10.2.3 the package's SQLite builder and the library's own each appended ESCAPE, and SQLite refused the statement; that happened with the extension off. The Rust port had been written to match #15328, so it follows: - Reverts 589edce: the tokenizers, parser, serializers and schemas read and write string literals as main's PHP does. StringLiteral is gone, and the shared filter module stays as it was. - The builders escape LIKE with a backslash and declare no escape, setJsonRemove is main's JSON_REMOVE, toRawSql quotes through each dialect's quoteString, and toAst/fromAst carry no escape clause. - compileLikePredicate(), likeEscape() and createTokenizer() are not methods of main's builders, so they and their steps go: 74 remain. - MySQL, MariaDB and ClickHouse use the base AST serializer, as main's createAstSerializer() does. Both corpora match main's package: 15,797 builder cases and 55,481 query lines. utopia-php/database's suite fails the same nine tests on main's package, on this branch's PHP and on the extension. Reverting this commit and the one before re-lands #15328 with its port. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
#15328 is out of this pull request (59d2256 for the PHP package, 458b4a5 for the Rust port of it). It broke SQLite with the extension off: utopia-php/database 10.2.3's SQLite builder appends My earlier "same 63 failures on PHP and on the extension" compared this branch with itself, never with main. With main as the baseline the suite now fails the same nine on main's package, on this branch's PHP and on the extension, and both corpora match main's package: 15,797 builder cases and 55,481 query lines. #15328 has the same problem on its own. Re-landing it here is a revert of those two commits plus a database library release that drops its own clause. |
| let option = match option { | ||
| option if option.is_null() => String::new(), | ||
| option if option.is_array() => "Array".to_owned(), | ||
| option => scalar(false, option, "options")?, |
There was a problem hiding this comment.
Validate collation keys before converting values
This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as ['bad key' => new stdClass()], PHP raises the key ValidationException, while this binding raises a TypeError for the value instead.
Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/extension/src/query/schema.rs
Line: 1405-1408
Comment:
**Validate collation keys before converting values**
This converts each option value before validating its key, unlike PHP, which rejects an invalid key first. For an input such as `['bad key' => new stdClass()]`, PHP raises the key `ValidationException`, while this binding raises a `TypeError` for the value instead.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
…mage appwrite/base 2.5.1 ships python3 3.14.10-r1. Alpine edge has split python3-ndbm out at r2 and installs it beside python3 on any apk add, where it overwrites a file r1 still owns. Every apk add on the base image fails, so CI's image build breaks on its next cache miss: the Extension job's did. The ffmpeg and base stages and crates/extension/build.sh upgrade python3 first, which takes both to r2. It can go once the base image carries r2. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…e base image" This reverts commit d9ddc77.
2.5.1 carries python3 3.14.10-r1. Alpine 3.24 then published r2, which splits python3-ndbm out and installs it wherever python3 3.14.10 is present. apk add does not upgrade what is installed, so any apk add on 2.5.1 pulls python3-ndbm r2 beside python3 r1 and fails on a file both own. The image builds only while its layers are cached. 2.5.2 is the same commit of appwrite/docker-base rebuilt, with python3 r2 and python3-ndbm already in place. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The composer image ships python3 3.14.10-r1, for mercurial. Alpine 3.24 has since split python3-ndbm out at r2 and installs it wherever python3 3.14.10 is present, so the stage's apk add for the CA bundle pulls it beside r1 and fails on a file both own. apk add does not upgrade what is installed; apk upgrade first does. The same conflict on appwrite/base is fixed by 2.5.2. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The stage installed ca-certificates 20261020-r0 or newer to distrust the eMudhra chains. The composer image has shipped that version since its Alpine 3.24 build, with none of those roots in its bundle, so the line installs nothing. It was also the stage's only apk add, and the one failing: composer's image carries python3 3.14.10-r1, and any apk add on it now pulls python3-ndbm r2 beside it. With no install there is nothing to conflict, so this replaces the apk upgrade added before it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The stage no longer installs the CA bundle, on the strength of what the image ships: ca-certificates 20261020-r0, with no eMudhra root. A floating composer:2 could change under that. This pins 2.11.2 at the digest it was checked on, as the base image is pinned. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The findings that requested changes are resolved. See the summary comment for what is still open.
|
How it got there
First ten minutes in tor1
What to watch during the soak
Roll back Revert appwrite-labs/application-configuration#1359 ( |

Moves five parts of
packages/queryonto theutopiaextension: the classifiers, the tokenizers,Query, the AST's parser and serializers, and the schemas. Off by default: nothing changes unless_APP_EXTENSION_LIBRARIESnamesquery.This was a stack of five PRs (this one, #15735, #15739, #15748 and #15753). They are now one, and each part keeps its own section below. The builders are here too, under the same
queryswitch.Methodand the small enums are still PHP.crates/extension/tests/query.phpruns every part on PHP and on the extension and compares the output: 55,481 lines, identical on macOS and on the Alpine image.Without #15328
This branch was built on #15328 (string literals quoted per dialect,
LIKEwith a declared escape, a stricter parser). That is taken back out:59d225636ereverts its merge and458b4a59bereverts the Rust port of it, so the PHP package here is main's plus the changes listed under each part.It came out because it broke SQLite with the extension off. utopia-php/database 10.2.3's SQLite builder appends its own
ESCAPE, the package's began to as well, and SQLite refused the statement. The database library's unit suite went from 9 failures to 63, and Cloud's unit tests failed.Re-landing #15328 is a revert of those two commits, together with a utopia-php/database release that drops its own clause.
The classifiers
What
crates/utopia/query: unchanged fromfeat/rust-utopia-conversion(feat(rust): Users service in Rust, conversion standard and PHP/Rust compat tester #14308) at a962288. It is newer than the copy in chore(crates): utopia-query, utopia-validators and utopia-usage from the conversion branch #15604 (16 files differ), so that PR needs the same revision.crates/extension/src/query.rs: withqueryon, the extension registersUtopia\Query\Type(enum),Utopia\Query\Classifier(interface),Utopia\Query\Classifier\SQL(abstract),MySQL,PostgreSQLandMongoDB.crates/extension/tests/run.shleavespackages/query/tests/E2Eout, because it needs MySQL, PostgreSQL, ClickHouse and MongoDB servers the Extension job does not start.The interface and the enum are registered as well, not left in PHP: a class registered at module start cannot implement a userland interface. PHP code that implements
Classifier, extendsClassifier\SQLwith its ownclassify(), or extends a concrete classifier and callsparent::classify()works as before; the corpus covers each.One thing found on the way
A
#[php_class]that derivesDefaultbreaks PHP subclasses on ext-php-rs 0.16.5:new Sub()returns an object of the Rust class, so the subclass's overrides are never called and$object instanceof Subis false. The classes here do not derive it, and a comment says why.DomainandEmaildo not derive it either, so they are unaffected. Not yet reported upstream.Checked (locally, macOS, PHP 8.5.12)
cargo fmt --all --checkandcargo clippy -p utopia-extension -p utopia-query --all-targets -- -D warnings: clean.cargo test -p utopia-query: 54 passed.packages/query/testswithout E2E, on the extension: 5,622 tests pass. The same suite passes on PHP.crates/extension/tests/query.php: 24,773 corpus lines, identical on PHP, on the extension, and withemails,queryboth on.ReflectionClass::isFinal()isfalseforType; a PHP enum reportstrue. Extending it is refused either way.Benchmark (
crates/extension/bench/query.php, release build, OPcache on, median of 5, ns per call):COM_STMT_EXECUTEreads one byte and returns, so the call into the extension is all there is to measure.Not checked:
run.shitself and the Alpine build: both run only in the Extension job.packages/query/tests/E2Eon the extension. It does not touch the classifiers.The tokenizers
What
crates/extension/src/query/tokenizer.rs: withqueryon, the extension registersUtopia\Query\Tokenizer\Tokenizerand its dialectsMySQL,MariaDB,PostgreSQL,SQLiteandClickHouse.TokenandTokenTypestay PHP. A token is a value object, sotokenize()returns the package's ownTokens, made by its constructor with the cases of its enum;filter()returns the objects it was given.ValidationException, with the same message.crates/extension/src/query.rsbecomesquery/classifier.rs, with the shared exception helper inquery/mod.rs.Tests changed
Five tests in
packages/query/tests/Tokenizer/MySQLTest.phpcalled the privatereplaceHashComments()by reflection, which the native class does not have. They now go throughtokenize():#was left alone: had it been rewritten to a comment, the stray quote would be inside the comment and tokenizing would succeed.Seen red: with the PHP method changed to rewrite every
#, three of the five fail (the other two assert a rewrite that does happen).Checked (locally, macOS, PHP 8.5.12)
cargo fmt --all --checkandcargo clippy --locked -p utopia-extension --all-targets -- -D warnings: clean.packages/query/testswithout E2E: 5,622 tests pass on PHP and on the extension.crates/extension/tests/query.php: 44,813 corpus lines (20,040 of them new), identical on PHP, on the extension, and withemails,queryboth on.==a new one.getIdentifierQuoteChar()exists and returns the dialect's quote, buttokenize()does not ask it, so a subclass that overrides it does not change the quote. Nothing in Appwrite or Cloud does.MariaDBwired to the standard dialect, 703 corpus lines differed. The package's own tests stayed green under that change; they do not cover#comments on MariaDB.Benchmark (release build, OPcache on, median of 5, ns per call):
Most of the Rust time is building the PHP
Tokenobjects through their constructor.Not checked:
run.shand the Alpine build, which run only in the Extension job.Query
Two things that would have broken production
The package's own 5,622 tests passed on the first complete version of this binding. Both problems were outside them, in
utopia-php/database10.1.4, whichcomposer.lockpins and whoseQueryextends this class:Utopia\Database\Query::cursorAfter(array|object $value)is not compatible with an extension method that declares its parametermixed, so PHP raised a fatal error when the class was declared. It also readsself::LOGICAL_TYPES, a constant of arrays, which a class registered at module start cannot have.Query.phpcallsstatic::parseQuery(),static::isMethod()and others mid-parse, and$this->toArray()fromtoString(). The database library overrides those to decode children given as JSON strings and to write a cursor document as its id. The first version called its own Rust code instead.Both are fixed, and both are now in the corpus. Its own
tests/unit/QueryTest.php(18 tests, 325 assertions) passes on PHP and on the extension.What
crates/extension/src/query/value.rs: withqueryon, the extension registersUtopia\Query\NativeQuery, the methods and state ofQuery.packages/query/src/extension.php(a Composerfilesentry) loadspackages/query/extension/Query.phpwhenNativeQueryexists. That declaresQuery extends NativeQuerywith the two array constants, before the autoloader looks forsrc/Query.php. The declaration is outsidesrc/so static analysis readssrc/Query.phpas the one declaration.getValues()returns the array that was stored, andclonecopies nested queries.Method,NullsPosition,CursorDirection,ParsedQueryand the exceptions stay PHP.json_decode()is PHP's own, called from the binding, soparse()accepts, refuses and reports exactly what it did.toString()writes the JSON itself for a query of nulls, booleans, integers, UTF-8 strings and queries like it, and hands anything else to PHP'sjson_encode(). The corpus runs both paths over escapes, invalid UTF-8, floats, arrays, objects and 300 levels of nesting.For subclasses:
new staticmakes the class a method was called on, directly when it keeps the extension's constructor and through its own otherwise, including throughparent::.Query.phpreaches throughstaticruns a subclass's own, in the same order. The same holds fortoArray()andshape()called on a query object.array. The cursor factories takearray|objectand are declaredarray, the nearest type anarray|objectoverride is compatible with.Tests changed
HelperTest::testContainsHasDeprecatedAttributeread the#[\Deprecated]attribute ofcontains()by reflection. It is nowtestContainsRaisesADeprecation, which asserts the deprecation the call raises. The binding raises the same one.Checked (locally, macOS, PHP 8.5.12)
cargo fmt --all --checkandcargo clippy --locked -p utopia-extension --all-targets -- -D warnings: clean.bin/monorepo check query(rector, pint, PHPStan at the package's level): passes.packages/query/testswithout E2E: 5,622 tests pass on PHP and on the extension.utopia-php/database10.1.4tests/unit/QueryTest.php: 18 tests pass on both.crates/extension/tests/query.php: 52,138 corpus lines, identical on PHP, on the extension, and withemails,queryboth on.staticdispatch disabled, 13 corpus lines differed. The package's tests stayed green: none of them has a subclass that overrides those methods.Known differences, each asserted by the corpus:
Queryhas a parent class,NativeQuery.ArgumentCountError; PHP ignores the extras.ArgumentCountError, a subclass of theTypeErrorPHP raises.isset()on a protected property from outside the class istrue.serialize()refuses the object. Nothing in Appwrite serializes a query.One difference not asserted:
groupByType(),getByType(),getCursorQueries(),merge()andvalidate()read a listed query's state directly, where PHP calls its getters. A subclass that overridesgetMethod(),getAttribute()orgetValues()is not consulted there. None of the three subclasses in this repository or the database library does.Benchmark
Release build, OPcache on, median of 5, ns per call:
This is not a performance change.
Queryis a value object over PHP values, so the binding is mostly glue: factories, parsing,toString()and analysis are faster, andnew Query(...), the getters andcloneare slower by the cost of crossing into the extension. That cost is ext-php-rs's: it rebuilds each method's argument descriptions, default values included, on every call. The five rows above fornew Query, the getters,toStringandclonewere measured again after mimalloc and thetoString()change. A subclass with its own constructor, asUtopia\Database\Queryhas, pays thenew Querycost on every factory call. The reason to have it is that the builders can then be moved without converting queries at their boundary.Not checked
run.shand the Alpine build, which run only in the Extension job.bin/monorepo validate. Locally it reports duplicates from a linkedvendordirectory that is not this branch's.queryon. Nothing here turns it on.Queryoutside this repository and the database library.The AST's parser and serializers
What moves
AST\Grammar,AST\Parser, andAST\SerializerwithMySQL,MariaDB,PostgreSQL,SQLiteandClickHouse, overcrates/utopia/query. The builders are their only callers.utopia-php/databasedoes not use the AST.The 25 node classes stay PHP. They are readonly data, and
Queryshowed that a native class makesnewabout twice as slow.AST\Walkerand the visitors stay PHP too, because a walk is only calls into a PHP visitor.One change to PHP, for everyone
The first commit changes
packages/query/src/AST/Serializer.phpwhether or not the extension is on.maindrops the parentheses of an equal-precedence right operand for every operator except-,/and%, so it writesa = (b = c)asa = b = c, which reads back as(a = b) = c. The crate was ported from the fixed serializer onfeat/rust-utopia-conversion, and the corpus found the 260 cases where the two disagreed. I took @eldadfux's fix as it is and added two tests that fail on the old file.Two things worth reviewing closely
Nodes are read and written by property slot. The parser does not call the node constructors. They only assign, and the two that validate check what the parser already checked. The first use in a request verifies every node class's property names and offsets, and throws an
Errornaming the class if the package and the extension disagree.Deep trees run on an allocated stack. My first version overflowed the native stack on a chain of 1,000
NOTs, which PHP handles because it recurses on its heap. Reading one level of a tree costs 3.1 KB of stack in a release build (measured), and a Swoole coroutine has 2 MB. The binding now measures a tree and works on anything deeper than 32 levels on a stack sized for it, usingstacker, which is a new dependency. Nothing on that stack calls PHP code. Under 512 KB and 128 KB fiber stacks, PHP and the extension now stop at the same inputs, where PHP's own engine overflows freeing the objects.Checks
queryandemails,query. The AST adds about 2,100 of them, including 209 statements each cut, dropped and swapped at every token, every pair of 31 operators nested both ways, trees 20,000 levels deep and chains of 8,000 terms.packages/query/tests: 5,624 pass on PHP and on the extension.bin/monorepo check query,cargo fmt,cargo clippy -D warnings: clean.Known differences, asserted in the corpus
serialize()does not call a subclass'sserializeExpression()orquoteIdentifier(). PHP does. No subclass in Appwrite or Cloud overrides them.NOTor sign operators are refused withValidationException. PHP parses until memory runs out. Trees past 100,000 levels are refused the same way.Benchmark
Release build, medians of 3 runs, macOS arm64.
Grammar::isTypeSerializing the 150-term chain is no faster. It is 150 levels deep, so it pays for the measuring pass and the allocated stack.
Not checked
bin/monorepo validatelocally, and Appwrite's E2E suites withqueryon.The schemas
What moves
SchemaandSchema\SQL(abstract), the dialectsSchema\MySQL,PostgreSQL,SQLite,ClickHouseandMongoDB, and the 16Schema\Feature\*interfaces they implement.The blueprints stay PHP:
Table,Column,ForeignKey,Index,CheckConstraint,RenameColumn, their dialect classes, traits and forwarders, and the enums. PHP code fills them with fluent calls and they validate as they are filled. A schema reads a finished blueprint, compiles it withcrates/utopia/queryand returns the package'sBuilder\Statement.Speed
A statement takes 7% to 22% less time than PHP's on the Alpine image. The first commit took 13% to 35% longer, and the second fixes that.
Release builds made by the Dockerfile's
extension-buildstage, run inappwrite/base:2.3.1on arm64, OPcache on, median of 5 alternating rounds. On macOS the same cases run at 0.72 to 0.84 of PHP's time.A profile showed more than half of a
compileCreate()inmallocandfree. Three changes followed:local_dynamic_tlsis what a library loaded withdlopenneeds on musl.Statementis made by setting its property slots. Its constructor only assigns promoted properties, and calling a PHP constructor from Rust costs more thannewdoes in PHP. If the constructor ever does more, this has to follow it.The margin is small because PHP compiles DDL with string concatenation, which it does well, and the extension has to read the blueprint out of PHP objects first. Only DDL calls a schema, so the main gain is still that the crate's DDL is checked against PHP's, statement for statement.
To review
Table\MySQL,Column\ClickHouse, a test's subclass), so a subclass or a class with extra properties still reads right. Reading by name through the property table was twice as slow as PHP.schema_methods!takes the feature list ([views, databases, ...], the same list as PHP'simplements) and writes them.createIndex(unique: ..., rawColumns: ...), and ext-php-rs names a parameter after the Rust one, soschema.rsallowsnon_snake_case. The corpus compares every signature.definition_mut()onTableandColumn, to set a blueprint read from elsewhere.setExecutor()is held in Rust, where PHP's cycle collector does not look. A closure that reaches its own schema is freed at the end of the request. The database library's executor is bound to the database, which does not keep the schema.Checks
crates/extension/tests/query.phpis identical on PHP, onqueryand onemails,query: 55,460 lines, 1,231 of them new. The README lists what they cover.packages/query/testson the extension: 5,624 tests pass.queryand onemails,query.cargo fmt --check,cargo clippy -D warnings, Pint.Known differences
Each is asserted in the corpus and described in the README.
quote(),compileColumnType(), ...) are not there to override or call, and the abstractSchemahas no methods of its own. Nothing in Appwrite, Cloud or the database library subclasses a schema.Featureinterfaces declare no methods.instanceofanswers as before.ParameterDirection.Not checked
queryswitched on.bin/monorepo validate: no file underpackages/changes.The builders
Off unless
_APP_EXTENSION_LIBRARIESnamesquery, like the rest.What
Builder\MySQL,MariaDB,PostgreSQL,SQLite,ClickHouseandMongoDB, the abstractBuilderandBuilder\SQL, theCompilerinterface and the 51Feature\*interfaces.What a subclass can rely on
build(), thecompile*()methods, the clause hooks, the validators and every other helper, 73 in all.parent::runs the native one. An override is handed the package's own objects, and nothing is converted for a method no subclass overrides.fromAst()writes what stays raw SQL with the serializer a subclass'screateAstSerializer()returns.bindings,pendingQueriesandresolvedAttributeCacheare protected properties it reads, assigns and appends to.static,build()returnsStatement,select()takesarray|string.These need PHP's post-startup hook, because
#[php_class]cannot express them:staticand union types, attaching the interfaces, and creating an object with its state already in it.A fix for
Querythat came out of thisserialize()of aQuerythrew. utopia-php/database hashesserialize($queries)for its cache keys. It now writes byte for byte what PHP's class writes, andunserialize()reads it, so either reads what the other wrote.Tests changed
Two tests in
packages/query/tests/Regression/CorrectnessRegressionTest.phpread the PHP builder's source file and a private property by reflection. They are skipped when the class is the extension's.Checked (locally, macOS, PHP 8.5.12)
crates/extension/tests/query-builders.php: 15,797 cases, identical on PHP and the extension. They include a subclass that overrides every dispatched helper and records the order they ran in.queryon, and with the builders on (two skipped, above).opcache.phpwith a PHP subclass of each of the 60 builder classes and interfaces.Not done
Builder\Trait\*traits works only when the trait touchespendingQueriesandbindingsalone.run.shnow runs the builders with the query package's tests. I changed it without being able to run it: it runs only in the Extension job.🤖 Generated with Claude Code