Metadata-Version: 2.4
Name: zova
Version: 1.6.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Rust
Classifier: Topic :: Database
License-File: LICENSE
Summary: SQLite-backed embedded database for records, objects, vectors, and graph relationships in one local file.
Keywords: zova,sqlite,database,objects,vectors,graphs
Home-Page: https://github.com/ata-sesli/zova
Author: Ata Sesli
License-Expression: MIT
Requires-Python: >=3.13
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/ata-sesli/zova
Project-URL: Issues, https://github.com/ata-sesli/zova/issues
Project-URL: Repository, https://github.com/ata-sesli/zova

# Zova Python Bindings

This package contains the source-first Python bindings for Zova.

It is a PyO3/maturin extension backed by the safe Rust `zova` binding. It does
not wrap the C ABI directly with `ctypes` or cffi. The native build still uses
Zova's C ABI underneath through the Rust `zova-sys` crate, so Python gets the
same records/objects/vectors foundation without reimplementing the ABI ownership
rules.

## Contents

1. [How It Fits](#how-it-fits)
2. [Install](#install)
3. [Local Development](#local-development)
4. [What It Covers](#what-it-covers)
5. [Pools](#pools)
6. [Savepoints](#savepoints)
7. [Operational Safety](#operational-safety)
8. [Extensions](#extensions)
9. [App Events](#app-events)
10. [Objects](#objects)
11. [Vectors](#vectors)
12. [Graphs](#graphs)
13. [Bound Stores](#bound-stores)
14. [Low-Level Surfaces](#low-level-surfaces)
15. [SQL-Native Vector Search](#sql-native-vector-search)

## How It Fits

Python users import `zova`. The extension is built with PyO3 and reuses the
safe Rust binding, which in turn links Zova's C ABI.

```mermaid
flowchart LR
    App["Python app"]
    PyPkg["zova Python package"]
    PyO3["PyO3 extension"]
    Rust["Rust zova crate"]
    CABI["libzova_c.a"]
    File["local .zova file"]

    App --> PyPkg
    PyPkg --> PyO3
    PyO3 --> Rust
    Rust --> CABI
    CABI --> File
```

## Install

After the Python package is published to PyPI:

```sh
python -m pip install zova
```

The Python package is backed by a PyO3 extension built through maturin and
Cargo. Users need Python 3.13 or newer; CPython 3.13 and 3.14 are the tested
runtime matrix. Linux wheels target glibc 2.28 or newer. Published stable-ABI
wheels do not require Rust, Cargo, Zig, or a local C compiler. Zova does not
publish a Python source distribution, so an unsupported platform or
interpreter fails without attempting a native build.

The release workflow builds Linux/macOS x86_64/arm64 and Windows x86_64
stable-ABI wheels.

The current `.zova` format is 14, and Zova does not migrate older
format databases in place. Format-9, format-10, format-11, format-12, format-13 and format-14 databases can be probed and
migrated forward with the module-level `probe_format(path)` and
`migrate_database(source, destination, *, verify=True)` functions: migration is
explicit, copy-forward, publishes a separately validated format-15 destination,
and never mutates the source. Like `Database.open`, `migrate_database` accepts
`extension_bundles` and `trust_store_path` for databases with a non-bundled
extension installed. It also accepts `plugins` (see
[Low-Level Surfaces](#low-level-surfaces)).

## Local Development

From `bindings/python`:

```sh
uv run --isolated --with maturin --with pytest maturin develop
uv run --isolated --with pytest python -m pytest
```

The native build uses maturin, Cargo, and the Rust `zova` crate. Users do not
need to locate a shared C library manually.

To test against a native library built with `-Dexperimental-cwal`, build it
from the repository root with `zig build c-abi -Dexperimental-cwal
-Doptimize=ReleaseFast -Denable-dynamic-extensions=false -p <prefix>` and set
`ZOVA_LIB_DIR=<prefix>/lib` and `ZOVA_INCLUDE_DIR=<prefix>/include` for both
commands above. Cargo does not notice a rebuilt library at the same path, so
use a separate `CARGO_TARGET_DIR` for it. The CWAL tests skip on a library
without CWAL; set `ZOVA_REQUIRE_CWAL=1` to make them fail instead.

The Python API is part of the stable 1.x contract described in
`../../API_STABILITY.md`.

## What It Covers

The Python package exposes database lifecycle, conversion, prepared SQL
statements, transactions, explicit vacuum, backup/compact/restore, objects,
streaming object writes, vectors, SQL-native vector search, graphs,
bundled extension lifecycle, same-process app events, context managers, and
Zova status exceptions.

One Python `Database` object owns one native handle. The native C ABI serializes
calls on that handle, so one handle is safe but not parallel. Open additional
database handles when an application needs independent concurrent connections;
SQLite locking rules still apply across handles. PyO3 classes remain unsendable
in this release even though the native C ABI serializes its own calls.

Use `Database.open(path, read_only=True)` for read-only handles, and
`Database.set_busy_timeout(milliseconds)` when an application wants SQLite to
wait briefly on cross-handle contention. No nonzero timeout is installed by
default. A write from a WAL transaction whose view predates another handle's
commit raises `ZovaError` with `status_name == "ZOVA_BUSY_SNAPSHOT"` without
waiting: roll back and run the transaction again. `docs/concurrency.md` lists,
per lock error, whether to wait or retry.

Use `Database.last_insert_rowid()`, `Database.changes()`,
`Database.total_changes()`, and `Statement.column_name(index)` for normal
application SQL record helpers. They do not expose or stabilize Zova's private
`_zova_*` tables.

## Pools

`zova.Pool` opens one writer and a fixed number of read-only readers on one
database file. The pool object is safe to share between threads.

```python
import zova

with zova.Pool.open("app.zova", reader_count=4) as pool:
    with pool.writer() as writer:          # waits until the writer is free
        writer.exec("insert into notes(body) values ('draft')")
    with pool.reader(timeout=0.05) as reader:
        statement = reader.prepare("select count(*) from notes")
```

What runs in parallel: each reader and the writer are separate SQLite
connections, so up to `reader_count` reads run at the same time as one write.
In WAL mode a reader sees the last committed state and does not wait for the
writer. Writes still run one at a time, on the single writer. On pool
handles, `Database.exec` and `Statement.step` release the GIL, so other
Python threads run while SQLite works; other calls keep the GIL. A reader
raises `ZovaError` with `status_name == "ZOVA_READ_ONLY"` for writes.

- `reader(timeout=None)` and `writer(timeout=None)` return a `Database`;
  `None` waits until a handle is free and the wait releases the GIL. A
  timeout in seconds that expires raises `ZovaError` with status `ZOVA_BUSY`.
- A checked-out `Database` belongs to the thread that checked it out.
  `close()`, or leaving its `with` block, hands it back and rolls back any
  transaction still open on it.
- `register_function` and `set_object_compression` apply to every handle and
  raise `ZOVA_MISUSE` while any handle is checked out.
- `Pool.close()` drops the pool; handles still checked out stay usable and
  the native pool closes when they are returned. In-memory databases are
  refused. `reader_count` 0 selects 4 and at most 64 are allowed;
  `busy_timeout_ms` 0 selects 5000.

## Savepoints

Use explicit savepoints for partial rollback inside one database connection:

```python
with zova.Database.open("app.zova") as db:
    db.begin_immediate()
    db.savepoint("attach_file")
    db.exec("insert into attachments(filename) values ('draft.txt')")
    db.rollback_to_savepoint("attach_file")
    db.release_savepoint("attach_file")
    db.commit()
```

Savepoint names are strict ASCII identifiers: 1-64 bytes, first byte
`[A-Za-z_]`, remaining bytes `[A-Za-z0-9_]`, and no case-insensitive `_zova_`
prefix. `rollback_to_savepoint()` keeps the savepoint active;
`release_savepoint()` removes it.
An inner released savepoint can still be undone by rolling back an outer
transaction or savepoint.

Use `savepoint_context()` when you want rollback cleanup tied to a `with` block:

```python
with db.savepoint_context("attach_file") as scoped_db:
    scoped_db.exec("insert into attachments(filename) values ('draft.txt')")
```

On normal exit the context releases the savepoint. On exception it rolls back,
releases, and then re-raises the original exception when cleanup succeeds.

## Operational Safety

Use `backup_to()` for a faithful snapshot, `compact_to()` for a
space-reclaiming copy, and `restore_backup()` to copy a backup into a new
destination file. Destinations must be `.zova` paths and are never overwritten.

```python
with zova.Database.open("app.zova") as db:
    db.backup_to("app.backup.zova")
    db.compact_to("app.compact.zova")

zova.restore_backup("app.backup.zova", "app.restored.zova")
```

By default, each operation verifies the destination after copying. Pass
`verify=False` only when you will verify separately, for example with
`zova check --deep`.

`reclaim_space()` releases free pages in place, in short write transactions,
from files in incremental auto-vacuum mode, the default for files created by
format 13. It returns one `zova.ReclaimedMember` per member file; a member whose
`auto_vacuum` is `"none"` releases nothing and needs `compact_to()` instead.
`max_pages=n` caps one call.

```python
with zova.Database.open("app.zova") as db:
    for member in db.reclaim_space():
        print(member.member, member.pages_released, member.free_pages_left)
```

`set_journal_mode("wal")` switches the main file and every attached store
together: either every member ends in the requested mode, or the members
already switched are restored and the call fails. `journal_modes()` returns one
`zova.JournalModeMember` per member, and `checkpoint(mode="passive")` returns
one `zova.CheckpointedMember` per member with its WAL and checkpointed frame
counts. Only WAL mode is stored in the file; set it right after `create`. See
`docs/concurrency.md`.

```python
with zova.Database.open("app.zova") as db:
    db.set_journal_mode("wal")
    for member in db.checkpoint("truncate"):
        print(member.member, member.wal_frames, member.checkpointed_frames)
```

Bound stores keep a main database's objects, vectors or graphs in separate
`.zova` files. `zova.create_store(role, path)` creates an empty store, with
`role` one of "object", "vector" or "graph"; `bind_store`, `split_store`
(which moves existing rows and returns `SplitStoreCounts`), `unbind_store` and
`bound_store` (a `BoundStoreInfo`, or `None` when unbound) run on `Database`.
They need a read-write handle outside a transaction; a bound path is recorded
as given.

```python
zova.create_store("object", "objects.zova")
with zova.Database.open("app.zova") as db:
    db.bind_store("object", "objects.zova")
    print(db.bound_store("object").path)
```

Experimental: `set_commit_protocol("cwal")` switches the set to the cross-file
commit protocol (CWAL), so a transaction that writes several members commits
atomically across them, and `set_commit_protocol("none")` switches back. It
reopens the handle, and only libraries built with `-Dexperimental-cwal` support
it; others fail with `ZOVA_UNSUPPORTED_ZOVA_VERSION`. Every member must be in
WAL mode, and the handle must be the only one on the set, outside a
transaction, with no open child handles or registered SQL functions; register
SQL functions after switching. A CWAL set allows one read-write handle and any
number of read-only ones. Do not open its member files with Python's `sqlite3`
or another SQLite library in the same process. See `docs/concurrency.md`.

Diagnostic recovery commands such as `zova doctor`, `zova salvage --dry-run`,
and `zova salvage <source> <destination>` are CLI-first. In v0.25, CLI salvage
copies valid core data and uses extension salvage hooks for extension-owned
storage. The Python package does not expose typed doctor/salvage report APIs
yet, and library code should not parse the human text output as a stable
binding contract.

## Extensions

Python exposes lifecycle methods for extensions already present in the current
process registry. The default registry includes bundled extensions such as
`trgm`, so Python applications can install, list, check, and drop `trgm`
directly. From 1.2.0, wheels also accept explicit trusted native bundles:

```python
db = zova.Database.create("app.zova", extension_bundles=["./search.zovaext"])
db.install_extension("search")
db.close()
db = zova.Database.open("app.zova", read_only=True,
                        extension_bundles=["./search.zovaext"])
```

Both constructors accept `trust_store_path`; omit it for Zova's default store.
First run `zova extension trust ./search.zovaext`. Opening never grants trust
or loads paths from the database. Native code and dependencies must match the
host. Owned statements retain their connection and libraries after `db.close()`.
Published 1.1.0 wheels do not include this support. Python does not wrap
extension authoring; application SQL functions, linked plugins and explicit
extension upgrades are described under
[Low-Level Surfaces](#low-level-surfaces). See the
[capability matrix](../../docs/extensions.md#availability-and-binding-matrix).

See [../../docs/extensions.md](../../docs/extensions.md) for the current host
contract and trust model. A fuller records/objects/vectors/graphs example lives
in `examples/extensions.py`.

```python
with zova.Database.open("app.zova") as db:
    db.install_extension("trgm")
    info = db.extension_info("trgm")
    assert info.storage_prefix == "_zova_ext_trgm_"
    db.check_extensions()

    with db.prepare(
        "select zova_trgm_put('messages', ?1, 'record', 'messages', ?2, ?3)"
    ) as stmt:
        stmt.bind_text(1, "message:123")
        stmt.bind_text(2, "123")
        stmt.bind_text(3, "attachment upload failed")
        assert stmt.step() == zova.Step.ROW

    with db.prepare(
        """
        select document_id, score
        from zova_trgm_search
        where index_name = 'messages'
          and query = ?1
          and "limit" = 10
        order by rank
        """
    ) as stmt:
        stmt.bind_text(1, "attachement failed")
```

## App Events

Use `listen` / `notify` for same-process storage workflow notifications. They
are explicit, in-memory, local to one open `Database` handle, and delivered only
after the surrounding Zova transaction commits. Rollback discards pending
notifications.

```python
with zova.Database.open("app.zova") as db:
    with db.listen("message:123:attachments") as sub:
        db.begin_immediate()
        db.exec("insert into attachments(message_id, name) values (123, 'photo.jpg')")
        db.notify("message:123:attachments", "changed")
        db.commit()

        note = sub.try_receive()
        if note is not None:
            print(note.channel, note.payload)
```

SQL `zova_notify(...)` follows the same transaction rules when the surrounding
transaction/savepoint was opened through Zova helpers; raw SQL transaction
scopes are rejected because Zova cannot track their notification lifetime.

Event delivery is queue-only in v0.18: no callbacks, no blocking receive, no
cross-process delivery, no replay after restart, and no automatic logging of SQL,
object, vector, or graph mutations. Each subscription queue holds 1024
notifications and drops the oldest entries on overflow; the next received
notification reports how many were dropped before it.

Handles of one `Pool` share notifications: a commit on any pool handle
delivers to subscriptions on every pool handle and to `Pool.listen(channel)`
subscriptions, which keep no handle checked out and can be used from any
thread. To notice commits made by other handles or processes, call
`Database.has_changed()`: it reports whether the main database or a bound
store committed since the previous call on that handle, and the first call
returns `True`.

## Objects

The Python binding exposes Zova objects as content-addressed byte values while
keeping application metadata in normal SQL tables.

```python
import zova

with zova.Database.create("app.zova") as db:
    db.exec(
        "create table attachments("
        "id integer primary key, "
        "filename text not null, "
        "object_id blob not null)"
    )

    object_id = db.put_object(b"hello from Zova")

    with db.prepare("insert into attachments(filename, object_id) values (?1, ?2)") as stmt:
        stmt.bind_text(1, "hello.txt")
        stmt.bind_blob(2, bytes(object_id))
        stmt.step()

    assert db.read_object_range(object_id, 0, 5) == b"hello"
```

For large inputs, use `ObjectWriter` so the full object does not have to be held
in memory by the caller:

```python
with db.object_writer() as writer:
    writer.write(b"chunk one")
    writer.write(b"chunk two")
    object_id = writer.finish()
```

If a writer leaves the context without `finish()`, it is cancelled and any
unreferenced chunks written by that writer are cleaned up. Writer operations
follow Zova's object transaction policy in single-file mode. When an object
store is bound, object writes participate in the same Zova transaction/savepoint
scope through SQLite `ATTACH`.

`db.set_object_compression(zova.ObjectCompression.LZ4)` makes that handle store
each new chunk as an LZ4 block when that is smaller than the chunk. The setting
is per handle, defaults to `ObjectCompression.NONE`, and is not stored in the
file. Object IDs, chunk hashes and manifests are unchanged, and every read
decodes compressed chunks.

To serve large objects with seeking, such as HTTP range requests, open an
`ObjectSeekableReader`. It is a file-like object (`read`, `readinto`, `seek`,
`tell`, `close`, context manager). It verifies each chunk once before
returning its bytes and holds no read transaction between calls:

```python
with db.object_seekable_reader(object_id) as reader:
    reader.seek(1024 * 1024)
    part = reader.read(64 * 1024)
```

Loose chunks and assembly are also exposed for receive-side workflows:
applications track transfer state in their own SQL tables, call
`put_object_chunk()` for verified chunks, then call
`assemble_object_from_chunks()` when the manifest is complete.

## Vectors

The Python binding exposes Zova vectors with the same model as the Rust binding:
Zova stores numeric vectors in named collections, while application metadata
stays in normal SQL tables.

```python
import zova

with zova.Database.create("vectors.zova") as db:
    db.exec(
        "create table chunks("
        "id text primary key, "
        "document_id text not null, "
        "text text not null, "
        "vector_id text not null)"
    )

    db.create_vector_collection(
        "chunks",
        zova.VectorCollectionOptions(2, zova.VectorMetric.L2, zova.VectorElementType.F32),
    )
    db.put_vectors(
        "chunks",
        [
            zova.VectorInput("chunk:1", zova.VectorElementType.F32, [0.0, 0.0]),
            zova.VectorInput("chunk:2", zova.VectorElementType.F32, [1.0, 0.0]),
        ],
    )

    db.exec(
        "insert into chunks(id, document_id, text, vector_id) values "
        "('c1', 'doc-a', 'first chunk', 'chunk:1'), "
        "('c2', 'doc-a', 'near chunk', 'chunk:2')"
    )

    results = db.search_vectors_in(
        "chunks",
        zova.VectorElementType.F32,
        [0.0, 0.0],
        ["chunk:1", "chunk:2"],
        2,
    )
    for result in results:
        with db.prepare("select text from chunks where vector_id = ?1") as stmt:
            stmt.bind_text(1, result.id)
            stmt.step()
            print(result.id, result.distance, stmt.column_text(0))
```

Vector APIs are typed by default. `F32` uses Python floats, `F16` values are
raw IEEE 754 binary16 bits carried as integer `uint16` bit patterns, and `I8`
values are raw signed byte values with no quantization metadata.

```python
db.create_vector_collection(
    "scores_i8",
    zova.VectorCollectionOptions(2, zova.VectorMetric.L2, zova.VectorElementType.I8),
)
db.put_vector("scores_i8", "near", zova.VectorElementType.I8, [1, -1])

db.create_vector_collection(
    "halves",
    zova.VectorCollectionOptions(2, zova.VectorMetric.L2, zova.VectorElementType.F16),
)
db.put_vector("halves", "one", zova.VectorElementType.F16, [0x3C00, 0x0000])
assert db.get_vector("halves", "one").values == [0x3C00, 0x0000]
```

Search is exact and lower distance is better. Candidate-filtered searches skip
missing ids and deduplicate duplicate candidates. Search-by-id excludes the
source vector. Threshold variants are inclusive, and dot-product thresholds may
be negative because dot distance is `-dot_product`.

Deleting a vector collection removes Zova's private vector rows only. User SQL
metadata rows that reference vector ids are application-owned and remain in
place.

## Graphs

Graphs store relationship topology while application metadata stays in SQL
tables, objects, and vectors. Apps provide stable node IDs and can point nodes
at records, objects, object chunks, vectors, entities, facts, concepts, or
external references.

```python
db.create_graph(zova.DEFAULT_GRAPH_NAME)
db.put_graph_node(
    zova.GraphNodeInput(
        zova.DEFAULT_GRAPH_NAME,
        "message:1",
        "message",
        zova.GraphTargetType.RECORD,
        "messages",
        "1",
    )
)
db.put_graph_node(
    zova.GraphNodeInput(
        zova.DEFAULT_GRAPH_NAME,
        "entity:zova",
        "entity",
        zova.GraphTargetType.ENTITY,
        None,
        "zova",
    )
)
db.put_graph_edge(
    zova.GraphEdgeInput(
        zova.DEFAULT_GRAPH_NAME,
        "message:1",
        "mentions",
        "entity:zova",
    )
)
```

Use `graph_neighbors()` for one-hop expansion and `graph_walk()` for bounded
directed walks. Zova validates object, chunk, and vector targets it owns, but
arbitrary SQL row existence remains the application's job. Node IDs may contain
sensitive app identifiers, so choose export-safe IDs when files may leave the
app.

SQL-native graph helpers are available through ordinary prepared statements:

```python
with db.prepare(
    "select m.body "
    "from zova_graph_neighbors as g "
    "join messages as m on m.graph_node_id = g.node_id "
    "where g.graph_name = 'default' "
    "and g.source_node_id = 'message:1' "
    'and g."limit" = 20 '
    "order by g.rank"
) as stmt:
    ...
```

Use `zova_graph_neighbors` for one-hop joins and `zova_graph_walk` for bounded
directed walks with `depth`, `predecessor_node_id`, and `edge_type` columns.

## Bound Stores

In v0.25, a `.zova` file may be bound to one object store, one vector store,
and one graph store through the native Zig API or CLI. The Python object,
vector, and graph methods above transparently use those stores after
`Database.open`. Store
create/bind/unbind/split management is not exposed as a Python API yet.

## Low-Level Surfaces

The Python package wraps every function in the C ABI. Beyond the APIs above:

- Batch graph writes: `put_graph_nodes`, `put_graph_edges`,
  `delete_graph_nodes`, `delete_graph_edges`, and `graph_degree`.
- Opaque-key graph APIs: `put_graph_nodes_keyed`, `put_graph_edges_keyed`,
  `get_graph_nodes_keyed`, `get_graph_edges_keyed` (a missing key gives
  `None`), `graph_neighbors_keyed`, `graph_degrees_keyed`,
  `get_graph_edge_payloads`, `replace_graph_edge_payloads`, `graph_scan`
  cursor pages, `graph_walk_direction` (and `graph_walk_direction_profiled`),
  and the `build_fresh_graph*_keyed` builders, which take
  `GraphFreshNodeInput` and `GraphFreshEdgeInput` values. Keys are opaque
  integers; do not persist them across a graph rebuild.
- `Database.begin_fresh_build()` returns a `FreshBuild` that loads tables, FTS
  tables, one graph and vector collections into empty targets, then publishes
  them together with `finish()`. `abort()`, `close()`, leaving a `with` block,
  and any failure (including invalid row values) roll the session back. While
  it is active, other calls on the same `Database` fail.
- `delete_vectors` and `search_vectors_multi_i8`, with the
  `VectorMultiI8SearchMode` and `VectorMultiI8Aggregation` enums.
- `register_function(name, arity, function, *, deterministic=False,
  direct_only=False, innocuous=False)` registers a scalar SQL function.
  Arguments arrive as `None`, `int`, `float`, `str`, or `bytes`; an exception
  or an unsupported result fails the statement. The function runs while the
  database is busy with the calling statement, so it must not use the same
  `Database` or its statements: that call never returns.
- `LinkedPlugin.from_address(address)` wraps a `zova_plugin_descriptor_v1`
  linked into the process, such as one exported by a library loaded with
  `ctypes`. The descriptor must stay valid for the rest of the process; a
  wrong address crashes it. Pass linked plugins as `plugins=[...]` to
  `Database.create`, `Database.open`, `Database.open_for_extension_upgrade`,
  and `migrate_database`.
- `Database.open_for_extension_upgrade` opens without running installed
  extension hooks, so `extension_upgrade` and `extension_rebuild` can repair a
  database whose extension check fails.
- `Database.create(path, page_size=...)`, `abi_version()`, and the
  `verify_extension_bundle`, `trust_extension_bundle` and
  `untrust_extension_bundle` functions.

## SQL-Native Vector Search

Zova registers SQL vector functions and the `zova_vector_search` virtual table
on Zova database connections. Bind query vectors as little-endian `f32` blobs
with `encode_f32_le()`:

```python
query = zova.encode_f32_le([0.0, 0.0])

with db.prepare(
    "select c.id, zova_vector_distance('chunks', c.vector_id, ?1) as distance "
    "from chunks as c "
    "where c.document_id = 'doc-a' "
    "order by distance "
    "limit 10"
) as stmt:
    stmt.bind_blob(1, query)
```

Row-to-row distances use `zova_vector_distance_by_id(collection, vector_id,
source_vector_id)`. Collection-wide SQL search uses `zova_vector_search`:

```python
with db.prepare(
    "select c.text, s.distance "
    "from zova_vector_search as s "
    "join chunks as c on c.vector_id = s.vector_id "
    "where s.collection = 'chunks' "
    "and s.query_vector = ?1 "
    "and s.top_k = 10 "
    "order by s.rank"
) as stmt:
    stmt.bind_blob(1, query)
```

Python's built-in `sqlite3` module opens an ordinary SQLite connection and does
not automatically register Zova's SQL functions or virtual table. Use
`zova.Database` for SQL-native vector search in this binding. A future SQLite
loadable extension may make the SQL surface available to external SQLite
connections.

