Referencia · §8.3

Parser

lexer, parser, ast

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

How deep a statement may nest is bounded (parser::MAX_NESTING, 1000; 500 in WebAssembly, where the host’s stack bounds it too): every stage after the parser walks the statement by recursion, so its tree’s height bounds the stack they take. A level of an expression counts 1 — parentheses, operators chained (a OR b OR …), casts, subscripts, joins —, a subquery 8 and a set operation 3, as they take that much more stack; past it the statement fails with 54001. Threads that run statements (sessions, parallel workers) have nucleus_platform::SESSION_STACK, 16 MB (8 MB on 32-bit), which the deepest statement allowed fits in (about 6 MB measured).

Statements: CREATE TABLE [IF NOT EXISTS] (column constraints PRIMARY KEY, NOT NULL, UNIQUE, DEFAULT, CHECK, REFERENCES; table constraints PRIMARY KEY (…), UNIQUE (…), CHECK (…), FOREIGN KEY (…) REFERENCES …, each with an optional CONSTRAINT name), CREATE TABLE [IF NOT EXISTS] t [(names)] [WITH (…)] AS query [WITH [NO] DATA] (the query’s columns, names given replacing theirs from the left, with their types — without a length or a numeric’s precision — and no constraints; filled by the query unless WITH NO DATA; tagged SELECT n), DROP TABLE [IF EXISTS] … [CASCADE], CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] (of columns and expressions; CONCURRENTLY: built online, §8.7), DROP INDEX [IF EXISTS], ALTER TABLE … ADD [COLUMN] [IF NOT EXISTS] …, ALTER TABLE … ADD [CONSTRAINT n] FOREIGN KEY | CHECK | UNIQUE …, ALTER TABLE … DROP CONSTRAINT [IF EXISTS] n, ALTER TABLE … RENAME …, … DROP COLUMN …, … ALTER COLUMN … SET / DROP DEFAULT | SET / DROP NOT NULL, ALTER INDEX … RENAME TO (§8.35), INSERT INTO t [AS a] … VALUES | SELECT | DEFAULT VALUES [ON CONFLICT …] [RETURNING] (OVERRIDING SYSTEM | USER VALUE after the columns; DEFAULT in a VALUES row: the column’s default), UPDATE … SET … [WHERE] [RETURNING] (SET c = DEFAULT), DELETE … [WHERE] [RETURNING], TRUNCATE [TABLE] t, … [CONTINUE | RESTART IDENTITY] [CASCADE | RESTRICT] (every row deleted as DELETE deletes them — in the transaction’s snapshot, under DELETE’s privilege and row policies; a table another references by a foreign key only with that one, named or by CASCADE; RESTART IDENTITY restarts the sequences their columns own, at once), queries (SELECT … INTO [TABLE] t …: CREATE TABLE t AS the query, as PostgreSQL’s), BEGIN/START TRANSACTION (ISOLATION LEVEL …, READ ONLY|WRITE, AS OF TIMESTAMP|COMMIT …), COMMIT/END, ROLLBACK, SET TRANSACTION …, SET name = value, SHOW name, EXPLAIN, ANALYZE [table], CREATE STATISTICS [IF NOT EXISTS] name [(ndistinct, dependencies, mcv)] ON a, b [, …] FROM t (2–8 columns counted together by ANALYZE; the kinds are accepted, every group gets the same; names the database’s, the owner’s), DROP STATISTICS [IF EXISTS] name, COMMENT ON TABLE t | COLUMN t.c IS 'text' | NULL (the owner’s; '' removes it too; kept in the table’s record, shown in nc_catalog.tables and .columns, ncsql \d and pg-compat’s obj_description / col_description / pg_description), COPY t [(columns)] FROM STDIN [[WITH] (FORMAT text | csv, HEADER [bool], DELIMITER 'c', NULL 'n', QUOTE 'q', ESCAPE 'e')] (or the older WITH CSV HEADER DELIMITER ';' …; §8.7), COPY t [(columns)] | (query) TO STDOUT [options] (§8.7). Table names may be qualified with public. (and, to read, nc_catalog., pg_catalog., information_schema.).

Queries: WITH [RECURSIVE] name [(cols)] AS (…) — at the statement’s top also before INSERT, UPDATE and DELETE, and with a CTE that is one of them (WITH d AS (DELETE … RETURNING *) INSERT INTO t SELECT * FROM d; inside a subquery 0A000, as PostgreSQL’s). Such a CTE’s statement runs once, before what comes after it, read or not; its RETURNING rows are what a reference reads (without RETURNING a reference is 0A000). A query CTE beside them is read once, where it stands, as PostgreSQL materializes it: what comes after it reads what it read, not what was written since — WITH m AS (SELECT …), i AS (INSERT … WHERE NOT EXISTS (SELECT 1 FROM m)) SELECT (SELECT count(*) FROM m) counts the rows before the insert (WITH RECURSIVE‘s queries excepted: bound where they are read). Unlike PostgreSQL’s, which all read the statement’s snapshot, a part that reads a table itself sees the writes of the CTEs before it. A recursive one may end in SEARCH DEPTH | BREADTH FIRST BY c… SET s and CYCLE c… SET m [TO v DEFAULT d] USING p (PostgreSQL 14’s, written as its rewrite: crates/sql/src/search_cycle.rs). Depth first, s is the record[] path of ROW(c…) from the base row; breadth first, s is ROW(depth, c…) (the depth, from 0, carried in a hidden column); ORDER BY s lists the rows in that order. CYCLE adds p, the path of ROW(c…), and m (true/false unless given), v on the row whose ROW(c…) is already on its parent’s path: that row is given but not followed, so UNION ALL ends on a graph with cycles. The recursive term must read the query in its own FROM (a join there too), not in a subquery (0A000, as PostgreSQL’s). WITH RECURSIVE name [(cols)] USING KEY (k…, [min(c) | max(c)]…) AS (base UNION [ALL] step) (DuckDB’s, from Hirn and Grust’s “A Fix for the Fixation on Fixpoints”; not in PostgreSQL) keeps the query’s rows as a table by key: each round’s rows (the base’s first) are applied to it — a key’s row replaced, its columns the last row’s, or the least / greatest non-NULL value of those named with min / max —, a key’s rows in one round combined the same way. The next round reads all of the round’s rows (UNION ALL) or the rows of the keys new or changed (UNION, so a cycle ends when nothing improves); the query’s rows are the table’s, in the order keys first came. In the step, recurring.name reads the table as the round began (not in a subquery, 42P19). Shortest paths are USING KEY (node, min(dist)) with UNION; NULL keys are one key; no SEARCH / CYCLE with it (0A000); min and max only (0A000); a key column must hash (42883). Property graphs (SQL/PGQ, ISO/IEC 9075-16; crates/sql/src/graphs.rs): CREATE PROPERTY GRAPH g VERTEX TABLES (t [AS a] [KEY (c…)] [labels], …) [EDGE TABLES (t [AS a] [KEY (c…)] SOURCE [KEY (c…) REFERENCES] v [(c…)] DESTINATION [KEY (c…) REFERENCES] w [(c…)] [labels], …)], labels LABEL l [PROPERTIES (expr [AS name], …) | PROPERTIES ARE ALL COLUMNS [EXCEPT (c…)] | NO PROPERTIES] (or DEFAULT LABEL, or bare PROPERTIES … for the table’s own label); DROP PROPERTY GRAPH [IF EXISTS] g (its owner or a superuser, 42501). A graph is a definition over tables, not data: the standard’s defaults are resolved when it is made — a table’s key its primary key, its label its alias, its properties all its columns, an edge’s end the edge table’s one foreign key to that vertex table (two are ambiguous, 42P17) — and kept spelled out (nc_catalog.property_graphs: name, owner, tables, definition; the schema’s dump). A label has the same property names wherever it is (42P17). While a graph names a table or a column of it, DROP TABLE, ALTER TABLE … DROP COLUMN and the renames are refused (2BP01); with CASCADE the drops take the graph too; a role owning a graph is not dropped. In FROM, GRAPH_TABLE (g MATCH pattern [, pattern…] [WHERE cond] COLUMNS (expr [AS name], …)) [AS alias [(names)]] is the table of the pattern’s matches. A pattern alternates vertices (v [IS label] [WHERE cond]) and edges -[e …]->, <-[e …]-, -[e …]- (either way) or bare ->, <-, -; :label is the same as IS label; label expressions combine with |, &, ! and % (any label). A variable named twice is one element; two patterns sharing a variable are joined by it; patterns match as joins do (two edge variables may be one edge). A property a table of the variable’s labels lacks is NULL. An edge quantified {m,n}, {n}, {m,}, {,n}, + or * is a walk of that many edges (each walk a row), over edge tables that each join one vertex table to itself by the same columns (else 0A000); p = … names the path and path_length(p) is its number of edges; a quantified edge’s variable is not read outside it (0A000). Without an upper bound a walk needs ANY SHORTEST (0A000): p = ANY SHORTEST (a)-[e]->+(b) gives one walk of the fewest edges for each pair of ends (a path of one quantified edge). GRAPH_TABLE is rewritten into the query it means before binding — for each choice of tables for its variables whose edges join them (at most 4,096, 54000), one join of derived tables over them, UNION ALL; a quantified edge a recursive CTE over its edge tables (ANY SHORTEST with USING KEY (start, end, min(len))), started at its first vertex’s own conditions — so the optimizer, every executor, privileges (the reader’s, on the tables) and row security treat it as the same query written by hand. Not taken: ALL SHORTEST, ANY k, path modes (TRAIL, ACYCLIC, SIMPLE), quantified groups of several edges, ALTER PROPERTY GRAPH. SELECT [DISTINCT], FROM with comma joins, [INNER|LEFT|RIGHT|FULL|CROSS] JOIN … ON | USING, subqueries and functions in FROM (generate_series, unnest, any scalar function; WITH ORDINALITY), LATERAL before a subquery or a function (functions are lateral without it, as PostgreSQL’s), alias column lists (AS t (a, b)), WHERE, GROUP BY (expressions, positions, aliases — a bare name a column of the FROM first, as in SQL-92 and PostgreSQL; GROUPING SETS, ROLLUP, CUBE, (), GROUP BY DISTINCT, with GROUPING(…) — a grouping per set, their rows together, §8.4), HAVING, WINDOW name AS (…), UNION | EXCEPT | INTERSECT [ALL] (INTERSECT binding tighter), VALUES, ORDER BY (ASC|DESC, NULLS FIRST|LAST, positions, aliases, expressions), LIMIT, OFFSET. Expressions: arithmetic, ||, the integers’ bitwise & | # ~ << >> (shifts wrapping as PostgreSQL’s), comparisons, AND/OR/NOT, IS [NOT] NULL|TRUE|FALSE|UNKNOWN|DISTINCT FROM, [NOT] BETWEEN, [NOT] IN (list | subquery) (of an empty subquery, IN is false and NOT IN true, a NULL operand’s too), [NOT] EXISTS, op ANY|SOME|ALL (array | subquery), scalar subqueries, [NOT] LIKE / ILIKE, ~ ~* !~ !~* (regular expressions, linear-time), CASE, CAST / ::, typed literals (INTERVAL '90' DAY, INTERVAL '5' DAY TO HOUR: a bare number counts the last field, the value cut below it, as in PostgreSQL), E'…' strings, COLLATE (accepted, ignored: text compares bytewise), OPERATOR(op), $n, an array’s @>, <@ and && (PostgreSQL’s: two arrays of one type, else 42883; every element of the right found in the left, or one in both, by equality — a NULL element equal to none, duplicates and dimensions ignored; issue #24), extract(field FROM x), position(sub IN s), substring(s FROM n FOR m), overlay(s PLACING r FROM n [FOR m]), trim([LEADING | TRAILING | BOTH] [chars] FROM s). Functions: lower upper length trim substr left right replace repeat strpos concat lpad rpad ltrim rtrim btrim split_part concat_ws translate reverse initcap overlay quote_ident quote_literal cbrt coalesce nullif greatest least abs round trunc floor ceil sign mod sqrt power regexp_replace version now current_timestamp current_date localtimestamp clock_timestamp extract date_part date_trunc make_date age justify_days justify_hours justify_interval to_timestamp array_length array_upper array_lower cardinality array_append arraycontains arraycontained arrayoverlap array_to_string pg_typeof current_user current_database current_schema current_setting snapshot_commit (the last: the commit the statement’s transaction reads, §8.28; and the catalog functions of §8.11); aggregates count sum avg min max string_agg array_agg bool_and bool_or every any_value (the last SQL:2023’s: a value of the group’s that is not NULL, the first seen; with DISTINCT, count(*), ORDER BY inside the call, FILTER (WHERE …) after it — also on an aggregate over a window); window calls f(…) OVER name | ([name] [PARTITION BY …] [ORDER BY …] [ROWS | RANGE | GROUPS {start | BETWEEN start AND end} [EXCLUDE CURRENT ROW | GROUP | TIES | NO OTHERS]]), a bound UNBOUNDED PRECEDING | n PRECEDING | CURRENT ROW | n FOLLOWING | UNBOUNDED FOLLOWING (§8.5).

Not yet: COPY … TO or FROM a server-side file, TIMETZ, time zones other than UTC, multi-dimensional arrays, user functions, the rest of issue #16’s forms.