Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
Z

zig-sqlite

> 数据库
Open source

zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.

613 stars0 likes5 views
WebsiteGitHub

About

zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.

zig-sqlite

This package is a thin wrapper around sqlite's C API.

Maintainer note: I'm currently on a break working with Zig and don't intend to work on new features for zig-sqlite. I will keep it updated for the latest Zig versions because that doesn't take too much of my time.

Status

While the core functionality works right now, the API is still subject to changes.

If you use this library, expect to have to make changes when you update the code.

Zig release support

zig-sqlite follows Zig's release structure:

  • master tracks Zig master
  • zig-0.15.1 tracks Zig 0.15.1

The plan is to support releases once Zig 1.0 is released but this can still change.

Table of contents

  • zig-sqlite
  • Status
  • Zig release support
  • Table of contents
  • Requirements
  • Features
  • Installation
  • Usage
    • Demo
    • Initialization
    • Preparing a statement
      • Common use
      • Diagnostics
    • Executing a statement
    • Reuse a statement
    • Reading data in one go
      • Type parameter
      • Statement.one
      • Statement.all and Statement.oneAlloc
    • Iterating
      • Iterator.next
      • Iterator.nextAlloc
    • Bind parameters and resultset rows
    • Custom type binding and reading
    • Note about complex allocations
  • Comptime checks
    • Check the number of bind parameters.
    • Assign types to bind markers and check them.
  • User defined SQL functions
    • Scalar functions
    • Aggregate functions
  • Setting Compile-time Options

Requirements

Zig master is the only required dependency.

For sqlite, you have options depending on your target:

  • On Windows the only supported way at the moment to build zig-sqlite is with the bundled sqlite source code file.
  • On Linux we have two options:
    • use the system and development package for sqlite (libsqlite3-dev for Debian and derivatives, sqlite3-devel for Fedora)
    • use the bundled sqlite source code file.

Features

  • Preparing, executing statements
  • comptime checked bind parameters
  • user defined SQL functions

Installation

Use the following zig fetch command:

zig fetch --save git+https://github.com/vrischmann/zig-sqlite

Now in your build.zig you can access the module like this:

