MoonBit bindings for Turso Database, layered on the official C ABI (turso.h).
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}")
}
}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}")
}| Platform / target | Status | Notes |
|---|---|---|
| Linux x86_64 | ✅ tested | CI runs the full suite plus local sync-server acceptance against pinned tursodb 0.8.2 |
| Linux aarch64 | ✅ tested | CI runs the suite on ubuntu-24.04-arm |
| macOS arm64 | ✅ tested | CI runs the suite on macos-latest |
| Windows x64 | ✅ tested | MSVC 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 | 🧪 spike | MoonBit 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 |
moon add jaredzhou/mturso@0.1.0import {
"jaredzhou/mturso@0.1.0",
}import {
"jaredzhou/mturso",
"moonbitlang/core/async",
}
options(
"allow-experimental-packages": [ "moonbitlang/core/async" ],
)| Platform | File |
|---|---|
| Linux x86_64 / aarch64 | libturso_sync_sdk_kit.so |
| macOS arm64 | libturso_sync_sdk_kit.dylib |
| Windows x64 | turso_sync_sdk_kit.dll |
bash scripts/fetch-turso-lib.shmkdir -p dist/libs
cp /path/to/mturso/libs/libturso_sync_sdk_kit.so dist/libs/
./dist/your-appMTURSO_LIB_PATH=/opt/mturso/libturso_sync_sdk_kit.so ./your-appasync 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}")
}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()
}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
}))
}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,
},
))
}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}")
}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()
}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 | Description |
|---|---|
| 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/execute | Implicit 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/execute | async; typed, streaming rows / ExecResult |
| Connection::fetch/fetch_one | Typed collection via FromRow |
| Row::get/get_by_name/value/value_raw | Typed, 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/execute | Run inside the transaction |
| DbTx::commit()/rollback() | Finish (once) |
| TursoError | ConnectionError / QueryError / NoRows / Busy / Conflict / SyncError |
moon check --target native # type check
moon test --target native # run the test suite (62 tests)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 serverlet server = @server.SyncServer::start(
@server.SyncServerConfig::new(
"./server.db",
backend=@server.SyncServerBackend::Native,
native_executable=Some("./server"),
auth=@server.SyncServerAuth::BearerToken(token),
),
)Authorization: Bearer <token>$env:MTURSO_SYNC_BEARER_TOKEN = "<long-random-token>"
$env:MTURSO_SYNC_EXTERNAL_TLS_PROXY = "1"
./server.exe ./server.db 0.0.0.0:8080async 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"))
}bash scripts/fetch-turso-lib.sh| Path | Contents |
|---|---|
| mturso.mbt | Database (pool) and Connection |
| value/ | Value, Column |
| traits.mbt / values.mbt | value traits, Row, QueryExecutor, built-in impls |
| rows.mbt | streaming Rows reader + frame parsing |
| tx.mbt / retry.mbt | transactions and retry helpers |
| pool.mbt | PoolStats + Database's pool-side impls |
| sync.mbt | SyncDatabase, 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 |
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 = _
}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
}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
}pub(open) trait Tx {
async fn commit(Self) -> Unit raise TursoError
async fn rollback(Self) -> Unit raise TursoError
}pub suberror TursoError {
ConnectionError(String)
QueryError(String)
NoRows
Busy(String)
Conflict(String)
SyncError(SyncErrorKind, String)
} derive(Debug)pub(all) suberror ValueError {
ValueError(String)
}pub struct Connection {
// private fields
}impl Fetching for Connectionimpl QueryExecutor for Connectionasync fn execute(self : Connection, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorasync fn query(self : Connection, sql : String, params? : Array[&ToValue]) -> &Rows raise TursoErrorasync fn query_one(self : Connection, sql : String, params? : Array[&ToValue]) -> Row raise TursoErrorimpl TxBeginner for Connectionasync fn Connection::execute(self : Connection, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorasync fn[T : FromRow] Connection::fetch(self : Connection, sql : String, params? : Array[&ToValue]) -> Array[T] raise TursoErrorasync fn[T : FromRow] Connection::fetch_one(self : Connection, sql : String, params? : Array[&ToValue]) -> T raise TursoErrorasync fn Connection::query(self : Connection, sql : String, params? : Array[&ToValue]) -> &Rows raise TursoErrorasync fn Connection::query_one(self : Connection, sql : String, params? : Array[&ToValue]) -> Row raise TursoErrorpub struct Database {
// private fields
}impl QueryExecutor for Databaseasync fn execute(self : Database, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorimpl TxBeginner for Databaseasync fn Database::execute(self : Database, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorpub struct DbTx {
// private fields
}impl QueryExecutor for DbTxasync fn execute(self : DbTx, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorasync fn DbTx::execute(self : DbTx, sql : String, params? : Array[&ToValue]) -> ExecResult raise TursoErrorpub struct ExecResult {
changes : Int64
}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 ResultRowspub struct SyncConfig {
// private fields
}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) -> SyncConfigpub struct SyncDatabase {
// private fields
}pub(all) enum SyncErrorKind {
Network
Auth
Protocol
RemoteBusy
RemoteConflict
Internal
} derive(Debug)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
}async fn[T, B : TxBeginner] begin_func(beginner : B, f : async (DbTx) -> T raise TursoError) -> T raise TursoErrorasync fn[T, B : TxBeginner] retry_tx(beginner : B, f : async (DbTx) -> T raise TursoError, opts? : RetryOptions) -> T raise TursoErrorInstall
Download zipMoonBit bindings for Turso Database, layered on the official C ABI (turso.h).