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()(forEXPLAIN),arity(),resolve(&[ArgInfo]) -> Signature(bind-time typing: per argumentKeep,Untyped(t)— an untyped literal,NULLor parameter takest—,Convert(t)orCommon; the result a type, the arguments’ common type, or aConstant),strict()(default true: aNULLargument givesNULLwithout 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 asrandom(), 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’sto_tsvector(cfg, col) @@ to_tsquery(cfg, q)as the text index’scol @@ q', §8.22),of_condition()andbind_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 <<= cidruses it),call(&CallContext, &[Value]), and optionallycall_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 ascallgives them;None(the default) for arguments it has no kernel for, andcallis made a row at a time.CallContextgives the statement’s transaction, the registry,now(),clock()andrandom(buf)(all through the database’s platform).Aggregate—name(),arity(),accepts_star()(count(*)),keeps_nulls()(default false: rows whose first argument isNULLare 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) andORDER BYinside the call. Optionallygrouped() -> Option<Box<dyn GroupAccumulator>>(resize(groups),update(rows, groups, &[&Vector]),finish(group), andgroup_bytes(), about the bytes a group’s state takes — by default 96 —, what a grouping counts againstwork_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. Withcombinable(),partial(group)andcombine(group, partial)too, its groups are aggregated in parallel: each worker’s state as a value, combined in key order (resizemay 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 aDISTINCTcall 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_typeis the binder’s rule forCommonarguments, for aresolvethat 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 —+,-,*,||… — andapply(op, a, b); the binder calls it throughArithmeticFn),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 — forx[i],x[lo:hi]andSET x[i] = v; a type without it cannot be subscripted,42804); a modifier —modifier(n)checkstype(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 ownsum,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 areValue::Ext(TypeRef, bytes)—Value::ext(t, bytes),v.ext_bytes()— whose bytes are canonical: equality and hashing are on them (CanonicalBytesimplements both), so they agree by construction; its type isDataType::Ext(TypeRef).TypeRefis 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).ncpsends registered types as text for now (their binary form with §M14.19’sUUID),pg-compatastext.Registry—empty(),builtin()(thebuiltinmodule: every built-in function, aggregate and table function, the schemaspublicandnc_catalog, thenc_catalogviews),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, aspg_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’soid,name,bpchar, …), and the lookupsfunction,aggregate,table_function,view,type_named,schemas,views,types,modules. A session can name only its registry’s types; a type is writtenname,schema.name,name 'literal'orx::name, andx::namewherenameis no type but a function__nameexists 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.