Craticula

SQL rendering

The same request must produce the same statement shape every time. Identifiers are always quoted, parentheses follow the structure of the filter, and negative operators use the negated operator. The page also lists where an engine differs, such as Postgres array parameters, collations and Oracle's empty-string rule.

addendum: the TRD's §7 enumerates SEM-1..SEM-7 and stops, but the conformance fixture suite needs a literal answer and no other document owns one)

The SEM-1..SEM-7 sections above pin semantics and say so explicitly — their snippets are illustrative. That was enough while nothing tried to satisfy them. It stopped being enough in #1638: the fixture suite (#1630) was hand-authored by seven parallel agents with no compiler to check it, and a research pass found the same IR construct rendered several different ways from identical inputs across categories — two spellings of notIn, two of notContains, two parenthesisations of a null-inclusive negative, two of a composite and/or, two of notBlank, and identifier quoting in one category out of nine. No single compiler can satisfy contradictory oracles under T-1a artifact equality, so the answers are pinned here, once, and every language port inherits them instead of rediscovering them.

Each rule below is the form the spec/fixtures/*/expected/postgres.artifact.json files now contain. Postgres is the reference dialect (§5); where a rule is Postgres-specific rather than universal, it says so and names what the other dialects do instead.

SQL-0. GridSchema.source is where the table comes from. A compiled query names a physical collection — FROM employees, a Mongo collection, a Search index — and until #1638 that name existed in no input: not in the AG Grid wire request (no SSRM payload carries one, and none should: it is exactly the kind of thing SEC-1 keeps client-side callers away from), not in GridSchema, not in the TRD. It was recoverable only from a fixture's directory name. grid-schema.schema.json therefore declares a required source string, alongside the field allowlist (SC-2) and the per-backend physical mappings (SC-4) that are already host-declared and already never client-influenced. A compiler MUST take the collection from schema.source and MUST NOT accept one from the request.

SQL-1. Always quote identifiers — every column, every alias, and the table. Postgres renders SELECT * FROM "employees" WHERE "age" >= $1, never the bare form.

Why. Unquoted identifiers are not "the same thing without the noise" — PostgreSQL case-folds them to lowercase. The fixture suite contains real proof: dialect-parity/ declares camelCase physical columns (lastName, employeeCode, jobTitle) and, before #1638, emitted them unquoted, so WHERE lastName ILIKE ... would reach the server as where lastname ilike ... and fail against the table those fixtures describe. The artifact-equality tier (T-1a) cannot see that class of bug at all — it compares strings — so it would have sat in the oracle until the execution-equality tier (T-1b, #1624) ran the query against a real database. Quoting also makes Dialect.QuoteIdentifier unambiguous: it is applied to every identifier, so there is no second rule about when to skip it, and no dialect needs a keyword blocklist to stay correct.

Must NOT. Must NOT quote conditionally ("only when it needs it", "only mixed-case names") — that reintroduces the blocklist and makes the fixture oracle depend on a keyword list that differs per dialect and per server version. Must NOT quote things that are not identifiers: the collation name in COLLATE craticula_ci, parameter placeholders, and the '%' / '\' / '' literals of the ILIKE and blank scaffolding are all left exactly as they are.

The rule is universal, and as of #1639 so is the fixture suite. #1638 re-authored only the Postgres artifacts, because the rule ("always quote") is dialect-independent while the quote character is not, and choosing each engine's is part of writing that engine's Dialect. #1639 wrote the other three and closed the gap: all 55 mysql/mssql/sqlite arms in spec/fixtures/dialect-parity/ are now quoted, so 006-022's parity sets are no longer mixed — seven artifacts each since #1642 added the oracle arm, six before it. The characters, with the escape each engine uses for one appearing inside an identifier:

DialectQuoteEscape inside an identifier
Postgres"" → ""
SQL Server[…]] → ]]
MySQL / MariaDB`` → ``
SQLite"" → ""
Oracle (#1642)"" → ""

MySQL uses backticks rather than " because " only quotes an identifier under ANSI_QUOTES, which is off by default and is a session mode a compiler must not assume of a host's connection.

Oracle is the second engine where quoting is a correctness rule rather than a hygiene one, and it folds the other way from Postgres: an unquoted identifier is upper-cased, so FROM employees reaches the server as FROM EMPLOYEES. Always-quoting neutralises that in the statement but moves the obligation into the host's DDL, because Oracle also stores an unquoted-CREATEd name folded — so a table created as CREATE TABLE employees cannot be reached by FROM "employees" at all (ORA-00942). Every source and physical column in this fixture suite is lowercase or camelCase (employees, sales_fact, lastName, fiscal_year), so on Oracle they all require quoted DDL; that is recorded as a host obligation in spec/fixtures/dialect-parity/README.md, not silently assumed. Identifier length is a non-issue in the other direction: Oracle's limit is 30 bytes before 12.2 and 128 from 12.2, this project's Oracle dialect assumes 12.2+ (see SQL-6), and the longest identifier any fixture declares is employeeCode at 12 characters.

SQL-3 and SQL-4 are now exercised on every dialect too (017/018's new arms), and SQL-4 is where the five genuinely part company: Postgres binds one array parameter, the other four — SQL Server, MySQL, SQLite and Oracle — bind N scalars, so even params.length differs across the arms of one fixture.

SQL-2. Parenthesisation is structural, not cosmetic — one rule per construct, applied always. Correct SQL admits many equivalent bracketings; artifact equality admits one. The four cases:

SQL-3. A negative operator renders with the negated operator, not an outer NOT (...). notContains is "c" NOT ILIKE '%' || $1 || '%' ESCAPE '\', not NOT ("c" ILIKE ...).

Why. Every other negative operator already does this — neq renders <>, not NOT (=); notIn renders <> ALL, not NOT (= ANY) — so the outer-NOT spelling made notContains the single exception, for no gain. Keeping the negation in the operator also keeps the ESCAPE clause attached to the pattern-match expression it belongs to, which is what SEM-7 requires. Note the deliberate contrast with the previous rule: an outer NOT (...) is correct and required for a tree-level notNode, because there the negation applies to an arbitrary subtree, not to one comparison. The distinction is the IR shape, never the surface similarity of the two.

SQL-4. Set membership is one array parameter on Postgres — = ANY($1) / <> ALL($1), cast to the column type for the three string-encoded types — and that is a dialect rendering, not a universal one. The set's values are bound as a single array parameter, so the placeholder count never depends on the value count: "status" = ANY($1) with params: [["active", "pending"]], never IN ($1, $2) with two scalars.

The array is cast for decimal, date and datetime (Bug #2304). Those values are strings (AR-7), so a host binds the array as text[], and PostgreSQL has no numeric = text, date = text or timestamptz = text operator. On Postgres the placeholder is therefore cast to the field's column type, and only for these three types: "price" = ANY($1::numeric[]), "day" = ANY($1::date[]), "at" = ANY($1::timestamptz[]), and <> ALL($1::numeric[]) (::date[], ::timestamptz[]) likewise. string, int64, double and boolean stay uncast (= ANY($1)), and the parameter list is unchanged (params: [[...]]). SQL Server, MySQL, SQLite and Oracle render exactly as before (N scalars). The cast is an explicit cast from the text[] a host binds for a string array. Consequences: (a) the host's datetime column is timestamptz, an absolute instant (SEM-4). A timestamp column without a zone makes Postgres compare through the session time zone and can shift rows silently; that is a host obligation, like SQLite's fixed-width datetime text. (b) A null element in the list (AR-7 nullValue beside real values) is allowed and stays NULL inside the array. An empty list is a constant under SEM-8 (1 = 0 / 1 = 1) and never reaches this cast. (c) Craticula.EntityFrameworkCore hands typed values to the provider and is out of scope.

Why it is behind the dialect interface. ANY(array) does not exist in SQL Server, MySQL or SQLite. #1639 renders those three as IN (...) with N scalar parameters. The query builder therefore MUST NOT emit either spelling itself — it asks the dialect for an in-list rendering and passes it the field and the set. A builder that contains an if for this is the BM-1 smell docs/architecture/c4-components-sql-compiler.md warns about. (This rule is also the reason the two spellings must not be treated as interchangeable in a fixture: params.length differs between them, so a port that picks the other one fails on the parameter list even when the SQL text is accepted.)

SQL-5. The substring family's pattern operator, escape clause and escape alphabet are all per dialect — three axes, not one. SEM-7 mandates "a SQL LIKE pattern with a matching ESCAPE clause" and, read literally, that is wrong on two of the four v1 dialects. The rule as the fixture suite actually pins it (#1639's D1/D3, and its review pass; spec/fixtures/dialect-parity/README.md keeps the story-level rationale):

DialectOperatorEscape clauseEscape alphabet
PostgresILIKE (CI) / LIKE (CS)ESCAPE '\'\ % _
SQL ServerLIKE (both, + a collation — SQL-6)ESCAPE '\'\ % _ [
MySQL / MariaDBLIKE (both)ESCAPE '\\'\ % _
SQLiteLIKE (CI) / GLOB (CS)ESCAPE '\' / none\ % _ / class-wrapping
Oracle (#1642)LIKE (both, + a collation — SQL-6)ESCAPE '\'\ % _

Three of those cells are correctness, not spelling, and each is invisible to the artifact-equality tier if a port gets it wrong in isolation:

Oracle contributes no fourth surprise, and that is worth stating so a port does not copy the wrong neighbour: it has no ILIKE (so the case-insensitive direction is a collation, like SQL Server's), but a backslash inside an Oracle string literal is an ordinary character, so the clause is ESCAPE '\' and MySQL's doubled spelling would be wrong; and its LIKE has exactly two metacharacters, % and _, so the shared escape alphabet is the whole alphabet and T-SQL's [ is T-SQL's alone.

Must NOT. A port MUST NOT read SEM-7's "LIKE … with a matching ESCAPE clause" as universal: on the SQLite case-sensitive path there is no LIKE and no ESCAPE clause to attach one to, and a port that emits them anyway both fails dialect-parity/021's sqlite arm and returns the wrong rows. It MUST NOT widen the shared escape alphabet to the union of all five either — \[ in a Postgres/MySQL/SQLite/Oracle pattern is a literal backslash followed by a bracket, which is not what the user searched for.

SQL-6. Where an engine's default collation disagrees with the field's declared case sensitivity, the compiler MUST spell the mechanism explicitly — in both directions. SEM-1's second Must-Not ("must NOT default to case-sensitive because the engine's default is") has a mirror image that is just as wrong and much easier to ship: leaving a field declared caseSensitivity: "sensitive" bare on an engine whose default collation folds case. SQL Server and Azure SQL ship SQL_Latin1_General_CP1_CI_AS; MySQL's server default is a _ci family; Oracle's default column collation is USING_NLS_COMP, which resolves through the session's NLS_COMP/NLS_SORT. On all three, "emit no case-insensitivity mechanism" can mean "compare case-insensitively", so the host's explicit opt-in is silently discarded and the SQL reads as though it were correct.

DialectCase-insensitiveCase-sensitive
PostgresCOLLATE craticula_cinothing — default collation is deterministic
SQL ServerCOLLATE Latin1_General_CI_ASCOLLATE Latin1_General_CS_AS
MySQL / MariaDBnothing — column's declared collationnothing — host DDL obligation (see below)
SQLiteCOLLATE NOCASEnothing — default sequence is BINARY
Oracle (#1642)COLLATE BINARY_CICOLLATE BINARY

Why Oracle spells both, and what version that pins. Oracle has no ILIKE, so there is exactly one mechanism to choose and it has to serve the exact-match family, ordering, set membership, the ORDER BY and the substring family. Two candidates exist and only one can:

Setting NLS_COMP = LINGUISTIC on the session is rejected on the same ground as SQLite's PRAGMA case_sensitive_like: connection-level state a compiler must not depend on. And because the default is that session state, the case-sensitive direction cannot be left bare either — hence COLLATE BINARY. Unlike MySQL, Oracle has one portable spelling for it, so it is a token rather than a host DDL obligation.

Whatever a dialect spells, it spells on every construct where SEM-1 applies at all, per SEM-1's "same mechanism in every context on a field": the scalar comparison, the set membership, the substring match and the ORDER BY. dialect-parity/014 (eq), /018 (notIn) and /021 (contains) pin the case-sensitive direction; /006, /016, /007 pin the insensitive one.

The exception is the bucket-identity keys, where SEM-1 does not apply in either direction: a GROUP BY key, a groupKeys drill-down match and a grouped level's ORDER BY spell nothing at all (GRP-2), and so do BM-3's SELECT DISTINCT column and its ORDER BY (GRP-6). This table therefore has no column for them, and on the three engines whose default folds case — SQL Server, MySQL and Oracle, i.e. every row of this table that spells the case-sensitive direction as something other than "nothing" — that "nothing" is a host DDL obligation of exactly the kind the MySQL row below records — see GRP-2's own accepted-divergence paragraph. A drill-down leaf's ORDER BY is not one of these keys and is covered by the table normally; so is a set filter's search prefix, which is a filter on the distinct column rather than the distinct key itself.

Why MySQL is the exception, and what a host owes. Case sensitivity there is a property of the column's declared collation, which the statement cannot override portably — MySQL's case-sensitive collation names are charset-specific (utf8mb4_bin, utf8mb4_0900_as_cs, MariaDB's own set) rather than one spelling a compiler can pin. A field declared caseSensitivity: "sensitive" therefore requires a _bin/_as_cs column collation in the host's DDL, or the declaration has no effect. That is a documented host obligation (PERF-4's per-backend index-guidance page), not a gap the compiler silently fills with a guessed collation name.

Must NOT. A compiler MUST NOT infer "case-sensitive" from the absence of a case-insensitivity mechanism, and a Dialect seam MUST NOT carry this decision as a boolean: false would have to mean both "text, compare case-sensitively" and "not a text comparison at all", and the two need opposite renderings — SQL Server rejects a COLLATE clause on an int/date expression outright ("COLLATE clause cannot be used on expressions of type int"), and Oracle likewise accepts COLLATE only on a character operand. The decision is three-valued at the seam or it is wrong at one end of it.

SQL-7. On an engine that treats the empty string as NULL, blank's text arm is IS NULL and nothing more. SEM-2 and SQL-2 give blank two shapes chosen by field type: ("c" IS NULL OR "c" = '') for string, "c" IS NULL for everything else. On Oracle the first one is wrong, and the second is what a string field must compile to as well.

Dialectblank on a string fieldblank on any other type
Postgres("c" IS NULL OR "c" = '')"c" IS NULL
SQL Server("c" IS NULL OR "c" = '')"c" IS NULL
MySQL / MariaDB("c" IS NULL OR "c" = '')"c" IS NULL
SQLite("c" IS NULL OR "c" = '')"c" IS NULL
Oracle"c" IS NULL"c" IS NULL

Why this is a correctness rule and not a redundant-disjunct tidy-up. Oracle documents that a character value of length zero is NULL. So "c" = '' is "c" = NULL, which under SQL's three-valued logic is UNKNOWN for every row — not FALSE, and that distinction is the whole rule:

operatora row whose value is NULLa row whose value is 'abc'
blank = (c IS NULL OR c = '')TRUE OR UNKNOWN → TRUE → matched ✓FALSE OR UNKNOWN → UNKNOWN → not matched ✓
notBlank = NOT (…)NOT TRUE → FALSE → not matched ✓NOT UNKNOWN → UNKNOWN → not matched ✗

A WHERE clause keeps only rows evaluating to TRUE, so blank is accidentally right and notBlank returns the empty result set — every row filtered out, on syntactically valid SQL, with no error. That is a silently empty grid, and the artifact-equality tier (T-1a) cannot see it, which puts it in the same class as MySQL's unparseable ESCAPE '\' (SQL-5) and a bare LIKE on a case-sensitive SQLite field (SQL-5's second bullet).

Where the decision belongs. This is an engine fact, not a rendering: the blank composition — and therefore SEM-2's "notBlank is blank's compiled text negated, never re-derived" — stays in the query builder, which asks the dialect a single yes/no question ("is '' NULL here?") and picks the arm. A Dialect.renderBlank method would instead have four of five implementations byte-identical, and every one of the five would have to reach back into the semantics layer for the field-type half of the answer. Equally, the question must NOT be answered wherever that field-type half is resolved (Craticula's SemanticsResolver): that layer knows the schema and nothing about engines, and teaching it a dialect name inverts the dependency the Dialect seam exists to draw. ("Otherwise blank and notBlank could drift apart" is not one of the reasons, though it is the first one a reader reaches for: the negation is composed over whatever text the blank half returned either way, so no design in the running admits drift.)

Must NOT. A compiler MUST NOT emit the = '' disjunct on an engine where '' is NULL "because it is harmless" — it is not harmless, it poisons the negation. It MUST NOT fix only blank and leave notBlank alone: blank is the operator that already worked, and a port that tests only the positive direction will see nothing wrong. And it MUST NOT reach the collapsed form by special-casing the field type (e.g. treating string as non-text on Oracle) — the type answer and the engine answer are different questions that happen to coincide here, and conflating them changes SEM-1's mechanism selection for the same field.

The Must-NOTs above are not the whole truth about Oracle, and this list is not exhaustive. One Oracle value escapes the rule entirely: EMPTY_CLOB() produces a zero-length LOB that is not NULL, so a column holding it is found by neither IS NULL nor = '', and blank misses it on either arm. Detecting it needs dbms_lob.getlength(c) = 0, which the compiler cannot emit because grid-schema.schema.json carries no physical type — a field declares string, and whether the host stored that as VARCHAR2, NVARCHAR2 or CLOB is not in the contract. This is therefore a documented limitation of blank on Oracle CLOB columns, not a defect in the rule: a host that maps a string field onto a CLOB and writes EMPTY_CLOB() into it gets a row that blank does not match and notBlank does. Recorded so the list above reads as complete about what it covers rather than complete about Oracle. Closing it would need a physical-type declaration in the schema, which is a /v1/ contract change and belongs to a story of its own.

SQL-7(b). The same engine fact makes an empty bound value uncompilable on Oracle, and a compiler targeting it MUST reject rather than render. $defs/stringValue's value carries a maxLength and no minLength, so "" is a legal IR value on every backend. On Oracle it binds as NULL, and the resulting statement is valid SQL that returns the wrong rows in silence:

RequestPostgres / SQL Server / MySQL / SQLiteOracle, if rendered
eq ""the rows whose value is the empty stringno rows (c = NULL is UNKNOWN)
neq ""every row except those, NULLs included (SEM-2)only the NULL rows — wrong rows, not no rows
contains ""every non-NULL row (LIKE '%%')no rows — '%' || NULL || '%' is itself NULL
in ["", "x"]either value matchesthe "" member is inert; notIn matches no row at all

So the rejection covers all three paths a string value can reach — the scalar comparison family, set membership, and the substring family — and not merely eq. It is a compiler error naming the engine fact, in the same register as GRP-4's "a sort key the projection does not contain is rejected rather than rendered": a plausible statement returning wrong rows is worse than a refusal.

Why this is scoped to the dialect and not to the IR. Adding minLength: 1 to stringValue would forbid, across the whole contract and every backend, an input the other four engines handle correctly — a /v1/ schema change with its own compatibility question, deliberately deferred to its own story rather than taken as a side effect of adding a dialect. A caller that wants to ask "is this value empty or absent" is asking for SEM-2's blank/notBlank, which SQL-7 above compiles correctly on Oracle. No fixture binds an empty value on any backend, so nothing in the suite changes.

Pinned by dialect-parity/019, whose oracle arm is the only one of that fixture's five SQL arms that is not its Postgres arm with tokens substituted; SQL-7(b) is pinned by unit tests alone (DialectRenderingTests), there being no artifact for a request that does not compile.

SQL-8. On Postgres the placeholder of a scalar comparison on a decimal, date or datetime field is cast to the column type — and that is a dialect rendering, not a universal one. The sibling of SQL-4, for the scalar operators (Bug #2320). Those values are strings (AR-7) and a host binds a string parameter as text; PostgreSQL has no numeric >= text, date >= text or timestamptz > text operator. On Postgres the placeholder of every scalar comparison is therefore cast to the field's column type, and only for these three types: "amount" >= $1::numeric, "day" >= $1::date, "at" > $1::timestamptz. "Scalar comparison" is eq, neq, gt, gte, lt, lte, each bound of inRange ("day" >= $1::date AND "day" < $2::date) and every date preset (AG-2), which expands to a half-open inRange and renders through the same comparison. string, int64, double and boolean stay uncast, and the parameter list is unchanged (the cast is in the SQL text only). SQL Server, MySQL, SQLite and Oracle render exactly as before, and so do the MongoDB and OpenSearch backends. Consequences: (a) the host's datetime column is timestamptz, as in SQL-4(a); with a timestamp column Postgres compares through the session time zone and can shift rows silently. (b) A null value (AR-7 nullValue) stays valid: NULL::numeric is a typed NULL, and the parameter list still carries the null. (c) Craticula.EntityFrameworkCore hands typed values to the provider and is out of scope.

Why it is behind the dialect interface. The cast is a PostgreSQL spelling; the query builder MUST NOT branch on the dialect for it (the BM-1 smell of SQL-4). The dialect is handed the field type with the value and decides.

Cross-links. grid-schema.schema.json (source), $defs/andNode, $defs/orNode, $defs/notNode, $defs/unaryOperator (blank, notBlank), $defs/binaryOperator (notContains, contains), $defs/setOperator (in, notIn), $defs/textOptions (caseSensitivity), SEM-1, SEM-7, SEC-4, AGG-6 (the one aggregate wrap this family renders, and the only backend that renders one), and BM-1's Dialect interface.