vsql_allow_preview_extensions = ON to install (see
Enabling the Preview Tier) — extensions that
don’t use preview capabilities install normally regardless of this setting.
Enabling the Preview Tier
Setvsql_allow_preview_extensions = ON with SET PERSIST before installing
any extension that uses a preview capability:
SET GLOBAL is rejected for this variable — the server requires SET PERSIST
so the setting survives restart. Extensions with preview capabilities are
loaded at startup, so the variable must be ON when the server starts.
If you’re launching mysqld directly (for example, from an install script that
starts the server for the first time), pass the flag on the command line
instead — mysqld-auto.cnf won’t exist yet to carry the persisted value:
Capability Index
Registration Pattern
To use a preview capability, declare a capability object by value at file scope and pass it by reference to.with() inside make_extension(). The
server populates the object’s abi pointer during registration:
.with(capability) tells the server which capabilities the extension
requires. If vsql_allow_preview_extensions is OFF when the extension is
installed, the server rejects the install with an error naming the capability.
Keyring Access
The keyring capability (vsql::preview::keyring) lets extensions read and
write secrets stored in the MySQL keyring component. Extensions use it for
things like API keys, encryption keys, or other secrets that shouldn’t live
in SQL tables.
The capability name VEF_PREVIEW_KEYRING_NAME is "vsql::preview::keyring".
A keyring component must be installed on the MySQL server for reads and
writes to succeed. Without one, operations return
KeyringCapability::Status::UNAVAILABLE.
Status Values
KeyringCapability::Status is a scoped enum returned by read() (inside
ReadResult) and write():
Declaring the Capability
Include the header, declare a capability object at file scope, and pass it to.with():
g_keyring object is populated by the server at load time. The
read() and write() methods return Status::UNAVAILABLE at runtime
when no keyring component is installed — check that status on each call
rather than gating on a separate availability probe.
Reading and Writing
data_id is the key identifier. auth_id is the owning user — pass an
empty string (or omit it on read, which defaults to {}) to read or write
internal keys not associated with a specific user.
read returns a ReadResult by value. Bind it with structured bindings:
Status::OK, value is empty.
write returns Status directly and stores data under data_id /
auth_id.
Complete Example
This is a simplified version of thevsql_keyring_reader test extension
that ships with the server. It registers 2 VDFs: keyring_read and
keyring_store.
Status Variables
The status_var capability (vsql::preview::status_var) lets an extension
expose long long and double counters as MySQL status variables. The
extension owns the storage and writes to it; the server reads through the
pointers each time the status variable is queried.
Build the capability with vsql::preview_status_var::make_capability(), passing
a braced list of descriptors from make_int(name, value_ptr) or
make_double(name, value_ptr). The template deduces the count from the
braced list, so no explicit size is required.
Complete Example
make_int requires a long long *; make_double requires a double *.
Those are the only two types supported.
Accessing from SQL
AfterINSTALL EXTENSION my_ext, the variable is visible with the extension
name as a prefix:
++ may
occasionally be lost; this is acceptable for approximate call counters exposed
via SHOW STATUS.
System Variables
The sys_var capability (vsql::preview::sys_var) lets an extension register
MySQL system variables backed by extension-owned storage. Three types are
supported: BOOL (bool *), INT (long long *), and STR (char **).
INT descriptors also carry min_val and max_val bounds; all descriptors
carry a default value and a comment.
Build the capability with vsql::preview_sys_var::make_capability() and the
matching factory functions make_bool, make_int, and make_str. The
capability object also exposes get() and set() for
programmatic access from extension code. Both return false on success.
To react to value changes, chain .on_change<&fn>() on a descriptor. The
callback receives a sv::SysVarChange with var_name() and typed accessors
(as_int(), as_real(), as_str()).
The capability object must have static storage duration. MySQL writes directly
to the storage pointers when the user sets a variable.
Complete Example
Accessing from SQL
AfterINSTALL EXTENSION my_ext, variables are accessible using the extension
name as a component prefix:
Reading and Writing from Extension Code
For INT and BOOL variables, read the global storage pointer directly — MySQL updates those atomically. To update a variable through MySQL (so locking, range validation, and persistence are handled by the server), callSYS_VARS.set(extension_name, var_name, scope, value). Both set and get
return false on success.
scope argument controls persistence:
Thread Worker
The thread worker capability (vsql::preview::thread_worker) lets an
extension run a background thread driven by the server. The thread is started
and stopped via a control system variable that the server registers at
extension load; the server invokes the extension’s work function on a periodic
timer, on file-descriptor readiness, or in response to enable/disable events.
The capability name VEF_PREVIEW_THREAD_WORKER_NAME is
"vsql::preview::thread_worker".
Declaring the Capability
Include the header, declare aThreadWorkerCapability instantiated on your
work function at file scope, and pass it to .with():
ThreadWorkerCapability<&my_work>), so it must be a function with the
signature shown below. The first constructor argument is the thread-name
suffix; the optional second argument overrides the control sys var name.
Work Function Signature
reason indicates why the server called the function. thread is the
server-owned handle for this worker (NULL on the initial VEF_WAKEUP_ENABLE
call — see below). arg is the opaque pointer registered on the descriptor;
it is passed through unchanged.
Wakeup Lifecycle
The server calls the work function with one of four reasons:
The
thread parameter is NULL when the reason is VEF_WAKEUP_ENABLE, because
the thread handle does not exist yet at that point. For the other three
reasons, thread is non-null.
Wakeup Return Value
vef_next_wakeup_t to update the next wakeup
configuration. A zero value in either field means “keep the current setting”
— return a value-initialized struct (return {};) to leave both unchanged.
To set a new poll file descriptor, return its value (must be greater than
zero). To clear an existing poll file descriptor, return -1 in poll_fd.
The return value is ignored when the reason is VEF_WAKEUP_DISABLE.
Thread Name and Control Variable
Two fields on the descriptor control naming:suffix— the thread-name suffix. The server prepends the extension name, producing thread names likemy_ext/monitor.var_name— optional. When non-null, the server registers this exact name as the control system variable. When null, the server uses the default pattern{suffix}_enabled.
SET GLOBAL {suffix}_enabled = ON; set it OFF to stop it.
Complete Example
A minimal extension with a single periodic worker that increments a heartbeat counter on each timer tick.vsql_allow_preview_extensions = ON), the
server registers a heartbeat_enabled system variable. Enable the worker with:
SQL Query
The sql_query capability (vsql::preview::sql_query) lets an extension
execute SQL statements from a background thread. Queries run inside the
server through the capability vtable — extensions do not link against any
MySQL client library.
The capability name VEF_PREVIEW_SQL_QUERY_NAME is
"vsql::preview::sql_query".
Declaring the Capability
Include the header, declare aSqlQueryCapability at file scope, and pass it
to .with(). It is typically registered alongside a ThreadWorkerCapability,
since sessions are opened from the worker callback:
g_sql.open(handle) returns a Session. Check it with operator bool before
use; an invalid Session indicates the capability vtable was not bound or the
server could not allocate a session. The Session is move-only and closes
itself on destruction.
Executing Queries
ASession produces a SqlQuery via session.sql(sv). The query can be run
in two modes:
execute()— runs the statement and buffers the full result set in aResult. Iterate rows by callingnext()at the caller’s pace.for_each(fn)— runs the statement and invokesfnonce per row as rows are produced, without buffering. The returnedResultcarries diagnostics only (no rows).
Result. A non-null Result does not mean the statement
succeeded — call has_error() to find out.
Buffered (execute):
column_str() returns a string_view that is valid only until the next
next() call or until Result is destroyed. Copy it if a longer lifetime is
needed. A string_view with data() == nullptr indicates SQL NULL.
Streaming (for_each):
Row passed to the callback is valid only for the duration of the call —
do not store references to it across rows. The Result returned by
for_each holds no buffered rows; next() on it will not yield data. Use it
only for has_error(), error(), warning_count(), and warning(i).
Diagnostics
Bothexecute() and for_each() surface diagnostics through the returned
Result. A diagnostic is one Diag:
Result exposes:
error() returns a default-constructed Diag (errno_ == 0) when the
statement succeeded. warning(i) returns a default-constructed Diag when
i >= warning_count().
The sqlstate and message views point into storage owned by the Result
and become invalid when the Result is destroyed — copy them if they need to
outlive it.
Complete Example
A worker that runs one buffered query and one streaming query on each tick, logging diagnostics from both:Column Storage
Column storage lets an extension register a custom binary on-disk layout directly with InnoDB for one of its custom types, instead of routing the type’s bytes through the row’s VARBINARY payload. Use it when your type needs an on-disk shape VARBINARY cannot express — for example, a packed array of floats that must live in dedicated pages. This is a capability feature: it enables new storage layouts, not a tuning knob for existing ones.Declaring the Capabilities
Two preview capabilities work together:vsql::preview::storage— opens access to InnoDB storage infrastructure (mini-transactions, segments, pages). Declare aStorageCapabilityat file scope.vsql::preview::column_store— binds a per-type storage implementation to one of the extension’s custom types. Declare aColumnStoreCapabilityat file scope usingmake_column_store<Ctx>(TYPE).…build().
.with() on make_extension():
make_column_store<MyCtx>(MY_TYPE) ties the implementation to one custom
type registered on the same extension. All seven slots are required at
build() time because each maps to a distinct point in the column lifecycle
that InnoDB will reach during normal operation.
The Seven Storage Functions
Every function takesstorage::Column::StorageCtx<MyCtx>*, whose user()
accessor returns the extension’s per-column state and whose arena() provides
server-managed allocation for auxiliary objects. Every function returns false
on success and true on error, writing a message into error_msg (capacity
error_msg_len) so failures surface to the SQL client.
mark_delete and purge are distinct because InnoDB MVCC requires deleted
rows to remain readable by older snapshots until purge runs.
Per-Column Context and the Arena
The C++ SDK default-constructsMyCtx before calling either create or load —
ctx->user() is already populated when your function is entered. MyCtx must
be default-constructible; the C++ SDK calls T() with no arguments.
Use ctx->user() directly to initialize state. Do not call
ctx->arena().construct<MyCtx>() — that allocates a second, unused instance
and ctx->user() does not point to it.
load follows the same pattern — ctx->user() is pre-populated and
storage_ref carries the packed value stored by ctx->set_ref() in create:
ctx->arena() only to allocate auxiliary objects that are too large or
dynamic to embed directly in MyCtx. The C++ SDK destroys the arena — and calls
~MyCtx() — automatically after drop returns, regardless of whether drop
succeeds.
InnoDB Access Utilities
Include<villagesql/preview/storage_api.h> for the InnoDB primitives.
All page reads and writes must occur inside a mini-transaction:
create time — see the create and load
examples in Per-Column Context above for the complete setup pattern. During
DML operations, get a segment reference from the root page to allocate new
pages:
mtr_ref to write calls so InnoDB logs the change:
Reading or writing inside the header or trailer regions corrupts the page —
InnoDB uses those byte ranges for its own bookkeeping and checksum.
Statement Events
The statement event capability (vsql::preview::statement_event) runs an
extension-provided handler after each query finishes executing. The server
invokes the handler synchronously on the query’s own thread and passes
execution metadata — the query text, timing, row counts, connection identity,
and optimizer quality indicators. Use it for slow-query logging, auditing, or
metrics collection.
The capability name VEF_PREVIEW_STATEMENT_EVENT_NAME is
"vsql::preview::statement_event".
Declaring the Capability
Declare aStatementEventCapability, instantiated on the firing phase and your
handler function, at file scope and pass it to .with():
vef_statement_event_phase_t
value. VEF_STATEMENT_EVENT_POSTEXECUTE fires after a query finishes executing,
on success or failure, and is the only phase implemented in this version. The
other vef_statement_event_phase_t values are reserved; declaring a handler for
one of them causes the server to reject INSTALL EXTENSION.
Handler Arguments
StatementEventArgs is a read-only view of the completed query; at the
POSTEXECUTE phase every field is populated. Selected accessors:
Because
query() returns the server’s rewritten form when one exists,
credential-bearing statements arrive with the secret obfuscated rather than in
cleartext, matching how the general, slow, and binary logs already redact them:
SET PASSWORD, CREATE/ALTER USER ... IDENTIFIED BY, CHANGE REPLICATION SOURCE ... SOURCE_PASSWORD, and CREATE SERVER ... OPTIONS(PASSWORD ...).
Statements with no rewrite rule are delivered verbatim.
String accessors such as query(), sqlstate(), and error_message() point
into storage that is valid only for the duration of the handler call — copy the
bytes if you need them after the handler returns.
StatementEventResult::error_msg(fmt, ...) writes a printf-formatted message.
At the POSTEXECUTE phase the message is advisory: the server logs it but does
not propagate it to the client.
Complete Example
A condensed form of thevsql_slow_query_log
test extension that ships with the server. It logs each query whose execution
time exceeds a threshold, combining the statement event capability with
system variables for runtime configuration:

