zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.
zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.
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.
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-sqlite follows Zig's release structure:
The plan is to support releases once Zig 1.0 is released but this can still change.
Zig master is the only required dependency.
For sqlite, you have options depending on your target:
zig-sqlite is with the bundled sqlite source code file.libsqlite3-dev for Debian and derivatives, sqlite3-devel for Fedora)Use the following zig fetch command:
zig fetch --save git+https://github.com/vrischmann/zig-sqliteNow in your build.zig you can access the module like this:
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.
See https://github.com/vrischmann/zig-sqlite-demo for a quick demo.
Import zig-sqlite like this:
const sqlite = @import("sqlite");You must create and initialize an instance of sqlite.Db:
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.
sqlite works exclusively by using prepared statements. The wrapper type is sqlite.Statement. Here is how you get one:
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:
User typeTo facilitate memory handling, consider using an arena allocator like this:
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.
Prepared statements contain comptime metadata which is used to validate every call to exec, one and all at compile time.
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:
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:
…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:
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:
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:
[]const u8 or []u8.sqlite.Text.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:
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;sqlite supports user-defined SQL functions which come in two types:
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 u8BLOB values can be either sqlite.Blob or []const u8INTEGER values can be any Zig integerREAL values can be any Zig floatYou can define a scalar function using db.createScalarFunction:
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.
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.
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.
SQLITE_ENABLE_ is trimmed. For example, SQLITE_ENABLE_API_ARMOR translates to api_armor.SQLITE_ is trimmed. For example, SQLITE_ZERO_MALLOC translates to zero_malloc.bool.1, it's defined as u1; a int must be used as the argument.No open issues yet, or sync has not completed.