# gizmodel/sql/ast

The SQL syntax tree. One record shape per kind of thing (expression, query, statement), each with an `op` naming what it is and the fields that op uses, so the planner dispatches by op through tables of functions instead of matching every case everywhere. Every dialect parses to these same nodes: the dialects differ in spelling, not in meaning, except where `Dialect` says.

```gizlang
import * as Ast from "gizmodel/sql/ast";
```

## Types

### `Expr`

```gizlang
type Expr = { op: string; args: Vec<Expr>; value: Value; name: string; table: string; negated: bool; distinct: bool; star: bool; ty: string; query: Vec<Select>; filter: Vec<Expr>; window: Vec<Window>; paren: bool; at: i64; }
```

An expression. `op` is one of:
 lit (value), param (name: "1", "2"...), column (table, name), star (table: "" or a name),
 neg, not, bitnot (args[0]); the binary operators + - * / % || = <> < <= > >= and or & | << >>
 -> ->> <-> <=> <#> @@ (args[0], args[1]);
 call (name, args, distinct, star for count(*), filter, window);
 case (args: [operand?] whens/thens... else?; `negated` true when there is an operand, `distinct`
 true when there is an else); cast (args[0], ty); in (args[0] subject, rest the list; negated);
 insub (args[0], query; negated); exists (query; negated); subquery (query);
 between (args[0..3]; negated); like/ilike/glob/regexp/similar (args[0], args[1], [escape]; negated);
 isnull (args[0]; negated); distinctfrom (args[0], args[1]; negated: IS NOT DISTINCT FROM);
 array (args), row (args), nextval (name: the sequence), currval (name), default.

- `op`: `string`
- `args`: `Vec<M151.Expr>`
- `value`: `M143.Value`
- `name`: `string`
- `table`: `string`
- `negated`: `bool`
- `distinct`: `bool`
- `star`: `bool`
- `ty`: `string`
- `query`: `Vec<M151.Select>`
- `filter`: `Vec<M151.Expr>`
- `window`: `Vec<M151.Window>`
- `paren`: `bool` — Written in parentheses: Oracle's `||` binds as `+` does, so only a parenthesized sum stays a unit.
- `at`: `i64` — The byte offset in the statement text of the token that starts it (an operator's own token), -1 when made
by a rewrite: the position an error reports.

### `Window`

```gizlang
type Window = { name: string; base: string; partition: Vec<Expr>; order: Vec<Order>; frame: string; start: Vec<Expr>; end: Vec<Expr>; startKind: string; endKind: string; exclude: string; }
```

`name` names a definition or a direct OVER reference; `base` copies an earlier definition.

- `name`: `string`
- `base`: `string`
- `partition`: `Vec<M151.Expr>`
- `order`: `Vec<M151.Order>`
- `frame`: `string`
- `start`: `Vec<M151.Expr>`
- `end`: `Vec<M151.Expr>`
- `startKind`: `string`
- `endKind`: `string`
- `exclude`: `string`

### `Order`

```gizlang
type Order = { expr: Expr; desc: bool; nulls: i64; }
```

An ORDER BY item: its expression, whether descending, and where nulls go.

- `expr`: `M151.Expr`
- `desc`: `bool`
- `nulls`: `i64`

### `Item`

```gizlang
type Item = { expr: Expr; alias: string; text: string; quoted: bool; }
```

`text`: the source of an unaliased item (Oracle labels its column with it), else "".

- `expr`: `M151.Expr`
- `alias`: `string`
- `text`: `string`
- `quoted`: `bool`

### `From`

```gizlang
type From = { kind: string; name: string; schema: string; alias: string; columns: Vec<string>; types: Vec<string>; query: Vec<Select>; args: Vec<Expr>; join: string; left: Vec<From>; right: Vec<From>; on: Vec<Expr>; using: Vec<string>; lateral: bool; ordinality: bool; only: bool; variadic: bool; }
```

A FROM item. kind: table (name, schema), query (query), function (name, args), join
(left, right, join: inner left right full cross, on, using, natural).

- `kind`: `string`
- `name`: `string`
- `schema`: `string`
- `alias`: `string`
- `columns`: `Vec<string>`
- `types`: `Vec<string>` — A function's column definition list (AS x(a int, b text)): each column's type, or "".
- `query`: `Vec<M151.Select>`
- `args`: `Vec<M151.Expr>`
- `join`: `string`
- `left`: `Vec<M151.From>`
- `right`: `Vec<M151.From>`
- `on`: `Vec<M151.Expr>`
- `using`: `Vec<string>`
- `lateral`: `bool`
- `ordinality`: `bool` — A function's WITH ORDINALITY: a last column numbering its rows from 1.
- `only`: `bool` — FROM ONLY t: t's rows without those of the tables that inherit from it. On a function: a select-list call (SELECT f()), whose record rows need no column definition list.
- `variadic`: `bool` — A function call whose last argument follows VARIADIC: that array is the variadic parameter itself.

### `Cte`

```gizlang
type Cte = { name: string; columns: Vec<string>; query: Select; recursive: bool; dml: Vec<Statement>; }
```

A CTE; a data-modifying one (WITH x AS (INSERT ... RETURNING ...)) holds its statement in `dml`.

- `name`: `string`
- `columns`: `Vec<string>`
- `query`: `M151.Select`
- `recursive`: `bool`
- `dml`: `Vec<M151.Statement>`

### `Select`

```gizlang
type Select = { with: Vec<Cte>; distinct: bool; distinctOn: Vec<Expr>; items: Vec<Item>; from: Vec<From>; where: Vec<Expr>; groupBy: Vec<Expr>; having: Vec<Expr>; windows: Vec<Window>; orderBy: Vec<Order>; limit: Vec<Expr>; offset: Vec<Expr>; values: Vec<Vec<Expr>>; setOp: string; right: Vec<Select>; lock: string; ties: bool; percent: bool; }
```

A query: a SELECT, or VALUES (`values`), combined with others by `setOp` (union, union all,
intersect, except) on `right`. `limit` and `offset` hold zero or one expression.

- `with`: `Vec<M151.Cte>`
- `distinct`: `bool`
- `distinctOn`: `Vec<M151.Expr>`
- `items`: `Vec<M151.Item>`
- `from`: `Vec<M151.From>`
- `where`: `Vec<M151.Expr>`
- `groupBy`: `Vec<M151.Expr>`
- `having`: `Vec<M151.Expr>`
- `windows`: `Vec<M151.Window>`
- `orderBy`: `Vec<M151.Order>`
- `limit`: `Vec<M151.Expr>`
- `offset`: `Vec<M151.Expr>`
- `values`: `Vec<Vec<M151.Expr>>`
- `setOp`: `string`
- `right`: `Vec<M151.Select>`
- `lock`: `string` — SQL Server's TOP n, Oracle's FETCH FIRST n: the same as limit.
- `ties`: `bool` — FETCH FIRST n ROWS WITH TIES: also the rows that sort the same as the last of the n.
- `percent`: `bool` — FETCH FIRST n PERCENT, TOP n PERCENT: `limit` is a percent of the row count.

### `ColumnSpec`

```gizlang
type ColumnSpec = { name: string; declared: string; nullable: bool; primary: bool; unique: bool; auto: bool; default: string; check: string; references: string; named: Vec<string>; }
```

A column in CREATE TABLE or ALTER TABLE ADD.

- `name`: `string`
- `declared`: `string`
- `nullable`: `bool`
- `primary`: `bool`
- `unique`: `bool`
- `auto`: `bool`
- `default`: `string`
- `check`: `string`
- `references`: `string`
- `named`: `Vec<string>` — Its constraints' names, "kind:name" (n NOT NULL, p, u, c, r), "" for an unnamed one.

### `Constraint`

```gizlang
type Constraint = { kind: string; name: string; columns: Vec<string>; text: string; }
```

A table constraint: primary, unique (columns), check (text), foreign (columns, references).

- `kind`: `string`
- `name`: `string`
- `columns`: `Vec<string>`
- `text`: `string`

### `Assign`

```gizlang
type Assign = { columns: Vec<string>; value: Expr; }
```

One SET of an UPDATE: the columns and the value.

- `columns`: `Vec<string>`
- `value`: `M151.Expr`

### `Conflict`

```gizlang
type Conflict = { columns: Vec<string>; action: string; sets: Vec<Assign>; where: Vec<Expr>; predicate: string; text: string; }
```

ON CONFLICT: target columns (empty: any), action nothing or update (sets, where).

- `columns`: `Vec<string>`
- `action`: `string`
- `sets`: `Vec<M151.Assign>`
- `where`: `Vec<M151.Expr>`
- `predicate`: `string`
- `text`: `string`

### `Statement`

```gizlang
type Statement = { op: string; query: Vec<Select>; table: string; alias: string; columns: Vec<string>; rows: Vec<Vec<Expr>>; load: Option<Batch>; defaults: bool; sets: Vec<Assign>; from: Vec<From>; where: Vec<Expr>; returning: Vec<Item>; conflict: Vec<Conflict>; or: string; specs: Vec<ColumnSpec>; constraints: Vec<Constraint>; ifNotExists: bool; ifExists: bool; name: string; what: string; unique: bool; method: string; options: string; text: string; value: Vec<Expr>; action: string; inner: Vec<Statement>; temporary: bool; orReplace: bool; asQuery: bool; inherits: Vec<string>; descending: Vec<bool>; partitionKey: string; partitionBound: Option<string>; parentIndex: string; viewChecks: Vec<Item>; named: bool; source: string; tablespace: string; indexSpaces: Vec<string>; tempNamed: bool; }
```

A statement. op: select, insert, update, delete, create_table, create_index, create_view,
create_sequence, drop (what: table, index, view, sequence), alter (action: add, drop_column,
rename, rename_column), begin, commit, rollback, savepoint, release, rollback_to, pragma, set,
show, explain, truncate, merge (as insert with conflict), call.

- `op`: `string`
- `query`: `Vec<M151.Select>`
- `table`: `string`
- `alias`: `string`
- `columns`: `Vec<string>`
- `rows`: `Vec<Vec<M151.Expr>>`
- `load`: `_gizlang_sdk_core.Option<M152.Batch>` — INSERT: the rows as typed columns, one for each column, when a program gives them (a load of records). An
engine stores the columns as they are, with no expression or value for a cell; SQL text has no form of it.
- `defaults`: `bool`
- `sets`: `Vec<M151.Assign>`
- `from`: `Vec<M151.From>`
- `where`: `Vec<M151.Expr>`
- `returning`: `Vec<M151.Item>`
- `conflict`: `Vec<M151.Conflict>`
- `or`: `string` — INSERT OR REPLACE / OR IGNORE: the action for any conflict.
- `specs`: `Vec<M151.ColumnSpec>`
- `constraints`: `Vec<M151.Constraint>`
- `ifNotExists`: `bool`
- `ifExists`: `bool`
- `name`: `string`
- `what`: `string`
- `unique`: `bool`
- `method`: `string`
- `options`: `string`
- `text`: `string`
- `value`: `Vec<M151.Expr>`
- `action`: `string`
- `inner`: `Vec<M151.Statement>`
- `temporary`: `bool`
- `orReplace`: `bool`
- `asQuery`: `bool`
- `inherits`: `Vec<string>` — CREATE TABLE ... INHERITS (parents).
- `descending`: `Vec<bool>` — CREATE INDEX: for each column, whether it was written DESC.
- `partitionKey`: `string` — PARTITION BY: "strategy\u0001key\u0002key...\u0001opclass\u0002...", "" when not given.
- `partitionBound`: `_gizlang_sdk_core.Option<string>` — The bound of PARTITION OF or ATTACH PARTITION, as the catalog keeps it (partbound): "default",
"in\u0001v\u0002v...", "range\u0001lo\u0002...\u0001hi\u0002..." or "hash\u0001modulus\u0001remainder"; "" for DETACH
PARTITION; undefined when the statement names no partition.
- `parentIndex`: `string` — CREATE INDEX made for a partition (ddl.giz indexStatement): the parent index it attaches to.
- `viewChecks`: `Vec<M151.Item>` — The conditions of the views WITH CHECK OPTION that an INSERT or UPDATE goes through, in the terms of its
table: the alias of each item names its view.
- `named`: `bool` — A :name parameter: PostgreSQL has none (psql substitutes its variables), so its dialect refuses it.
- `source`: `string` — CREATE FUNCTION, PROCEDURE, TRIGGER and PACKAGE: the text from the object word to the end, as the dictionary shows it.
- `tablespace`: `string` — The TABLESPACE of CREATE TABLE or CREATE INDEX, or of ALTER ... SET TABLESPACE; "" when none is given.
- `indexSpaces`: `Vec<string>` — CREATE TABLE: the tablespaces of its USING INDEX TABLESPACE clauses.
- `tempNamed`: `bool` — Whether the statement names an object in pg_temp (pg_temp.x), whose qualifier the parser drops.

## Functions

### `columnSpec`

```gizlang
function columnSpec(name: string, declared: string, nullable: bool): ColumnSpec
```

A column `name` of type `declared`, with no constraint but NOT NULL when not `nullable`.

### `expr`

```gizlang
function expr(op: string): Expr
```

A new expression node of OP with no fields set.

Effects: fail.

### `columnRef`

```gizlang
function columnRef(table: string, name: string): Expr
```

A reference to column NAME of TABLE ("" for any).

Effects: fail.

### `exprOf`

```gizlang
function exprOf(op: string, args: Vec<Expr>): Expr
```

A new expression node of OP with ARGS.

Effects: fail.

### `lit`

```gizlang
function lit(v: Value): Expr
```

A literal expression of V.

Effects: fail.

### `paramRef`

```gizlang
function paramRef(n: i64): Expr
```

The parameter $N (from 1).

Effects: fail, alloc.

### `select`

```gizlang
function select(): Select
```

An empty SELECT.

### `newFrom`

```gizlang
function newFrom(kind: string): From
```

A FROM item of kind with every other field empty.

### `statement`

```gizlang
function statement(op: string): Statement
```

An empty statement of OP.

### `window`

```gizlang
function window(): Window
```

An empty window definition.

### `exprAny`

```gizlang
function exprAny<F>(x: Expr, test: F): bool effects {test, fail}
```

Whether `test` holds for `x` or for a part of it (its arguments, recursively).

### `keepable`

```gizlang
function keepable(s: Select): bool
```

Whether the answer of S depends only on the data it reads: it calls no function but an aggregate (a clock, a random
draw or a function with effects gives another answer to the same data), reads no table function and locks no row.
A source may keep such an answer until the data changes (model/source.giz TextClient).

Effects: fail, alloc.

