kura_dialect behaviour (kura v2.31.3)
View SourceSQL dialect behaviour. Translates a portable #kura_query{} AST into
backend-specific SQL.
#kura_query{} is the portable AST: it describes operations as atoms
and tuples, not as SQL strings. The dialect callbacks turn that AST
into SQL bytes appropriate for a given backend.
Today
The canonical implementation is kura_dialect_pg, which targets
PostgreSQL with its $N placeholder convention.
Tomorrow
Adding SQLite or MySQL is a matter of providing another implementation
of this behaviour. Differences (placeholder syntax ? vs $N,
identifier quoting "foo" vs `foo`, RETURNING vs lastrowid,
ON CONFLICT vs ON DUPLICATE KEY UPDATE, LIMIT/OFFSET vs FETCH FIRST) all live in the dialect impl. The AST stays the same.
Many-to-many join tables are read and written through the same callbacks:
to_sql/1 for the join read, delete_all/1 and insert_all/3 for the
rows put_assoc and cast_assoc replace. They are called on the dialect
directly, without the attribute tenant condition, since a join table has no
tenant column; a prefix tenant still qualifies the table.
Bound values
kura_query_compiler:to_sql_cached/2 compiles a query's shape once, with
every bound value replaced by a marker (see kura_query_shape), and
reuses the result for every call that differs only in its values. An
implementation must therefore pass a value in a bound position through to
params() unchanged, and never inspect it or write it into the SQL text.
That includes limit and offset: in a shape they hold a marker, not
the integer the record type names.
A template whose markers are missing, repeated or nested is detected and
not cached, and so is a shape the implementation raises on, but SQL that
varies with a value's content cannot be. nil and undefined are never
replaced by a marker, so an implementation may compile them specially.
Vector distance
A {distance, Field, Metric, Vector} node from kura_query:distance/3
can appear in a select expression, in order_by, and as the left side
of a {Distance, Op, Threshold} condition in a where or a having, Op
being '<', '<=', '>' or '>='. Vector and Threshold are bound
values like any other. kura_dialect_pg emits pgvector's <->, <=>
and <#>. A dialect for a backend without vector distance must raise
{unsupported, vector_distance} on such a node, and must never fall back
to the PG spelling: in MySQL <=> is NULL-safe equality, so a query
that should fail would instead return rows in a meaningless order. A
dialect that delegates to kura_dialect_pg has to catch the node before
it does.
Text matches
{Field, Op, Text} with Op one of contains, starts_with, ends_with,
icontains, istarts_with and iends_with (?KURA_IS_TEXT_MATCH_OP)
matches Text literally. Text is a bound value, so an implementation
cannot escape it in Erlang: it escapes the wildcards in SQL and names the
escape character in an ESCAPE clause, as kura_dialect_pg does with
replace/3. The i forms ignore case; kura_dialect_pg emits ILIKE,
which a dialect for a backend without it has to replace.
Patterns
{Field, like, Pattern} and {Field, ilike, Pattern} take a pattern whose
escape character is the backslash, which is what kura_query:escape_like/1
writes. kura_dialect_pg relies on PostgreSQL's default. A dialect for a
backend whose LIKE has no default escape character has to name it:
LIKE ? ESCAPE '\'.
Empty lists
{Field, in, []} matches no row and {Field, not_in, []} every row.
kura_dialect_pg emits 1 = 0 and 1 = 1, never IN ().
Deterministic lookups
kura_query:where/2 and kura_query:having/2 rewrite a comparison on a
deterministic encrypted field into {Field, encrypted_in, Frames} or
{Field, encrypted_not_in, Frames}, meaning the column is IN or
NOT IN the values. The values are bound like any other (the shape cache
replaces them with markers), so an implementation passes them through to
params() unchanged. They are ciphertext bytes: bind each in the column's
byte type, never as text. The list holds one value per lookup key per
looked-up value, so never assume it has one element. The operator atoms
are kura's own and must never appear in the SQL. A dialect that delegates
to kura_dialect_pg but binds binaries as text, as SQLite does, has to
catch the node before it delegates and cast each placeholder to bytes.
Locks
The lock of a query is whatever the caller put there: a term from
kura_query:lock/2, or in a record built by hand a binary. Read it through
kura_query:lock_clause/1, never as it is. That returns a strength,
{Strength, Wait}, {Strength, #{tables := Names}} with an optional
wait, a list of those for several clauses, or {fragment, SQL}, and
raises for anything else. Quote each of Names as an identifier; only a
fragment's SQL goes into the statement unquoted.
A dialect may take a stronger lock than the one asked for, never a weaker
one: a backend without FOR NO KEY UPDATE takes FOR UPDATE.
Stored values
A driver with a native type for every kura type returns each value in the
Erlang form kura_types:load/2 reads, and its dialect has nothing to do.
A backend that stores a type in another form implements load_stored/2,
which kura calls on each non-null value of a row read through a schema,
with the field's type, before kura_types:load/2. It returns the Erlang
form, or the value as it is when it has nothing to do or cannot read it;
the row then keeps what the driver returned, as it does for any value
load/2 refuses.
It must never make a float of a decimal held as text:
kura_types:load/2 keeps that text exact. JSON text for jsonb and embeds
needs nothing either, load/2 decodes it.
Public API entry point
Consumers go through kura_query_compiler, which delegates to the
configured dialect module. They do not call this behaviour's
callbacks directly.
Summary
Types
Next placeholder index. Used when composing sub-queries (CTEs, sub-selects in WHERE) so placeholders stay contiguous across the entire compiled statement.
Parameter list in the order the placeholders appear in sql().
Compiled SQL bytes. Implementations are free to return iodata or a binary.
The table a statement targets: a schema module, whose table/0 names it, or
a table name as an atom or a binary. The from of a query handed to a dialect
takes the same forms; kura_query:from/1 takes a schema module or an atom.
A many-to-many join_through given as a binary reaches the dialect as one.
Callbacks
Optional. SQL bytes for a kura column type, used by kura_migrator DDL.
Optional. Convert a query's bound values before it is compiled.
kura_query_compiler calls it on every query it compiles: before it splits
the query into a cached shape, so it sees the values, and again on the shape
once the tenant condition is added. Return every value you do not convert
unchanged; the result must keep the query's shape. It must be idempotent.
kura_dialect_pg converts where values to the field's type here. A dialect
without it binds every value as the caller gave it.
Compile a DELETE-by-primary-key. The key is one clause per column (single-key is a one-element list).
Compile a bulk DELETE (DELETE ... WHERE ...) from a query AST.
Optional. SQL bytes for a column default value, used by kura_migrator DDL.
Compile a single-row INSERT (no options).
Compile a single-row INSERT with options (e.g. on_conflict).
Compile a bulk INSERT (multi-row).
Compile a bulk INSERT with options (returning, and on_conflict as for insert/4, guard included).
Optional. Turn Value, as the driver returned it for a field of Type,
into the Erlang form kura_types:load/2 reads. See "Stored values" in the
moduledoc. Called once for each non-null value of a row read through a
schema; never for raw SQL. Return Value unchanged for anything else.
Optional. The text of the Nth bind parameter in a statement: $N for
PostgreSQL, ?N for SQLite. kura writes the few statements it does not
build from a query, such as the migrator's version bookkeeping, with it.
Without it they are written with $N.
Compile a query AST into {SQL, Params}.
Compile a query AST starting placeholder numbering at StartCounter.
Returns the next free counter so callers can chain sub-compilations.
Compile an UPDATE-by-primary-key. The key is one clause per column (single-key is a one-element list).
Compile a bulk UPDATE (UPDATE ... WHERE ...) from a query AST and a SET map.
Functions
The text of the Nth bind parameter under Dialect: its placeholder/1
when it has one, and $N otherwise, or when Dialect is undefined.
Which bare fields of a query name a column of its from table.
Types
-type counter() :: pos_integer().
Next placeholder index. Used when composing sub-queries (CTEs, sub-selects in WHERE) so placeholders stay contiguous across the entire compiled statement.
-type params() :: [term()].
Parameter list in the order the placeholders appear in sql().
-type sql() :: iodata().
Compiled SQL bytes. Implementations are free to return iodata or a binary.
The table a statement targets: a schema module, whose table/0 names it, or
a table name as an atom or a binary. The from of a query handed to a dialect
takes the same forms; kura_query:from/1 takes a schema module or an atom.
A many-to-many join_through given as a binary reaches the dialect as one.
Callbacks
-callback column_type(kura_types:kura_type()) -> binary().
Optional. SQL bytes for a kura column type, used by kura_migrator DDL.
-callback convert_values(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}) -> #kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}.
Optional. Convert a query's bound values before it is compiled.
kura_query_compiler calls it on every query it compiles: before it splits
the query into a cached shape, so it sees the values, and again on the shape
once the tenant condition is added. Return every value you do not convert
unchanged; the result must keep the query's shape. It must be idempotent.
kura_dialect_pg converts where values to the field's type here. A dialect
without it binds every value as the caller gave it.
It runs before the encrypted filter guard on the cached path, and a query
built without kura_query:where/2 never meets that guard's first check, so
an implementation may see the plaintext value of an encrypted field. It must
not raise on a value or log one.
Compile a DELETE-by-primary-key. The key is one clause per column (single-key is a one-element list).
-callback delete_all(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}) -> {sql(), params()}.
Compile a bulk DELETE (DELETE ... WHERE ...) from a query AST.
Optional. SQL bytes for a column default value, used by kura_migrator DDL.
Compile a single-row INSERT (no options).
Compile a single-row INSERT with options (e.g. on_conflict).
on_conflict may carry #{guard => [Field]} as a third element. The update
must then only apply where each field of the existing row equals the
incoming one. A dialect that cannot express that must raise, never drop the
guard: it is what keeps an upsert inside its tenant.
Compile a bulk INSERT (multi-row).
Compile a bulk INSERT with options (returning, and on_conflict as for insert/4, guard included).
-callback load_stored(Type :: kura_types:kura_type(), Value :: term()) -> term().
Optional. Turn Value, as the driver returned it for a field of Type,
into the Erlang form kura_types:load/2 reads. See "Stored values" in the
moduledoc. Called once for each non-null value of a row read through a
schema; never for raw SQL. Return Value unchanged for anything else.
Optional. The text of the Nth bind parameter in a statement: $N for
PostgreSQL, ?N for SQLite. kura writes the few statements it does not
build from a query, such as the migrator's version bookkeeping, with it.
Without it they are written with $N.
-callback to_sql(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}) -> {sql(), params()}.
Compile a query AST into {SQL, Params}.
-callback to_sql_from(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}, counter()) -> {sql(), params(), counter()}.
Compile a query AST starting placeholder numbering at StartCounter.
Returns the next free counter so callers can chain sub-compilations.
Compile an UPDATE-by-primary-key. The key is one clause per column (single-key is a one-element list).
-callback update_all(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}, map()) -> {sql(), params()}.
Compile a bulk UPDATE (UPDATE ... WHERE ...) from a query AST and a SET map.
Functions
The text of the Nth bind parameter under Dialect: its placeholder/1
when it has one, and $N otherwise, or when Dialect is undefined.
-spec qualified_columns(#kura_query{from :: atom() | module() | binary() | undefined, select :: [atom() | term()] | {exprs, [term()]}, wheres :: [term()], joins :: [term()], order_bys :: [term()], group_bys :: [atom()], havings :: [term()], limit :: non_neg_integer() | undefined, offset :: non_neg_integer() | undefined, distinct :: boolean() | [atom()], lock :: kura_query:lock() | binary() | undefined, prefix :: binary() | undefined, preloads :: [atom() | {atom(), list() | map()}], ctes :: [{binary(), #kura_query{}}], combinations :: [{union | union_all | intersect | except, #kura_query{}}], include_deleted :: boolean()}) -> undefined | {binary(), #{atom() => kura_types:kura_type()}}.
Which bare fields of a query name a column of its from table.
Returns undefined when nothing is qualified: the query has no join, or
its from is a bare table or CTE name rather than a schema module.
Otherwise returns {Table, Fields}: the from schema's table/0 and the
fields, with their types, that a dialect writes as "Table"."field". Any
other name stays bare, for the server to find among the joined tables.
Under attribute tenancy (kura_tenant) the tenant field is left out of
Fields. kura_tenant:scope_query/2 adds the tenant condition for the
from table only, so a qualified tenant field would confine the from
rows and read the joined table's rows of every tenant. Bare, the field is
ambiguous in a join of two tables that both carry it, and the server
refuses the query.