Files
leleka/scripts/e2e/codex/tasks/feature-query/seed/SPEC.md
T

181 lines
10 KiB
Markdown

# Specification: the `where` query language
This document defines the textual `where` expressions that `minidb` accepts in addition to Python callables.
It is the single source of truth: an implementation that follows it exactly is correct.
## 1. Where it applies
* `minidb/query.py` exposes `compile_where(text, columns)`, where `text` is the expression and `columns` is an iterable of the table's
column names (including `id`). It returns a predicate `predicate(row) -> bool` for a row given as a `dict`.
* The predicate returns `True` when the expression evaluates to TRUE for the row and `False` when it evaluates to FALSE or UNKNOWN.
(UNKNOWN is the third truth value of SQL-style logic, see section 5; unknown rows are never selected.)
* `Table.select`, `Table.update`, `Table.delete` and `Table.count` accept `where` either as a callable (unchanged behaviour), as `None`
(all rows, unchanged), or as a `str`, which is compiled with `compile_where` using the table's column names before any row is examined.
An empty or blank string is an expression like any other and is a syntax error (section 3.4). Any other type raises `TypeError` as before.
* The command line tool accepts `--where EXPRESSION` for `select`, `update` and `delete` (section 8).
## 2. Lexical structure
The text is first split into tokens. Characters are counted from 0; every position in this document is an index into the original text,
including leading whitespace.
* **Whitespace** (space, tab, carriage return, line feed) separates tokens and is otherwise ignored.
* **Keywords**, matched case-insensitively and only as whole words: `AND OR NOT IN BETWEEN LIKE ILIKE IS NULL TRUE FALSE`.
* **Identifiers**: an ASCII letter or underscore followed by ASCII letters, digits or underscores, that is not a keyword. A word is read as
far as these characters go, so `note` and `android` are identifiers, not `NOT` or `AND` followed by something. Identifiers are case-sensitive
and name columns.
* **Numbers**: an optional sign (`+` or `-`) written directly in front of the digits, then one or more digits, optionally followed by a dot and
one or more digits. Without a dot the number is an integer, with a dot it is a float. Leading zeros are allowed. `-5` is one token.
A sign that is not directly followed by a digit is an invalid character. There is no arithmetic, so `5-3` is the number `5` followed by
the number `-3` (a syntax error, section 3.4).
* **Strings**: enclosed in single quotes. A quote inside a string is written twice (`'it''s'` is `it's`). There are no other escape
sequences, a backslash is an ordinary character, and a string may contain any character including newlines.
* **Operators and punctuation**: `=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`, `(`, `)`, `,`. The two-character operators win over their one-character
prefixes (`<=` is one token, not `<` then `=`). `!=` and `<>` mean the same thing.
* Any other character (including a `!` that is not followed by `=`, a `.` that is not inside a number, and non-ASCII characters outside
strings) is invalid.
Tokenisation of the whole text happens before parsing, so a lexical error (invalid character, unterminated string) is reported in
preference to any syntax error, wherever either is.
## 3. Grammar
```text
expression := or_expr
or_expr := and_expr { OR and_expr }
and_expr := not_expr { AND not_expr }
not_expr := NOT not_expr | primary
primary := '(' expression ')' | predicate
predicate := operand [ suffix ]
suffix := cmp_op operand
| [ NOT ] IN '(' literal { ',' literal } ')'
| [ NOT ] BETWEEN operand AND operand
| [ NOT ] ( LIKE | ILIKE ) operand
| IS [ NOT ] NULL
cmp_op := '=' | '!=' | '<>' | '<' | '<=' | '>' | '>='
operand := IDENT | literal
literal := NUMBER | STRING | TRUE | FALSE | NULL
```
### 3.1 Precedence and associativity
From the tightest to the loosest: the predicate forms (comparison, `IN`, `BETWEEN`, `LIKE`, `IS NULL`), then `NOT`, then `AND`, then `OR`.
`AND` and `OR` are left-associative. Parentheses group. `NOT age > 30` is `NOT (age > 30)`. The `AND` inside `BETWEEN a AND b` belongs to the
`BETWEEN`; in `x BETWEEN 1 AND 5 AND y = 2` the second `AND` is the logical one.
### 3.2 Meaning of each form
Let `x`, `a`, `b` be operands and `p`, `q` expressions. The forms are defined by these equivalences (evaluation order and short-circuiting
follow section 5):
* `x NOT IN (a, b, c)` is `NOT (x IN (a, b, c))`, and `x IN (a, b, c)` is `x = a OR x = b OR x = c`, evaluated left to right.
* `x BETWEEN a AND b` is `x >= a AND x <= b` (no swapping of the bounds: `x BETWEEN 5 AND 1` is never true), and `x NOT BETWEEN a AND b` is
`NOT (x BETWEEN a AND b)`.
* `x NOT LIKE a` is `NOT (x LIKE a)`; `x NOT ILIKE a` is `NOT (x ILIKE a)`.
* `x IS NOT NULL` is `NOT (x IS NULL)`.
* A *bare operand* used as a condition (a predicate without a suffix) is true or false when it is a boolean, and unknown when it is NULL.
### 3.3 Not supported
Arithmetic, function calls, quoted identifiers, comments, subqueries and escape characters in `LIKE` patterns do not exist. A column whose name is
a keyword cannot be referenced (such names are rejected when a column is created).
### 3.4 Syntax errors
A syntax error is a `QuerySyntaxError` with an integer attribute `position`. The parser reads tokens from left to right and reports the first
token that cannot continue a valid expression, using the grammar above:
* if that token exists, `position` is the index of its first character;
* if the text ends too early (including an empty or blank text), `position` is `len(text)`;
* a token left over after a complete expression (for example `age = 1 name = 2`, or a stray `)`) is reported at that token;
* an unterminated string is reported at its opening quote, an invalid character at that character.
`str(error)` is a short description followed by ` at position N`, for example `unexpected token at position 8`.
## 4. Values and types
A row value is an `int`, `float`, `str`, `bool` or `None` (NULL). Literals have the obvious types; `TRUE` and `FALSE` are booleans. For the
purposes of this language `bool` is **not** a number.
### 4.1 Comparison (`=`, `!=`, `<>`, `<`, `<=`, `>`, `>=`)
1. If either operand is NULL the result is UNKNOWN. No type check is made.
2. Two numbers (`int` or `float`) compare by numeric value, so `30 = 30.0` is TRUE.
3. Two strings compare by code point order, case-sensitively (`'B' < 'a'`, `'Dave' > 'D'`).
4. Two booleans compare with `FALSE < TRUE`, all six operators allowed.
5. Any other combination (string with number, boolean with number, boolean with string) raises `QueryTypeError`, whatever the operator.
### 4.2 `LIKE` and `ILIKE`
`x LIKE p` compares the string `x` with the pattern `p`. In the pattern `%` matches any sequence of characters (including none), `_` matches exactly
one character (any character, including a newline), and every other character, including regular-expression characters such as `.` and `[`,
matches only itself. The pattern must match the whole string. `LIKE` is case-sensitive; `ILIKE` compares after converting both strings with
`str.lower()`. If either side is NULL the result is UNKNOWN (checked first); otherwise both sides must be strings, else `QueryTypeError`.
Either side may be a column or a literal.
### 4.3 `IS NULL`
`x IS NULL` is TRUE when `x` is NULL and FALSE otherwise; it is never UNKNOWN and never a type error.
### 4.4 Bare operands
A bare operand that is a boolean gives TRUE or FALSE, NULL gives UNKNOWN, and any other value (number, string) raises `QueryTypeError`.
### 4.5 When type errors happen
A `QueryTypeError` is raised by the predicate, when it is called on the first row for which evaluation (section 5) reaches a forbidden
combination. It is never raised while compiling, and never for rows where the offending part is not evaluated (NULL operands, short-circuiting).
A query over a table with no rows, or whose rows never reach the forbidden combination, never raises it.
## 5. Three-valued logic and evaluation order
Truth values are TRUE, FALSE, UNKNOWN.
* `NOT`: TRUE becomes FALSE, FALSE becomes TRUE, UNKNOWN stays UNKNOWN.
* `p AND q`: evaluate `p` first. If it is FALSE the result is FALSE and `q` is **not evaluated**. Otherwise evaluate `q`: the result is FALSE if
`q` is FALSE; else UNKNOWN if either operand is UNKNOWN; else TRUE.
* `p OR q`: evaluate `p` first. If it is TRUE the result is TRUE and `q` is **not evaluated**. Otherwise evaluate `q`: the result is TRUE if `q` is
TRUE; else UNKNOWN if either operand is UNKNOWN; else FALSE.
* UNKNOWN on the left never short-circuits. Chains evaluate left to right.
Consequences worth remembering: `x = NULL` is UNKNOWN, never TRUE, for every `x`; `x NOT IN (1, NULL)` is never TRUE; `NOT (x = 1)` is not selected
for a row whose `x` is NULL.
## 6. Names
Every identifier must be a column name of the table. Unknown identifiers raise `QueryNameError` while compiling, before any row is examined, even
on an empty table. The error has the attributes `name` (the identifier) and `position` (index of its first occurrence in the text, scanning left to
right). Name checking happens after parsing succeeded: a text with a syntax error raises `QuerySyntaxError` even if it also contains unknown
identifiers.
## 7. Error classes
All in `minidb/query.py`:
```text
MiniDBError (minidb/errors.py)
QueryError
QuerySyntaxError attribute: position
QueryNameError attributes: name, position
QueryTypeError
```
## 8. Command line
`select`, `update` and `delete` take `--where EXPRESSION`. For `update` and `delete` the options `--id N` and `--where EXPRESSION` are mutually
exclusive and exactly one of them is required. `select` without `--where` prints all rows as before; with it, only the rows for which the expression
is TRUE (in id order unless `--order-by` is given). `update` and `delete` print `updated N` / `deleted N` with the number of affected rows.
A query error (`QueryError`) is reported like every other `MiniDBError`: `error: <message>` on standard error and exit status 2.
## 9. Examples
| Expression | Selects |
| --- | --- |
| `age >= 18 AND city = 'Berlin'` | adults in Berlin |
| `name LIKE 'A%' OR name ILIKE '%son'` | names starting with `A` or ending with `son` in any case |
| `age BETWEEN 20 AND 30` | `20 <= age <= 30`; rows with NULL age are not selected |
| `city IN ('Rome', 'Paris') AND NOT active` | `active` is a boolean column |
| `note IS NULL OR note = ''` | missing or empty notes |
| `age NOT IN (25, 30)` | NULL ages are not selected either |
| `name = 'O''Brien'` | quote escaping |