mturso

    MoonBit bindings for Turso Database, layered on the official C ABI (turso.h).

    sqlite
    turso
    database
    ffi
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    2 days ago
    Downloads
    10

    #mturso

    MoonBit bindings for Turso — the Rust rewrite of SQLite — built on the official C ABI (turso.h), with SQLite-compatible SQL. Linux, macOS, and Windows x64 are supported; WebAssembly is on the way.

    platforms turso license

    Database is a database and its connection pool; Connection is one checkout from that pool. Queries are typed and streamed row by row, so a large result set never has to be materialised up front. The async API keeps the event loop free while a statement runs.

    #Quickstart

    #Local database

    async fn main {
    let db = @mturso.Database::open(":memory:") // or a file path
    defer db.close()

    ignore(db.execute("create table t(id integer primary key, name text)"))

    // Explicit checkout. `close()` returns the connection to the pool.
    let conn = db.connect()
    defer conn.close()

    ignore(conn.execute(
    "insert into t(name) values (?1), (?2)",
    params=["alice", "bob"],
    ))

    // Pull rows one at a time.
    let rows = conn.query("select id, name from t order by id")
    defer rows.close()
    while rows.has_next() {
    let row = rows.get_row()
    let id : Int = row.get(0)
    let name : String = row.get(1)
    println("\{id}: \{name}")
    }
    }

    #Remote sync

    Connect a local replica to a Turso-compatible remote. The first open bootstraps the replica; later pushes and pulls synchronize changes incrementally.

    async fn sync_example() -> Unit raise @mturso.TursoError {
    let config = @mturso.SyncConfig::new(
    "./notes.db",
    remote_url="https://your-database.turso.io",
    auth_token=Some("your-token"),
    )
    let db = @mturso.SyncDatabase::open(config)
    defer db.close()

    let conn = db.connect()
    defer conn.close()

    ignore(
    conn.execute(
    "create table if not exists notes(id integer primary key, body text)",
    ),
    )
    ignore(
    conn.execute(
    "insert into notes(body) values (?1)",
    params=["written locally"],
    ),
    )

    db.push()
    let changed = db.pull()
    let stats = db.stats()
    println("changed=\{changed}, revision=\{stats.revision}")
    }

    #Features

    • SQLite-compatible SQL, in process — use familiar SQL against file or in-memory databases, with SQLite-compatible storage and no separate database process to manage.
    • Typed queries and safe parameters — read integers, floats, text, blobs, NULL, JSON, and timestamps as native values, stream large result sets, and bind parameters without constructing SQL strings.
    • Async by default — slow queries and writes run off the MoonBit event loop, while independent connections continue to make progress.
    • Bounded connection pooling — cap concurrent connections and worker threads, reuse connections automatically, or hold one for a longer unit of work, with contention statistics available.
    • Transactions and contention handling — use explicit or managed transactions, including deferred, immediate, exclusive, read-only, and MVCC concurrent modes, plus retry helpers for busy locks and write conflicts.
    • Offline-first remote sync — bootstrap a local replica from a Turso-compatible remote, keep working offline, push local commits, pull incremental changes, and inspect or checkpoint sync state.
    • Self-hosted sync server — run against the pinned tursodb server or this project's native implementation, with SQL access, bootstrap, pull, push, and optional bearer authentication. The server is tested with both this client and the official Go sync client.
    • Runtime-loaded native engine — Linux x86_64 and Windows x64 packages include the Turso library and load it at runtime, so consumers do not need linker flags; tested macOS arm64 and Linux aarch64 builds fetch the matching library with one script.

    #Platform support

    Platform / targetStatusNotes
    Linux x86_64✅ testedCI runs the full suite plus local sync-server acceptance against pinned tursodb 0.8.2
    Linux aarch64✅ testedCI runs the suite on ubuntu-24.04-arm
    macOS arm64✅ testedCI runs the suite on macos-latest
    Windows x64✅ testedMSVC build; CI runs the full suite plus local sync-server acceptance. The DLL is loaded at runtime and workers use Win32 threads plus anonymous pipes
    WebAssembly / edge🧪 spikeMoonBit wasm + Turso wasm runs end to end under a Node worker host; browser/OPFS and a public API remain planned. See notes/wasm-spike.md and #10

    macOS x86_64 is deliberately absent (MoonBit ships no darwin-x86_64 toolchain). Windows ARM64 is unsupported because Turso v0.8.2 ships a 0-byte placeholder DLL in its windows_arm64 package.

    #Installation

    Add the package from Mooncakes, pinned to the first release:

    moon add jaredzhou/mturso@0.1.0

    Or add the dependency directly in your moon.mod:

    import { "jaredzhou/mturso@0.1.0", }

    Your package's moon.pkg only needs the import:

    import {
    "jaredzhou/mturso",
    "moonbitlang/core/async",
    }

    options(
    "allow-experimental-packages": [ "moonbitlang/core/async" ],
    )

    #Native dynamic library

    The engine is a native shared library loaded at runtime by ffi/loader.c. MoonBit package files therefore need no link, cc-link-flags, rpath, or LD_LIBRARY_PATH.

    The platform file names are:

    PlatformFile
    Linux x86_64 / aarch64libturso_sync_sdk_kit.so
    macOS arm64libturso_sync_sdk_kit.dylib
    Windows x64turso_sync_sdk_kit.dll

    MTURSO_LIB_PATH is an explicit file override. When it is unset, the lookup order is:

    1. the libs/ directory in the mturso source checkout used to build the binding
    2. libs/ beside the executable
    3. ./libs/ under the process working directory
    4. the platform's normal dynamic-loader search path

    For source-workspace development, no environment variable is normally needed. For another platform or architecture, place the matching library in libs/:

    bash scripts/fetch-turso-lib.sh

    The script only copies the platform library and updates its .sha256; it never changes moon.pkg. On Windows, run it from Git Bash or MSYS2.

    For a deployed executable, copy the library next to it:

    mkdir -p dist/libs cp /path/to/mturso/libs/libturso_sync_sdk_kit.so dist/libs/ ./dist/your-app

    On Windows the deployed path is <exe-dir>\libs\turso_sync_sdk_kit.dll.

    Or point to it explicitly:

    MTURSO_LIB_PATH=/opt/mturso/libturso_sync_sdk_kit.so ./your-app

    Use the .dylib name on macOS. When MTURSO_LIB_PATH is set, it is the only file attempted. A bad path fails immediately with the path and dynamic-loader error rather than silently loading another copy.

    #Usage

    #Typed collection with fetch / fetch_one

    async fn demo(conn : @mturso.Connection) -> Unit raise @mturso.TursoError {
    let users : Array[(Int, String)] = conn.fetch("select id, name from t order by id")
    let one : (Int, String) = conn.fetch_one(
    "select id, name from t where id = ?1",
    params=[1],
    )
    println("\{users.length()} users, first = \{one.0}")
    }

    fetch_one raises TursoError::NoRows when the query returns nothing. Both helpers close the reader for you.

    #Values, NULL and raw bytes

    Value has five variants (Null, Integer, Real, Text, Blob). Row::value(i) returns the Value; Row::value_raw(i) returns the raw bytes (useful for exact BLOB/UTF-8 data). MoonBit String is UTF-16, while the wire format is UTF-8: conversion happens at the boundary, and invalid UTF-8 is decoded lossily (U+FFFD).

    #Transactions

    async fn demo(db : @mturso.Database) -> Unit raise @mturso.TursoError {
    let conn = db.connect()
    defer conn.close()

    let tx = conn.begin_tx() // BEGIN (Deferred)
    ignore(tx.execute("insert into t(name) values ('carol')"))
    tx.commit()

    // Pooled transaction: the connection returns to the pool on commit/rollback.
    let tx2 = db.begin_tx(opts=@mturso.TxOptions::{
    mode: Some(@mturso.TxMode::Concurrent), // BEGIN CONCURRENT (MVCC only)
    read_only: None,
    })
    ignore(tx2.execute("insert into t(name) values ('dave')"))
    tx2.rollback()
    }

    begin_func wraps a whole transaction and commits on success / rolls back on error:

    async fn insert_many(db : @mturso.Database) -> Unit raise @mturso.TursoError {
    ignore(@mturso.begin_func(db, async fn(tx) -> Int raise @mturso.TursoError {
    ignore(tx.execute("insert into t(name) values ('eve')"))
    0
    }))
    }

    #Retries

    retry_tx retries the whole transaction on Busy (WAL write lock) or Conflict (MVCC write-write conflict), with full-jitter backoff. The closure may run more than once — keep it idempotent.

    async fn bump(conn : @mturso.Connection) -> Unit raise @mturso.TursoError {
    ignore(@mturso.retry_tx(
    conn,
    async fn(tx) -> Int raise @mturso.TursoError {
    ignore(tx.execute("update t set v = v + 1 where id = 1"))
    0
    },
    opts=@mturso.RetryOptions::{
    attempts: 10,
    base_delay_ms: 1,
    max_delay_ms: 50,
    budget_ms: None,
    },
    ))
    }

    #The pool

    async fn demo() -> Unit raise @mturso.TursoError {
    let db = @mturso.Database::open("./app.db", max_conns=4)
    defer db.close()

    ignore(db.execute("create table t(x integer)")) // implicit acquire/release
    let rows = db.query("select x from t") // released when `rows.close()`
    defer rows.close()

    let conn = db.connect() // explicit checkout (waits at max_conns)
    defer conn.close() // return to the pool

    let st = db.stats()
    println("max=\{(db.max_conns())} acquires=\{st.acquire_count} waits=\{st.acquire_wait_count}")
    }

    #Offline-first sync

    SyncDatabase keeps a local database synchronized with a Turso Cloud database or a local tursodb --sync-server. SQL still goes through the public Connection; synchronization operations are explicit and serialized.

    async fn sync_demo() -> Unit raise @mturso.TursoError {
    let config = @mturso.SyncConfig::new(
    "./local.db",
    remote_url="http://127.0.0.1:8080",
    // auth_token=Some("..."), // required when the remote enables auth
    client_name=Some("my-app"),
    long_poll_timeout_ms=30_000,
    )
    let db = @mturso.SyncDatabase::open(config) // bootstrap if local is empty
    defer db.close()

    let conn = db.connect()
    defer conn.close()
    ignore(conn.execute("insert into notes(body) values ('offline edit')"))
    db.push()

    let changed = db.pull() // true when remote changes were applied
    let stats = db.stats()
    println("revision=\{stats.revision} received=\{stats.network_received_bytes}")
    db.checkpoint()
    }

    bootstrap_if_empty=false allows opening without a reachable remote. A later push() or pull() reports a structured TursoError::SyncError; committed local changes remain available for retry. close() rejects new operations immediately and finalizes native resources after any in-flight operation ends.

    #Error handling

    async fn demo(conn : @mturso.Connection) -> Unit raise @mturso.TursoError {
    ignore(conn.query("select * from no_such_table")) catch {
    @mturso.TursoError::QueryError(msg) => println("query failed: \{msg}")
    @mturso.TursoError::ConnectionError(msg) => println("connection: \{msg}")
    @mturso.TursoError::Busy(msg) => println("busy: \{msg}")
    @mturso.TursoError::Conflict(msg) => println("conflict: \{msg}")
    @mturso.TursoError::NoRows => println("no rows")
    }
    }

    #API overview

    APIDescription
    Database::open(path, max_conns?)Open a database (file or ":memory:"); max_conns defaults to 4
    Database::connect()async; take a connection from the pool (waits at max_conns)
    Database::query/query_one/executeImplicit acquire → run → release
    Database::begin_tx(opts?)Pooled transaction (DbTx, released on commit/rollback)
    Database::stats()/max_conns()/is_closed()Pool observability
    Database::set_journal_mode(Wal/Mvcc)/set_default_tx_mode()File-level journal mode and default transaction mode
    Database::close()Idempotent; cascades to every connection, then deinits
    SyncConfig::new(path, remote_url~, auth_token?)Sync database path, remote URL/token, bootstrap and long-poll settings
    SyncDatabase::open(config)async; open locally and bootstrap when enabled
    SyncDatabase::connect()async; return the same public Connection used by local databases
    SyncDatabase::push()/pull()/checkpoint()async; serialize sync operations on one database
    SyncDatabase::stats()async; CDC/WAL/network counters plus opaque remote revision
    SyncDatabase::close()Idempotent; reject new work, then finalize after an active operation drains
    Connection::open(path)Convenience connection backed by a private max_conns=1 database
    Connection::query/query_one/executeasync; typed, streaming rows / ExecResult
    Connection::fetch/fetch_oneTyped collection via FromRow
    Row::get/get_by_name/value/value_rawTyped, by-name, raw-value, or exact-byte column access
    Connection::begin_tx(opts?)DbTx
    Connection::close()Return the connection to the pool (idempotent)
    Connection::last_insert_rowid()/sqlite_version()/is_closed()Observability
    DbTx::query/query_one/executeRun inside the transaction
    DbTx::commit()/rollback()Finish (once)
    TursoErrorConnectionError / QueryError / NoRows / Busy / Conflict / SyncError

    #Known limitations

    • No cancellation or timeouts — once submitted, a statement runs to completion (Turso's C ABI has no cross-thread cancel).
    • Platform boundaries — native Linux, macOS arm64, and Windows x64 are supported. Windows ARM64 and WebAssembly browser integration are not.
    • Sync scope — the first sync release supports one remote database and full bootstrap. Partial sync, namespace routing, remote encryption, and multi-database --sync-dir are not exposed yet. Sync databases require an explicit checkpoint().
    • Turso Cloud is opt-in — deterministic CI uses the pinned local tursodb server. A real Cloud smoke test requires a database URL and token supplied by the caller.
    • Preview engine — Turso 0.8.2 is a preview release with many features behind experimental flags; don't treat it as production SQLite.

    #Roadmap

    • #10 — WebAssembly / edge spike: minimal Node-host prototype complete; browser-backed API remains planned. See notes/wasm-spike.md.

    #Development

    moon check --target native # type check moon test --target native # run the test suite (62 tests)

    Do not run a bare moon fmt over the sources: this toolchain respells Int to Int32. If you do, revert with sed -i 's/Int32/Int/g' on the touched files.

    The sync-server development helpers download the pinned Turso CLI into .cache/:

    make download-cli # fetch and verify tursodb 0.8.2 make native-server # build the self-hosted pipeline server make test-server # lifecycle + native pipeline tests make server # start the self-hosted pipeline server make server-tursodb # start the external tursodb sync server make test-tursogo # run Go serverless SDK against the running server

    On Windows, install GNU Make; the Makefile locates Git Bash through git and uses it automatically for these targets.

    Override SYNC_DB, SYNC_ADDR, or TURSODB when needed. make server-wrapper uses the unified cmd/server launcher with external tursodb.

    SyncServerConfig selects the self-hosted native backend by default. The native backend uses the in-process jaredzhou/pony@0.7.0 HTTP server and Turso engine. Both the launcher and the native serving process are the same cmd/server executable; --serve-native is its internal serving mode:

    let server = @server.SyncServer::start(
    @server.SyncServerConfig::new(
    "./server.db",
    backend=@server.SyncServerBackend::Native,
    native_executable=Some("./server"),
    auth=@server.SyncServerAuth::BearerToken(token),
    ),
    )

    From the CLI, the default mode starts the self-hosted Pony server directly in the same process, without a launcher. --tursodb selects external tursodb. The internal --serve-native flag exists only for library-managed SyncServer::start(Native).

    The native backend implements /v2/pipeline, /v3/pipeline, and /v3/cursor, including batches, conditional steps, positional parameters, typed rows, BLOB/base64, and per-step errors. It does not yet persist batons for interactive transactions spanning multiple HTTP requests.

    The native server speaks plain HTTP. It listens on loopback by default. Bearer authentication is enforced by Pony middleware on every sync endpoint:

    Authorization: Bearer <token>

    Set MTURSO_SYNC_BEARER_TOKEN when launching the native server directly. Missing, malformed, and incorrect credentials all receive 401 Unauthorized. The static token is compared in constant time, and tokens are never written to logs or protocol errors. SyncServerAuth::BearerVerifier reserves the same middleware seam for JWT/OIDC verification.

    MoonBit does not currently have an HTTPS server implementation for this path, so the native server deliberately does not accept certificate/private-key configuration. A public deployment must use a TLS-terminating reverse proxy such as Caddy or nginx in front of a loopback-bound native server. The proxy is responsible for the certificate, SAN matching, and preserving the Authorization header. Do not expose the plain HTTP listener directly.

    For a proxy in another container or private host, set MTURSO_SYNC_EXTERNAL_TLS_PROXY=1. A non-loopback native bind is rejected unless that explicit proxy mode and Bearer authentication are both configured:

    $env:MTURSO_SYNC_BEARER_TOKEN = "<long-random-token>" $env:MTURSO_SYNC_EXTERNAL_TLS_PROXY = "1" ./server.exe ./server.db 0.0.0.0:8080

    The external tursodb --tursodb backend remains loopback-only and has no built-in authentication because the pinned CLI does not implement it.

    Real Turso Cloud validation is optional because deterministic CI uses the pinned local server. To smoke-test a Cloud database, provide the URL and token through the environment and construct SyncConfig with them; do not commit or print the token:

    async fn cloud_smoke() -> Unit raise @mturso.TursoError {
    let url = @env.get_env_var("TURSO_SYNC_URL").unwrap_or("")
    let token = @env.get_env_var("TURSO_AUTH_TOKEN").unwrap_or("")
    if url == "" || token == "" {
    fail("set TURSO_SYNC_URL and TURSO_AUTH_TOKEN")
    }
    let db = @mturso.SyncDatabase::open(@mturso.SyncConfig::new(
    "./cloud-smoke.db",
    remote_url=url,
    auth_token=Some(token),
    ))
    defer db.close()
    let conn = db.connect()
    defer conn.close()
    ignore(conn.execute("select 1"))
    }

    The Linux x86_64 and Windows x64 Turso libraries are vendored in libs/ with SHA-256 files. They are loaded at runtime, so neither the repo nor a consumer needs -L, -l, an rpath, or LD_LIBRARY_PATH. On another platform or architecture, fetch the matching library; the script only copies files and does not edit moon.pkg:

    bash scripts/fetch-turso-lib.sh

    Layout:

    PathContents
    mturso.mbtDatabase (pool) and Connection
    value/Value, Column
    traits.mbt / values.mbtvalue traits, Row, QueryExecutor, built-in impls
    rows.mbtstreaming Rows reader + frame parsing
    tx.mbt / retry.mbttransactions and retry helpers
    pool.mbtPoolStats + Database's pool-side impls
    sync.mbtSyncDatabase, operation driver, and MoonBit-owned sync I/O
    server/shared external/native SyncServer facade and lifecycle
    cmd/server/unified external/native sync-server launcher and Pony HTTP adapter
    ffi/extern "c" declarations + thin C stub + vendored Turso headers
    design/Compiler-checked design spec (moon check clean)
    libs/The Turso C shared library
    notes/Research notes on the Turso engine
    examples/Go SDK examples and a C ABI worker skeleton

    #License

    Apache-2.0

    Column

    值类型从子包转出,使用方只写 @mturso.Value / @mturso.Column。

    Value

    值类型从子包转出,使用方只写 @mturso.Value / @mturso.Column。

    Closer

    pub(open) trait Closer {
    fn close(Self) -> Unit
    }

    能关闭的东西。

    Fetching

    pub(open) trait Fetching : QueryExecutor {
    async fn[T : FromRow] fetch(Self, String, params? : Array[&ToValue]) -> Array[T] raise TursoError = _
    async fn[T : FromRow] fetch_one(Self, String, params? : Array[&ToValue]) -> T raise TursoError = _
    }

    能按 FromRow 把 SELECT 结果收成 T 的类型。

    fetch / fetch_one 对 T 泛型,不能放进 QueryExecutor(那会让 trait 不能当对象用,而 &QueryExecutor / &Tx 是 API 的一部分)。所以它们住在 这个单独的非 object-safe trait 里,共享一份默认实现。

    FromRow

    pub(open) trait FromRow {
    fn from_row(Row) -> Self raise TursoError
    }

    能从一行构造出来的类型(配合 fetch / fetch_one)。
    impl FromRow for Bool
    impl FromRow for Byte
    impl FromRow for Char
    impl FromRow for Int
    impl FromRow for Int16
    impl FromRow for Int64
    impl FromRow for UInt
    impl FromRow for UInt16
    impl FromRow for UInt64
    impl FromRow for Float
    impl FromRow for Double
    impl FromRow for String
    impl FromRow for Option[T]
    impl FromRow for Bytes
    impl FromRow for Array[T]
    impl FromRow for Map[String, V]
    impl FromRow for Ref[T]
    impl FromRow for Tuple2[A, B]
    impl FromRow for Tuple3[A, B, C]
    impl FromRow for Tuple4[A, B, C, D]
    impl FromRow for Tuple5[A, B, C, D, E]

    FromValue

    pub(open) trait FromValue {
    fn from_value(
    Value
    ) -> Self raise ValueError
    }

    能从值里解出来的类型。
    impl FromValue for Bool
    impl FromValue for Byte
    impl FromValue for Char
    impl FromValue for Int
    impl FromValue for Int16
    impl FromValue for Int64
    impl FromValue for UInt
    impl FromValue for UInt16
    impl FromValue for UInt64
    impl FromValue for Float
    impl FromValue for Double
    impl FromValue for String
    impl FromValue for Option[T]
    impl FromValue for Bytes

    QueryExecutor

    pub(open) trait QueryExecutor {
    async fn query(Self, String, params? : Array[&ToValue]) -> &Rows raise TursoError
    async fn query_one(Self, String, params? : Array[&ToValue]) -> Row raise TursoError
    async fn execute(Self, String, params? : Array[&ToValue]) -> ExecResult raise TursoError
    }

    能执行 SQL 的东西。

    Rows

    pub(open) trait Rows {
    async fn has_next(Self) -> Bool raise TursoError
    fn get_row(Self) -> Row raise TursoError
    fn columns(Self) -> Array[
    Column
    ]
    fn changes(Self) -> Int64
    fn close(Self) -> Unit
    }

    拉取式行读取器(本版是流式实现:has_next 才去读下一帧)。

    ToValue

    pub(open) trait ToValue {
    fn to_value(Self) ->
    Value

    }

    能作为 SQL 参数的类型。
    impl ToValue for Unit
    impl ToValue for Bool
    impl ToValue for Byte
    impl ToValue for Char
    impl ToValue for Int
    impl ToValue for Int16
    impl ToValue for Int64
    impl ToValue for UInt
    impl ToValue for UInt16
    impl ToValue for UInt64
    impl ToValue for Float
    impl ToValue for Double
    impl ToValue for String
    impl ToValue for Option[T]
    impl ToValue for Bytes
    impl ToValue for Value
    impl ToValue for Ref[T]
    pub(open) trait Tx {
    async fn commit(Self) -> Unit raise TursoError
    async fn rollback(Self) -> Unit raise TursoError
    }

    进行中的事务:只管 commit / rollback,不继承 QueryExecutor。 具体类型(DbTx)同时实现 QueryExecutor 和 Tx,两个能力正交。

    TxBeginner

    pub(open) trait TxBeginner {
    async fn begin_tx(Self, opts? : TxOptions) -> DbTx raise TursoError
    }

    能开事务的东西(本版:Connection;池落地后返回同一个 DbTx)。

    TursoError

    pub suberror TursoError {
    ConnectionError(String)
    QueryError(String)
    NoRows
    Busy(String)
    Conflict(String)
    SyncError(SyncErrorKind, String)
    } derive(
    Debug
    )

    ValueError

    pub(all) suberror ValueError {
    ValueError(String)
    }

    值转换错误(与数据库错误分开:一个是「取出来的东西不是我想要的类型」, 一个是「数据库那边失败了」)。

    Connection

    pub struct Connection {
    // private fields
    }

    Connection::autocommit

    fn Connection::autocommit(self : Connection) -> Bool raise TursoError

    Whether the connection currently has no explicit transaction.

    Connection::begin_tx

    async fn Connection::begin_tx(self : Connection, opts? : TxOptions) -> DbTx raise TursoError

    Connection::close

    fn Connection::close(self : Connection) -> Unit

    关闭连接 = 还回池(幂等;不是销毁)。

    Connection::execute

    async fn Connection::execute(self : Connection, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoError

    让 conn.query(...) / conn.execute(...) 这类 dot 调用成立。

    Connection::fetch

    async fn[T : FromRow] Connection::fetch(self : Connection, sql : String, params? : Array[&ToValue]) -> Array[T] raise TursoError

    Connection::fetch_one

    async fn[T : FromRow] Connection::fetch_one(self : Connection, sql : String, params? : Array[&ToValue]) -> T raise TursoError

    Connection::is_closed

    fn Connection::is_closed(self : Connection) -> Bool

    连接是否已关闭(已还回池也算关闭)。

    Connection::last_insert_rowid

    fn Connection::last_insert_rowid(self : Connection) -> Int64 raise TursoError

    最近一次 INSERT 生成的 rowid。

    Connection::open

    async fn Connection::open(path : String) -> Connection raise TursoError

    只打开一条连接。内部持有 max_conns = 1 的私有 Database;关闭连接时 私有 Database 也一起关闭。

    Connection::query

    async fn Connection::query(self : Connection, sql : String, params? : Array[&ToValue]) -> &Rows raise TursoError

    让 conn.query(...) / conn.execute(...) 这类 dot 调用成立。

    Connection::query_one

    async fn Connection::query_one(self : Connection, sql : String, params? : Array[&ToValue]) -> Row raise TursoError

    让 conn.query(...) / conn.execute(...) 这类 dot 调用成立。

    Connection::sqlite_version

    async fn Connection::sqlite_version(self : Connection) -> String raise TursoError

    引擎自报的 SQLite 兼容版本(兼容性伪装,不是 Turso 自己的版本号)。

    Database

    pub struct Database {
    // private fields
    }

    数据库句柄 = 一个连接池(见 ADR-0001)。

    • idle:空闲连接的裸句柄(复用);
    • busy:借出中的裸句柄;None 是墓碑(已归还,槽位留着让索引稳定);
    • sem:max_conns 个许可,connect() 满了会等。

    Database::begin_tx

    async fn Database::begin_tx(self : Database, opts? : TxOptions) -> DbTx raise TursoError

    Database::close

    fn Database::close(self : Database) -> Unit

    关闭数据库(幂等):级联关掉 idle 和 busy 里的所有连接(join 各自 worker), 再 turso_database_deinit。

    Database::connect

    async fn Database::connect(self : Database) -> Connection raise TursoError

    从池里取一条连接:优先复用 idle;否则新建(受 max_conns 限制,满了等待)。

    Database::default_tx_mode

    fn Database::default_tx_mode(self : Database) -> TxMode

    当前默认事务模式。

    Database::execute

    async fn Database::execute(self : Database, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoError

    Database::is_closed

    fn Database::is_closed(self : Database) -> Bool

    数据库是否已关闭。

    Database::max_conns

    fn Database::max_conns(self : Database) -> Int

    池上限。

    Database::open

    fn Database::open(path : String, max_conns? : Int) -> Database raise TursoError

    打开数据库。max_conns 是池上限(默认 4)。

    Database::query

    async fn Database::query(self : Database, sql : String, params? : Array[&ToValue]) -> &Rows raise TursoError

    Database::query_one

    async fn Database::query_one(self : Database, sql : String, params? : Array[&ToValue]) -> Row raise TursoError

    Database::set_default_tx_mode

    fn Database::set_default_tx_mode(self : Database, mode : TxMode) -> Unit

    覆盖后续 begin_tx(mode=None) 使用的默认事务模式。

    Database::set_journal_mode

    fn Database::set_journal_mode(self : Database, mode : JournalMode) -> Unit raise TursoError

    设置库级 journal mode,并联动默认事务模式:Mvcc → Concurrent, Wal → Deferred。

    Database::stats

    fn Database::stats(self : Database) -> PoolStats

    池统计快照。

    DbTx

    pub struct DbTx {
    // private fields
    }

    具体事务。begin_tx 返回它,所以事务里的调用都是 dot 调用。
    impl Tx for DbTx

    DbTx::commit

    async fn DbTx::commit(self : DbTx) -> Unit raise TursoError

    DbTx::execute

    async fn DbTx::execute(self : DbTx, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoError

    DbTx::query

    async fn DbTx::query(self : DbTx, sql : String, params? : Array[&ToValue]) -> &Rows raise TursoError

    DbTx::query_one

    async fn DbTx::query_one(self : DbTx, sql : String, params? : Array[&ToValue]) -> Row raise TursoError

    DbTx::rollback

    async fn DbTx::rollback(self : DbTx) -> Unit raise TursoError

    ExecResult

    pub struct ExecResult {
    changes : Int64
    }

    execute 的结果。

    ExecResult::affected_rows

    fn ExecResult::affected_rows(self : ExecResult) -> Int

    受影响行数。

    JournalMode

    pub(all) enum JournalMode {
    Wal
    Mvcc
    } derive(Eq,
    Debug
    )

    Turso 支持的 journal mode。它是库/文件级属性,不是单连接属性。

    PoolStats

    pub(all) struct PoolStats {
    acquire_count : Int64
    acquire_wait_count : Int64
    acquire_wait_duration_ms : Int64
    } derive(Eq,
    Debug
    )

    池的观测数据。

    ResultRows

    pub struct ResultRows {
    stream :
    RawFdStream

    columns : Array[
    Column
    ]
    stmt :
    Stmt

    conn :
    Conn

    release : Connection?
    pending : Array[
    Value
    ]?
    pending_raw : Array[Bytes]?
    changes : Int64
    done : Bool
    closed : Bool
    // private fields
    }

    流式行集。
    impl Rows for ResultRows

    ResultRows::changes

    fn ResultRows::changes(self : ResultRows) -> Int64

    让具体类型上的 rows.has_next() 这类 dot 调用也成立(不只是 &Rows)。

    ResultRows::close

    fn ResultRows::close(self : ResultRows) -> Unit

    让具体类型上的 rows.has_next() 这类 dot 调用也成立(不只是 &Rows)。

    ResultRows::columns

    让具体类型上的 rows.has_next() 这类 dot 调用也成立(不只是 &Rows)。

    ResultRows::get_row

    fn ResultRows::get_row(self : ResultRows) -> Row raise TursoError

    让具体类型上的 rows.has_next() 这类 dot 调用也成立(不只是 &Rows)。

    ResultRows::has_next

    async fn ResultRows::has_next(self : ResultRows) -> Bool raise TursoError

    让具体类型上的 rows.has_next() 这类 dot 调用也成立(不只是 &Rows)。

    RetryOptions

    pub(all) struct RetryOptions {
    attempts : Int
    base_delay_ms : Int
    max_delay_ms : Int
    budget_ms : Int?
    } derive(Eq,
    Debug
    )

    重试预算。

    RetryOptions::default

    fn RetryOptions::default() -> RetryOptions

    Row

    一行结果。字段私有,只能通过方法读。

    Row::columns

    该行所属结果集的列描述。

    Row::get

    fn[T : FromValue] Row::get(self : Row, index : Int) -> T raise TursoError

    按下标取值。类型不符时抛 TursoError(FromValue 抛的 ValueError 在这里被 包成数据库错误,镜像 moonpg 的做法)。

    Row::get_by_name

    fn[T : FromValue] Row::get_by_name(self : Row, name : String) -> T raise TursoError

    按列名取值。找不到列时抛 TursoError::QueryError。

    Row::len

    fn Row::len(self : Row) -> Int

    列数。

    Row::value

    fn Row::value(self : Row, index : Int) ->
    Value

    取下标的原始 Value(不抛——想精确区分类型的人用这个)。

    Row::value_raw

    fn Row::value_raw(self : Row, index : Int) -> Bytes

    取下标的原始字节(Text 返回未解码的 UTF-8 字节,Blob 返回其字节; 其它类型返回空)。

    SyncConfig

    pub struct SyncConfig {
    // private fields
    }

    Configuration for a local sync database.

    SyncConfig::new

    fn SyncConfig::new(path : String, remote_url~ : String, auth_token? : String?, client_name? : String?, long_poll_timeout_ms? : Int, bootstrap_if_empty? : Bool, max_conns? : Int) -> SyncConfig

    SyncDatabase

    pub struct SyncDatabase {
    // private fields
    }

    A local database synchronized with a remote Turso database.

    SyncDatabase::checkpoint

    async fn SyncDatabase::checkpoint(self : SyncDatabase) -> Unit raise TursoError

    Checkpoint the local sync database WAL while preserving sync metadata.

    SyncDatabase::close

    fn SyncDatabase::close(self : SyncDatabase) -> Unit

    Reject new work and finalize the sync database once active work completes.

    SyncDatabase::connect

    async fn SyncDatabase::connect(self : SyncDatabase) -> Connection raise TursoError

    Borrow a connection from the sync database.

    SyncDatabase::is_closed

    fn SyncDatabase::is_closed(self : SyncDatabase) -> Bool

    SyncDatabase::open

    async fn SyncDatabase::open(config : SyncConfig) -> SyncDatabase raise TursoError

    Open a sync database and bootstrap it when configured.

    SyncDatabase::pull

    async fn SyncDatabase::pull(self : SyncDatabase) -> Bool raise TursoError

    Fetch remote changes and atomically replay any unpushed local changes.

    SyncDatabase::push

    async fn SyncDatabase::push(self : SyncDatabase) -> Unit raise TursoError

    Push committed local changes to the remote database.

    SyncDatabase::stats

    async fn SyncDatabase::stats(self : SyncDatabase) -> SyncStats raise TursoError

    Return a snapshot of synchronization statistics.

    SyncErrorKind

    pub(all) enum SyncErrorKind {
    Network
    Auth
    Protocol
    RemoteBusy
    RemoteConflict
    Internal
    } derive(
    Debug
    )

    绑定层错误。

    前三档与 moonpg 的 PgError 同构;Busy / Conflict 是可重试信号, 单列出来是为了让重试助手能用模式匹配判断(而不是匹配错误文本):

    • Busy:写锁忙(TURSO_BUSY)。
    • Conflict:MVCC 写写冲突(TURSO_BUSY_SNAPSHOT),事务已被中止。

    撞到哪一个不取决于你用哪个重试助手,而取决于这条连接的运行模式: 没开 MVCC(或开了 MVCC 但用普通 BEGIN)走写者互斥 → Busy; MVCC + BEGIN CONCURRENT 走乐观并发 → 提交时 Conflict。

    SyncStats

    pub(all) struct SyncStats {
    cdc_operations : Int64
    main_wal_size : Int64
    revert_wal_size : Int64
    last_pull_unix_time : Int64
    last_push_unix_time : Int64
    network_sent_bytes : Int64
    network_received_bytes : Int64
    revision : String
    }

    Snapshot of local and network synchronization state.

    Timestamp

    pub(all) struct Timestamp(String) derive(Eq,
    Debug
    )

    ISO 8601 时间戳(UTC),例如 "2026-10-13T00:00:00Z"。

    与 Turso 内建的 timestamp custom type 对齐:那个类型的 base 是 TEXT (ISO 8601),不是整数(见 docs.turso.tech/sql-reference/data-types)。 要数值就走 unix()(秒)/ Timestamp::from_unix()。

    Timestamp::from_unix

    fn Timestamp::from_unix(secs : Int64) -> Timestamp

    从 UNIX 秒(UTC)构造,格式化成 YYYY-MM-DDTHH:MM:SSZ。

    Timestamp::unix

    fn Timestamp::unix(self : Timestamp) -> Int64 raise ValueError

    取 UNIX 秒(UTC)。接受 YYYY-MM-DD[T ]HH:MM:SS,后面可跟 Z 或 .小数; 别的形式(比如带时区偏移 +08:00)抛 ValueError。

    TxMode

    pub(all) enum TxMode {
    Deferred
    Immediate
    Exclusive
    Concurrent
    } derive(Eq,
    Debug
    )

    BEGIN 的模式。前三个与 SQLite 一一对应;Concurrent 是 Turso 的 BEGIN CONCURRENT(只在 MVCC 下有意义;非 MVCC 下会硬报错)。

    TxOptions

    pub(all) struct TxOptions {
    mode : TxMode?
    read_only : Bool?
    } derive(Eq,
    Debug
    )

    begin_tx 的选项。

    TxOptions::default

    fn TxOptions::default() -> TxOptions

    begin_func

    async fn[T, B : TxBeginner] begin_func(beginner : B, f : async (DbTx) -> T raise TursoError) -> T raise TursoError

    开事务 → 跑 f → 成功 commit;出错 rollback(吞掉 rollback 的错)后重新抛出。

    retry_tx

    async fn[T, B : TxBeginner] retry_tx(beginner : B, f : async (DbTx) -> T raise TursoError, opts? : RetryOptions) -> T raise TursoError

    begin_func + 重试。重试单位是整个事务;重试的是「可重试」那一档 (Busy | Conflict)。撞到哪个取决于连接的运行模式: 写者互斥 → Busy;MVCC + BEGIN CONCURRENT → Conflict。

    没有语句级重试助手:读不需要重试,写要能重试就显式走事务。

    sync_error

    fn sync_error(kind : SyncErrorKind, message : String) -> TursoError