1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
# zig-sqlite
This package is a thin wrapper around [sqlite](https://sqlite.org/index.html)'s C API.
## Requirements
* [Zig master](https://ziglang.org/download/)
* Linux
* the system and development package for sqlite
* `libsqlite3-dev` for Debian and derivatives
* `sqlite3-devel` for Fedora
## Features
* Preparing, executing statements
* comptime checked bind parameters
## Installation
Since there's no package manager for Zig yet, the recommended way is to use a git submodule:
```bash
$ git submodule add https://git.sr.ht/~vrischmann/zig-sqlite src/sqlite
```
Then add the following to your `build.zig` target(s):
```zig
exe.linkLibC();
exe.linkSystemLibrary("sqlite3");
exe.addPackage(.{ .name = "sqlite", .path = "src/sqlite/sqlite.zig" });
```
Now you should be able to import sqlite like this:
```zig
const sqlite = @import("sqlite");
```
## Usage
### Initialization
You must create and initialize an instance of `sqlite.Db`:
```zig
var db: sqlite.Db = undefined;
try db.init(allocator, .{ .mode = sqlite.Db.Mode{ .File = "/home/vincent/mydata.db" } });
```
The `init` method takes an allocator and an optional tuple which will be used to configure sqlite.
Right now the only member used in that tuple is `mode` which defines if the sqlite database is in memory or uses a file.
### Preparing a statement
sqlite works exclusively by using prepared statements. The wrapper type is `sqlite.Statement`. Here is how you get one:
```zig
const query =
\\SELECT id, name, age, salary FROM employees WHERE age > ? AND age < ?
;
var stmt = try db.prepare(query);
defer stmt.deinit();
```
The `Db.prepare` method takes a `comptime` query string.
### Executing a statement
For queries which do not return data (`INSERT`, `UPDATE`) you can use the `exec` method:
```zig
const query =
\\UPDATE foo SET salary = ? WHERE id = ?
;
var stmt = try db.prepare(query);
defer stmt.deinit();
try stmt.exec({
.salary = 20000,
.id = 40,
});
```
See the section "Bind parameters and resultset rows" for more information on the types mapping rules.
### Reading data
For queries which do return data you can use the `all` method:
```zig
const query =
\\SELECT id, name, age, salary FROM employees WHERE age > ? AND age < ?
;
var stmt = try db.prepare(query);
defer stmt.deinit();
const rows = try stmt.all(
struct {
id: usize,
name: []const u8,
age: u16,
salary: u32,
},
.{ .allocator = allocator },
.{ .age1 = 20, .age2 = 40 },
);
for (rows) |row| {
std.log.debug("id: {} ; name: {}; age: {}; salary: {}", .{ row.id, row.name, row.age, row.salary });
}
```
The `all` method takes a type and an optional tuple.
The type represents a "row", it can be:
* a struct where each field maps to the corresponding column in the resultset (so field 0 must map to field 1 and so on).
* a single type, in that case the resultset must only return one column.
Not all types are allowed, see the section "Bind parameters and resultset rows" for more information on the types mapping rules.
### Bind parameters and resultset rows
Since sqlite doesn't have many [types](https://www.sqlite.org/datatype3.html) only a small number of Zig types are allowed in binding parameters and in resultset mapping types.
Here are the rules for bind parameters:
* any Zig `Int` or `ComptimeInt` is tread as a `INTEGER`.
* any Zig `Float` or `ComptimeFloat` is treated as a `REAL`.
* `[]const u8`, `[]u8` or any array of `u8` is treated as a `TEXT`.
* The custom `sqlite.Blob` type is treated as a `BLOB`.
* The custom `sqlite.Text` type is treated as a `TEXT`.
Here are the rules for resultset rows:
* `INTEGER` can be read into any Zig `Int` provided the data fits.
* `REAL` can be read into any Zig `Float` provided the data fits.
* `TEXT` can be read into a `[]const u8` or `[]u8`.
* `TEXT` can be read into any array of `u8` provided the data fits.
* `BLOB` follows the same rules as `TEXT`.
Note that arrays must have a sentinel because we need a way to communicate where the data actually stops in the array, so for example use `[200:0]u8` for a `TEXT` field.
## 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 < ? AND weight > ?");
defer stmt.deinit();
const rows = try stmt.all(usize, .{ .allocator = allocator }, .{
.age_1 = 10,
.age_2 = 20,
});
_ = rows;
```
It fails with this compilation error:
```
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:465:17: error: number of bind markers not equal to number of fields
@compileError("number of bind markers not equal to number of fields");
^
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:543:22: note: called from here
self.bind(values);
^
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:619:41: note: called from here
var iter = try self.iterator(Type, values);
^
./src/main.zig:16:30: note: called from here
const rows = try stmt.all(usize, .{ .allocator = allocator }, .{
^
./src/main.zig:5:29: note: called from here
pub fn main() anyerror!void {
```
### 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 < ? AND weight > ?");
defer stmt.deinit();
const rows = try stmt.all(usize, .{ .allocator = 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 < ? AND weight > ?{usize}");
defer stmt.deinit();
const rows = try stmt.all(usize, .{ .allocator = allocator }, .{
.age_1 = 10,
.age_2 = 20,
.weight = false,
});
_ = rows;
```
Now this fails to compile:
```
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:485:25: error: value type bool is not the bind marker type usize
@compileError("value type " ++ @typeName(struct_field.field_type) ++ " is not the bind marker type " ++ @typeName(typ));
^
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:557:22: note: called from here
self.bind(values);
^
/home/vincent/dev/perso/libs/zig-sqlite/sqlite.zig:633:41: note: called from here
var iter = try self.iterator(Type, values);
^
./src/main.zig:16:30: note: called from here
const rows = try stmt.all(usize, .{ .allocator = allocator }, .{
^
./src/main.zig:5:29: note: called from here
pub fn main() anyerror!void {
```
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](https://ziglang.org/documentation/master/#Primitive-Types) types.
* all [arbitrary bit-width integer](https://ziglang.org/documentation/master/#Primitive-Types) types.
* all [float](https://ziglang.org/documentation/master/#Primitive-Types) types.
* bool.
* strings with `[]const u8` or `[]u8`.
* strings with `sqlite.Text`.
* blobs with `sqlite.Blob`.
It's probably possible to support arbitrary types if they can be marshaled to a 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](https://ziglang.org/documentation/master/#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 < ? AND weight > ?{usize}");
defer stmt.deinit();
const rows = try stmt.all(usize, .{ .allocator = allocator }, .{
.age_1 = 10,
.age_2 = 20,
.weight = @as(usize, 200),
});
_ = rows;
```
|