zig
const sqlite = b.dependency("sqlite", .{
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("sqlite", sqlite.module("sqlite"));

If you'd like to use specific features that can only be accessed by setting compile-time options (like FTS5, R*Tree), you can define them here as build options. See Setting Compile-time Options for instructions.

Usage

Demo

See https://github.com/vrischmann/zig-sqlite-demo for a quick demo.

Initialization

Import zig-sqlite like this:

zig
const sqlite = @import("sqlite");

You must create and initialize an instance of sqlite.Db:

zig
var db = try sqlite.Db.init(.{
    .mode = sqlite.Db.Mode{ .File = "/home/vincent/mydata.db" },
    .open_flags = .{
        .write = true,
        .create = true,
    },
    .threading_mode = .MultiThread,
});

The init method takes a InitOptions struct which will be used to configure sqlite.

Only the mode field is mandatory, the other fields have sane default values.

Preparing a statement

Common use

sqlite works exclusively by using prepared statements. The wrapper type is sqlite.Statement. Here is how you get one:

zig
try db.exec("CREATE TABLE IF NOT EXISTS employees(id integer primary key, name text, age integer, salary integer)", .{}, .{});

const query =
    \\SELECT id, name, age, salary FROM employees WHERE age > ? AND age  ? AND age  $id");
    defer stmt.deinit();

    return stmt.all(User, allocator, .{}, .{ .id = 20 });
}

This will do multiple allocations:

  • one for each id field in the User type
  • one for the resulting slice

To facilitate memory handling, consider using an arena allocator like this:

zig
const allocator = std.heap.page_allocator; // Use a suitable allocator

var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();

const users = try fetchUsers(arena.allocator(), db);
_ = users;

This is especially recommended if you use custom types that allocate memory since, as noted above, it's necessary to prevent memory leaks.

Comptime checks

Prepared statements contain comptime metadata which is used to validate every call to exec, one and all at compile time.

Check the number of bind parameters.

The first check makes sure you provide the same number of bind parameters as there are bind markers in the query string.

Take the following code:

zig
var stmt = try db.prepare("SELECT id FROM user WHERE age > ? AND age  ?");
defer stmt.deinit();

const allocator = std.heap.page_allocator; // Use a suitable allocator

const rows = try stmt.all(usize, allocator, .{}, .{
    .age_1 = 10,
    .age_2 = 20,
});
_ = rows;

It fails with this compilation error:

…

Assign types to bind markers and check them.

The second (and more interesting) check makes sure you provide appropriately typed values as bind parameters.

This check is not automatic since with a standard SQL query we have no way to know the types of the bind parameters, to use it you must provide theses types in the SQL query with a custom syntax.

For example, take the same code as above but now we also bind the last parameter:

zig
var stmt = try db.prepare("SELECT id FROM user WHERE age > ? AND age  ?");
defer stmt.deinit();

const allocator = std.heap.page_allocator; // Use a suitable allocator

const rows = try stmt.all(usize, allocator, .{}, .{
    .age_1 = 10,
    .age_2 = 20,
    .weight = false,
});
_ = rows;

This compiles correctly even if the weight field in our user table is of the type INTEGER.

We can make sure the bind parameters have the right type if we rewrite the query like this:

zig
var stmt = try db.prepare("SELECT id FROM user WHERE age > ? AND age  ?{usize}");
defer stmt.deinit();

const allocator = std.heap.page_allocator; // Use a suitable allocator

const rows = try stmt.all(usize, allocator, .{}, .{
    .age_1 = 10,
    .age_2 = 20,
    .weight = false,
});
_ = rows;

Now this fails to compile:

…

The syntax is straightforward: a bind marker ? followed by {, a Zig type name and finally }.

There are a limited number of types allowed currently:

  • all integer types.
  • all arbitrary bit-width integer types.
  • all float types.
  • bool.
  • strings with []const u8 or []u8.
  • strings with sqlite.Text.
  • blobs with sqlite.Blob.

It is probably possible to support arbitrary types if they can be marshaled to an SQLite type. This is something to investigate.

NOTE: this is done at compile time and is quite CPU intensive, therefore it's possible you'll have to play with @setEvalBranchQuota to make it compile.

To finish our example, passing the proper type allows it compile:

zig
var stmt = try db.prepare("SELECT id FROM user WHERE age > ? AND age  ?{usize}");
defer stmt.deinit();

const allocator = std.heap.page_allocator; // Use a suitable allocator

const rows = try stmt.all(usize, allocator, .{}, .{
    .age_1 = 10,
    .age_2 = 20,
    .weight = @as(usize, 200),
});
_ = rows;

User defined SQL functions

sqlite supports user-defined SQL functions which come in two types:

  • scalar functions
  • aggregate functions

In both cases the arguments are sqlite3_values and are converted to Zig values using the following rules:

  • TEXT values can be either sqlite.Text or []const u8
  • BLOB values can be either sqlite.Blob or []const u8
  • INTEGER values can be any Zig integer
  • REAL values can be any Zig float

Scalar functions

You can define a scalar function using db.createScalarFunction:

zig
try db.createScalarFunction(
    "blake3",
    struct {
        fn run(input: []const u8) [std.crypto.hash.Blake3.digest_length]u8 {
            var hash: [std.crypto.hash.Blake3.digest_length]u8 = undefined;
            std.crypto.hash.Blake3.hash(input, &hash, .{});
            return hash;
        }
    }.run,
    .{},
);

const hash = try db.one([std.crypto.hash.Blake3.digest_length]u8, "SELECT blake3('hello')", .{}, .{});

Each input arguments in the function call in the statement is passed on to the registered run function.

Aggregate functions

You can define an aggregate function using db.createAggregateFunction:

…

Each input arguments in the function call in the statement is passed on to the registered step function. The finalize function is called once at the end.

The context (2nd argument of createAggregateFunction) can be whatever you want; both the step and finalize functions must have their first argument of the same type as the context.

Setting Compile-time Options

SQLite compile-time options are added as build options for customizing the SQLite source code.

…

The options are shortened for easier reading. You can check them by running zig build --help in this project. Mostly they follow the rules below.

  • Upper-cases are converted into lower-cases, unless the word is already shortened, like "DQS" for "double-quoted strings"
  • SQLITE_ENABLE_ is trimmed. For example, SQLITE_ENABLE_API_ARMOR translates to api_armor.
  • Otherwise, SQLITE_ is trimmed. For example, SQLITE_ZERO_MALLOC translates to zero_malloc.
  • If the option doesn't receive argument, or receives 0 or 1, it's defined as bool.
    • If the option only accepts 1, it's defined as u1; a int must be used as the argument.
  • "Not recommended", "No-op" and "Deprecated" options are not added as build options.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Csqlitezigzig-package

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库