Skip to content

turso.zig

All projects
Database binding · Zig / Turso

An unofficial Zig binding for Turso. Open a local database through the Zig API, or reach the pinned C declarations directly when you need them.

Inside the binding

Read a typed row

The basic example opens an in-memory database, inserts a user and queries two columns. The loop reads the ID as an integer and the name as bytes.

examples/basic.zig · lines 25–37
var rows = try connection.query(
    "SELECT id, name FROM users",
    &.{},
    .{},
);
defer rows.deinit();

while (try rows.next()) |row| {
    std.debug.print("{d}: {s}\n", .{
        try row.get(i64, 0),
        try row.get([]const u8, 1),
    });
}

Keep a value after the query

Text and blobs borrowed from the current row expire on the next operation on that statement. The example makes owned copies before finishing the query.

Borrowed row data expires on the next statement operation. A toOwned copy survives until its owner frees it.
Row and owner lifetimes · turso.zig documentation. Full size
examples/values.zig · lines 47–53
// These copies remain valid after the native row is advanced or released.
var label = try row.toOwned(init.gpa, 3);
defer label.deinit(init.gpa);
var owned_payload = try row.toOwned(init.gpa, 4);
defer owned_payload.deinit(init.gpa);

try rows.finish(null);

The caller releases each copy using the allocator that made it. Read the regression test

Follow the binding to its upstream API

The build translates the pinned SDK Kit header. The raw module exposes those declarations alongside the higher-level Zig interface.

src/raw.zig · lines 7–16
pub const c = @import("turso_c");
pub const version = @import("version.zig");

test "pinned ABI translates" {
    _ = c.turso_database_t;
    _ = c.turso_connection_t;
    _ = c.turso_statement_t;
    _ = c.turso_database_new;
    _ = c.turso_statement_step;
}

Run the examples

Basic query

The basic example creates a table and reads its rows back.

zig build example-basic

Value ownership

The values example prints owned text and a blob after finishing the query.

zig build example-values

Run these from the repository with the matching Zig, Rust and C toolchains.

Who owns the memory?

A connection belongs to its database, and a row borrows from a statement. The binding checks destruction order, but Zig does not enforce move-only types. Copying an owner by value can still break that contract.

Ownership contract