Referencia · §8.12

Extension API

ext, builtin

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

What a module adds to the SQL layer (principle 12), versioned (ext::API_VERSION, 1). The guide for writing one is examples/extension/README.md, with the sample module geo (geopoint, geohash, geo.cities) built on this API alone, embedded and as a custom server build (geo-demo serve).

  • Module — name(), register(&mut Registry).
  • ScalarFunction — name() (for EXPLAIN), arity(), resolve(&[ArgInfo]) -> Signature (bind-time typing: per argument Keep, Untyped(t) — an untyped literal, NULL or parameter takes t —, Convert(t) or Common; the result a type, the arguments’ common type, or a Constant), strict() (default true: a NULL argument gives NULL without a call), volatility() (Immutable, Stable, Volatile — the default; only immutable functions may define an ordering), parallel_safe() (default: unless volatile; a volatile function whose calls do not depend on one another, such as random(), returns true so workers call it), found(args) (the condition whose rows a ranking function ranks: text_score’s are @@’s; §8.20), rewrite(args) (a call giving the same value on every row, bound in this one’s place — pg-compat’s to_tsvector(cfg, col) @@ to_tsquery(cfg, q) as the text index’s col @@ q', §8.22), of_condition() and bind_condition(operands, rest) (a function of an operator’s condition, highlight(body @@ q): the operator, and the call bound in its place from the operator’s operands — typed as its signature converted them — and the other arguments), implied_range() (for a function of two arguments true only when the first lies in a range computed from the second: two functions giving the bounds; the binder adds the comparisons beside the call, for index ranges — inet <<= cidr uses it), call(&CallContext, &[Value]), and optionally call_batch(&CallContext, &[&Vector], len, &Sel) -> Option<Result<Vector>>: a batch kernel for the vectorized executor (§8.5), the values for the rows in play — NULLs and errors as call gives them; None (the default) for arguments it has no kernel for, and call is made a row at a time. CallContext gives the statement’s transaction, the registry, now(), clock() and random(buf) (all through the database’s platform).
  • Aggregate — name(), arity(), accepts_star() (count(*)), keeps_nulls() (default false: rows whose first argument is NULL are skipped), resolve (as a function’s), start() -> Box<dyn Accumulator> (add(&[Value]), finish()), one per group. The engine does the grouping, DISTINCT (over the arguments) and ORDER BY inside the call. Optionally grouped() -> Option<Box<dyn GroupAccumulator>> (resize(groups), update(rows, groups, &[&Vector]), finish(group), and group_bytes(), about the bytes a group’s state takes — by default 96 —, what a grouping counts against work_mem): the states of many groups fed a batch at a time by the vectorized executor (§8.5) — a capability; without it the accumulators are fed row by row, with the same result. With combinable(), partial(group) and combine(group, partial) too, its groups are aggregated in parallel: each worker’s state as a value, combined in key order (resize may be asked for more groups than are used: room for them); a window frame over any rows of its partition then combines a segment tree’s partial states (§8.5, Window functions). finish_keeps_state() (default false): finish(group) leaves the state as it was, so a window frame growing from its partition’s start reads each row’s result from one state. infallible() (default false): no input makes it fail, so the optimizer may compute it below a join, over rows the join would drop (eager aggregation, §8.6). order_free() (default false): its result is the same in any order of its rows, so a DISTINCT call of it may be fed its values grouped first (§8.6).
  • TableFunction — name(), arity(), resolve(&[ArgInfo]) -> TableSignature (per argument, and the output columns: one is named after the function or its alias, several by their own names, qualified by the alias), rows(&CallContext, &[Value]). ext::common_type is the binder’s rule for Common arguments, for a resolve that needs it.
  • CatalogView — schema(), name(), columns(), rows(&CallContext).
  • Type — name(), aliases(), category(), input(text), output(&Value), and its abilities, each its own interface it has or not: equality() (Equality), hashing() (Hashing), ordering() (TotalOrder), key_encoding() (KeyEncoding: order-preserving, self-delimiting), distance() (Distance: an operator and a distance), arithmetic() (Arithmetic: the binary operators it defines — +, -, *, || … — and apply(op, a, b); the binder calls it through ArithmeticFn), elements() (Elements: element_type(), count, get, slice, with — 0-based and in range, the binder and evaluator doing SQL’s 1-based positions and clamping — for x[i], x[lo:hi] and SET x[i] = v; a type without it cannot be subscripted, 42804); a modifier — modifier(n) checks type(n) when a column or cast names it (by default: the type takes none, 42601), fit(v, n) checks or fits a value to it on every write and on a cast (FitFn); casts — cast_from(v) from another type, cast_to(v, t) to one (None: not this type’s cast, the built-in rules apply); aggregate(name) (its own sum, avg, … — chosen by the first argument’s type before the built-in one); stored_with_row() (a value read with its row nearly always — vector, sparsevec — stays in the row however long instead of out of line, §8.1’s large values; by default false); encoding_version(); examples() (on which registration checks the laws: a type that breaks one is not registered). A registered type’s values are Value::Ext(TypeRef, bytes) — Value::ext(t, bytes), v.ext_bytes() — whose bytes are canonical: equality and hashing are on them (CanonicalBytes implements both), so they agree by construction; its type is DataType::Ext(TypeRef). TypeRef is the type interned once per name (small, Copy): name(), id(), imp(), TypeRef::named(name), TypeRef::by_id(id) (each thread keeps the real type it last looked up either way, so decoding a column of a registered type takes the interning table’s lock once, not a value — §M14.12 V2, where every worker of a parallel scan waited on it). The catalog stores a registered type by name; a database naming a type this process has never registered still opens (TypeRef::named_or_missing: values print as hex, input fails naming the missing type). ncp sends registered types as text for now (their binary form with §M14.19’s UUID), pg-compat as text.
  • Registry — empty(), builtin() (the builtin module: every built-in function, aggregate and table function, the schemas public and nc_catalog, the nc_catalog views), shared_builtin(), add(&dyn Module) (refused, and the registry unchanged, if the module or anything it registers is already there), add_function(names, f), add_aggregate(names, a) (functions and aggregates share one namespace), add_table_function(f), add_schema(name, description, searched) (a searched schema’s views are found by unqualified names after the user’s tables, as pg_catalog’s), add_view(v), add_type(t), add_storage(s) (a table storage, §8.15), add_index_method(m) (an index access method, §8.17), add_alias(name, ty) (pg-compat’s oid, name, bpchar, …), and the lookups function, aggregate, table_function, view, type_named, schemas, views, types, modules. A session can name only its registry’s types; a type is written name, schema.name, name 'literal' or x::name, and x::name where name is no type but a function __name exists calls it (pg-compat’s ::regclass).

Laws (nucleus_sql::laws, run property-based by the test kit’s nucleus_testkit::laws): for each ability a type has — equality is an equivalence; hashing agrees with equality; the order is total and agrees with equality; the key encoding’s byte order is the type’s order, it decodes back and is self-delimiting — and always: text output parses back to an equal value, the row encoding reads back what it wrote, and the engine’s own comparisons and hashing (Value’s) agree with the type’s. Registry::add_type checks them on the type’s examples; laws::check(ty, generator, cases) on generated values (laws::Gen, a seeded generator; laws::generator(ty) for the built-in types, their arrays, uuid, json, vector and sparsevec). crates/sql/tests/laws.rs runs the kit on every built-in type and array, and shows a broken type caught and refused.

tests/extension.rs is a module from outside the crate adding a function, an aggregate, a table function and a view, used through SQL; tests/types.rs one adding the geopoint type (equality and a distance, no order, no key encoding) — stored, reread, compared, grouped, and refused exactly where an ability is missing.

A session runs against one registry: Session::new(kv) the built-in one, Session::with_registry(kv, registry) any. The binder finds functions and views there; bound calls and view scans hold the registered objects, so execution needs no lookup. The built-in functions share one implementation behind the same interface.