-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibsql.zig
More file actions
593 lines (469 loc) · 16.8 KB
/
libsql.zig
File metadata and controls
593 lines (469 loc) · 16.8 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
const std = @import("std");
const builtin = @import("builtin");
const c = @cImport({
@cInclude("libsql.h");
});
/// This simply indicates success or failure.
/// You should use Diagnostics to get the error message and parse that
/// for detailed information.
pub const Error = error{Failed};
pub const Diagnostics = struct {
ptr: ?*c.libsql_error_t = null,
const Self = @This();
pub fn deinit(self: *Self) void {
if (self.ptr != null) {
c.libsql_error_deinit(self.ptr);
}
self.* = undefined;
}
pub fn empty(self: *const Self) bool {
return self.ptr == null;
}
pub fn message(self: *Self) ?[]const u8 {
if (self.ptr == null) {
return null;
}
const cmsg = c.libsql_error_message(self.ptr);
return std.mem.span(cmsg);
}
pub fn format(self: *const Self, writer: *std.Io.Writer) !void {
if (self.ptr == null) {
if (builtin.mode == .Debug) {
try writer.print("(no error, you made an oopsie)", .{});
}
return;
}
const cmsg = c.libsql_error_message(self.ptr);
try writer.print("{s}", .{cmsg});
}
pub fn fromRaw(err: ?*c.libsql_error_t) ?Self {
const ptr = err orelse return null;
return .{ .ptr = ptr };
}
fn storeAndReturn(err: ?*c.libsql_error_t, out: ?*Self) ?Self {
const wrapped = switch (builtin.mode) {
.Debug => fromRaw(err),
else => if (out != null) fromRaw(err) else null,
};
if (out != null and wrapped != null) {
out.?.* = wrapped.?;
}
return wrapped;
}
};
pub const TracingLevel = enum(c.libsql_tracing_level_t) {
@"error" = c.LIBSQL_TRACING_LEVEL_ERROR,
warn = c.LIBSQL_TRACING_LEVEL_WARN,
info = c.LIBSQL_TRACING_LEVEL_INFO,
debug = c.LIBSQL_TRACING_LEVEL_DEBUG,
trace = c.LIBSQL_TRACING_LEVEL_TRACE,
};
pub const Log = struct {
message: [:0]const u8,
target: [:0]const u8,
file: [:0]const u8,
timestamp: u64,
line: usize,
level: TracingLevel,
const Self = @This();
pub fn fromRaw(ptr: c.libsql_log_t) Self {
return .{
.message = std.mem.span(ptr.message),
.target = std.mem.span(ptr.target),
.file = std.mem.span(ptr.file),
.timestamp = ptr.timestamp,
.line = ptr.line,
.level = @enumFromInt(ptr.level),
};
}
};
pub const Logger = fn (Log) void;
pub const SetupOptions = struct {
logger: ?Logger = null,
version: ?[:0]const u8 = null,
};
pub fn LogFunction(logger: Logger) fn (c.libsql_log_t) callconv(.c) void {
const logFn = struct {
fn handleLog(ptr: c.libsql_log_t) callconv(.c) void {
const log = Log.fromRaw(ptr);
logger(log);
}
}.handleLog;
return logFn;
}
/// Make sure to call setup before using any other functionality, especially
/// if you want tracing logs from libsql.
pub fn setup(options: SetupOptions, out_diag: ?*Diagnostics) Error!void {
const config: c.libsql_config_t = .{
.logger = if (options.logger) |logger| &LogFunction(logger) else null,
.version = @ptrCast(options.version),
};
const err = c.libsql_setup(config) orelse return;
_ = Diagnostics.storeAndReturn(@constCast(err), out_diag);
return error.Failed;
}
pub const Database = struct {
ptr: c.libsql_database_t,
pub const Cipher = enum(c.libsql_cypher_t) {
Default = c.LIBSQL_CYPHER_DEFAULT,
AES256 = c.LIBSQL_CYPHER_AES256,
};
pub const InitOptions = struct {
url: ?[:0]const u8 = null,
path: ?[:0]const u8 = null,
auth_token: ?[:0]const u8 = null,
encryption_key: ?[:0]const u8 = null,
sync_interval: u64 = 0,
cypher: Cipher = Cipher.Default,
disable_read_your_writes: bool = false,
webpki: bool = false,
synced: bool = false,
disable_safety_assert: bool = false,
namespace: ?[:0]const u8 = null,
};
const Self = @This();
pub fn init(options: InitOptions, out_diag: ?*Diagnostics) Error!Self {
const ptr = c.libsql_database_init(.{
.url = @ptrCast(options.url),
.path = @ptrCast(options.path),
.auth_token = @ptrCast(options.auth_token),
.encryption_key = @ptrCast(options.encryption_key),
.sync_interval = options.sync_interval,
.disable_read_your_writes = options.disable_read_your_writes,
.webpki = options.webpki,
.synced = options.synced,
.disable_safety_assert = options.disable_safety_assert,
.namespace = @ptrCast(options.namespace),
});
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
pub fn deinit(self: *Self) void {
c.libsql_database_deinit(self.ptr);
self.* = undefined;
}
pub fn open(self: *Self, out_diag: ?*Diagnostics) Error!Connection {
const ptr = c.libsql_database_connect(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
pub const Sync = struct { frame_no: u64, frames_synced: u64 };
pub fn sync(self: *Self, out_diag: ?*Diagnostics) Error!Sync {
const ptr = c.libsql_database_sync(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .frame_no = ptr.frame_no, .frames_synced = ptr.frames_synced };
}
};
pub const Connection = struct {
ptr: c.libsql_connection_t,
const Self = @This();
pub fn deinit(self: *Self) void {
c.libsql_connection_deinit(self.ptr);
self.* = undefined;
}
pub const Info = struct {
last_inserted_rowid: i64,
total_changes: u64,
};
pub fn connectionInfo(self: *Self, out_diag: ?*Diagnostics) Error!Info {
const ptr = c.libsql_connection_info(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .last_inserted_rowid = ptr.last_inserted_rowid, .total_changes = ptr.total_changes };
}
pub fn batch(self: *Self, sql: [:0]const u8, out_diag: ?*Diagnostics) Error!void {
const ptr = c.libsql_connection_batch(self.ptr, sql.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
}
pub fn prepare(self: *Self, sql: [:0]const u8, out_diag: ?*Diagnostics) Error!Statement {
const ptr = c.libsql_connection_prepare(self.ptr, sql.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
pub fn transaction(self: *Self, out_diag: ?*Diagnostics) Error!Transaction {
const ptr = c.libsql_connection_transaction(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
};
pub const Transaction = struct {
ptr: ?c.libsql_transaction_t,
const Self = @This();
/// It's safe to call this on an already committed transaction.
/// The recommended way to use this function is with a defer:
/// ```
/// var tx = try conn.transaction(null);
/// defer tx.rollback();
/// // ...
/// tx.commit();
/// ```
///
/// TODO: The rust code calls unwrap here so need to check if a runtime crash
/// can occur if e.g. a network error occurs with a remote connection. :(
pub fn rollback(self: *Self) void {
if (self.ptr != null) {
c.libsql_transaction_rollback(self.ptr.?);
}
self.* = undefined;
}
/// Calling commit twice, or calling any other methods asides rollback
/// after a call to commit, is illegal behaviour
///
/// TODO: The rust code calls unwrap here so need to check if a runtime crash
/// can occur if e.g. a network error occurs with a remote connection. :(
pub fn commit(self: *Self) void {
c.libsql_transaction_commit(self.ptr.?);
self.ptr = null;
}
pub fn batch(self: *Self, sql: [:0]const u8, out_diag: ?*Diagnostics) Error!void {
const ptr = c.libsql_transaction_batch(self.ptr.?, sql.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
}
pub fn prepare(self: *Self, sql: [:0]const u8, out_diag: ?*Diagnostics) Error!Statement {
const ptr = c.libsql_transaction_prepare(self.ptr.?, sql.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
};
/// Represents a libsql value.
/// Texts and blobs must be copied to keep them around as the memory
/// is owned by libsql and must be freed with a call to deinit.
pub const Value = union(Value.Tag) {
integer: i64,
real: f64,
text: []const u8,
blob: []const u8,
pub const Tag = enum(c_uint) {
integer = c.LIBSQL_TYPE_INTEGER,
real = c.LIBSQL_TYPE_REAL,
text = c.LIBSQL_TYPE_TEXT,
blob = c.LIBSQL_TYPE_BLOB,
};
const Self = @This();
pub fn fromRaw(value: c.libsql_value_t) ?Self {
if (value.type == c.LIBSQL_TYPE_NULL) {
return null;
}
const value_type: Self.Tag = @enumFromInt(value.type);
return switch (value_type) {
.integer => .{ .integer = value.value.integer },
.real => .{ .real = value.value.real },
.text => .{ .text = Slice.fromRaw(value.value.text).?.bytes },
.blob => .{ .blob = Slice.fromRaw(value.value.blob).?.bytes },
};
}
pub fn deinit(self: Self) void {
switch (self) {
.text, .blob => |v| {
var slice: Slice = .{ .bytes = v };
slice.deinit();
},
else => {},
}
}
pub fn toRaw(self: Self) c.libsql_value_t {
return .{
.type = @intFromEnum(self),
.value = switch (self) {
.integer => |v| .{ .integer = v },
.real => |v| .{ .real = v },
.text => |v| .{ .text = (Slice{ .bytes = v }).toRaw() },
.blob => |v| .{ .blob = (Slice{ .bytes = v }).toRaw() },
},
};
}
pub fn rawNull() c.libsql_value_t {
return c.libsql_null();
}
};
pub const Statement = struct {
ptr: c.libsql_statement_t,
pub const ExecuteResult = struct { rows_changed: u64 };
const Self = @This();
pub fn deinit(self: *Self) void {
c.libsql_statement_deinit(self.ptr);
self.* = undefined;
}
pub fn columnCount(self: *Self) usize {
return c.libsql_statement_column_count(self.ptr);
}
pub fn reset(self: *Self) void {
c.libsql_statement_reset(self.ptr);
}
pub fn bindValue(self: *Self, value: ?Value, out_diag: ?*Diagnostics) Error!void {
const or_null = if (value) |v| v.toRaw() else Value.rawNull();
const ptr = c.libsql_statement_bind_value(self.ptr, or_null);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
}
pub fn bindMany(self: *Self, values: []const ?Value, out_diag: ?*Diagnostics) Error!void {
for (values) |value| {
try self.bindValue(value, out_diag);
}
}
pub fn bindNamed(self: *Self, name: [:0]const u8, value: ?Value, out_diag: ?*Diagnostics) Error!void {
const or_null = if (value) |v| v.toRaw() else Value.rawNull();
const ptr = c.libsql_statement_bind_named(self.ptr, &name, or_null);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
}
pub fn execute(self: *Self, out_diag: ?*Diagnostics) Error!ExecuteResult {
const ptr = c.libsql_statement_execute(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .rows_changed = ptr.rows_changed };
}
pub fn query(self: *Self, out_diag: ?*Diagnostics) Error!Rows {
const ptr = c.libsql_statement_query(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return .{ .ptr = ptr };
}
};
pub const Slice = struct {
bytes: []const u8,
const Self = @This();
pub fn fromRaw(ptr: c.libsql_slice_t) ?Self {
return libsqlSliceToZigSlice(ptr);
}
pub fn deinit(self: *Self) void {
c.libsql_slice_deinit(self.toRaw());
self.* = undefined;
}
pub fn toRaw(self: *const Self) c.libsql_slice_t {
return zigSliceToLibsqlSlice(self.bytes);
}
};
pub const Rows = struct {
ptr: c.libsql_rows_t,
const Self = @This();
pub fn deinit(self: *Self) void {
c.libsql_rows_deinit(self.ptr);
self.* = undefined;
}
pub fn columnCount(self: *Self) i32 {
return c.libsql_rows_column_count(self.ptr);
}
pub fn columnName(self: *Self, index: i32) ?Slice {
const ptr = c.libsql_rows_column_name(self.ptr, index);
return libsqlSliceToZigSlice(ptr);
}
pub fn next(self: *Self, out_diag: ?*Diagnostics) Error!?Row {
const ptr = c.libsql_rows_next(self.ptr);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
if (c.libsql_row_empty(ptr)) {
return null;
}
return .{ .ptr = ptr };
}
};
pub const Row = struct {
ptr: c.libsql_row_t,
const Self = @This();
pub fn deinit(self: *Self) void {
c.libsql_row_deinit(self.ptr);
self.* = undefined;
}
pub fn empty(self: *Self) bool {
return c.libsql_row_empty(self.ptr);
}
pub fn length(self: *Self) i32 {
return c.libsql_row_length(self.ptr);
}
pub fn name(self: *Self, index: i32) ?Slice {
const ptr = c.libsql_row_name(self.ptr, index);
return Slice.fromRaw(ptr);
}
pub fn value(self: *Self, index: i32, out_diag: ?*Diagnostics) Error!?Value {
const ptr = c.libsql_row_value(self.ptr, index);
if (Diagnostics.storeAndReturn(ptr.err, out_diag)) |_| {
return error.Failed;
}
return Value.fromRaw(ptr.ok);
}
pub fn values(self: *Self, out_slice: []?Value, out_diag: ?*Diagnostics) Error!void {
std.debug.assert(out_slice.len <= self.length());
for (0..out_slice.len) |index| {
out_slice[index] = try self.value(@intCast(index), out_diag);
}
}
};
test "connect to local file" {
const allocator = std.testing.allocator;
var tmp_dir = std.testing.tmpDir(.{});
defer tmp_dir.cleanup();
const tmp_dir_path = try tmp_dir.dir.realpathAlloc(allocator, ".");
defer allocator.free(tmp_dir_path);
const db_path_c = try std.fs.path.joinZ(allocator, &.{ tmp_dir_path, "libsql.sqlite" });
defer allocator.free(db_path_c);
var diag: Diagnostics = .{};
defer diag.deinit();
errdefer if (!diag.empty()) std.debug.print("error: {f}\n", .{diag});
try setup(.{}, &diag);
var db = try Database.init(.{ .path = db_path_c }, &diag);
defer db.deinit();
var conn = try db.open(&diag);
defer conn.deinit();
var stmt = try conn.prepare("CREATE TABLE test (field BOOL)", &diag);
defer stmt.deinit();
_ = try stmt.execute(&diag);
}
test "connect to memory" {
var diag: Diagnostics = .{};
defer diag.deinit();
errdefer if (!diag.empty()) std.debug.print("error: {f}\n", .{diag});
try setup(.{}, &diag);
var db = try Database.init(.{}, &diag);
defer db.deinit();
var conn = try db.open(&diag);
defer conn.deinit();
var create_stmt = try conn.prepare("CREATE TABLE test (field BOOL)", &diag);
defer create_stmt.deinit();
_ = try create_stmt.execute(&diag);
try conn.batch("INSERT INTO test VALUES (true)", &diag);
var get_stmt = try conn.prepare("SELECT * FROM test LIMIT ?", &diag);
defer get_stmt.deinit();
try get_stmt.bindMany(&.{.{ .integer = 1 }}, &diag);
var rows = try get_stmt.query(&diag);
defer rows.deinit();
var row = try rows.next(&diag) orelse unreachable;
defer row.deinit();
var values: [1]?Value = undefined;
defer for (values) |v| if (v != null) v.?.deinit();
try row.values(&values, &diag);
try std.testing.expect(values[0].?.integer == 1);
}
fn libsqlSliceToZigSlice(slice: c.libsql_slice_t) ?Slice {
if (slice.ptr == null) {
return null;
}
const base: [*:0]const u8 = @ptrCast(slice.ptr);
const wrapped: Slice = .{ .bytes = std.mem.span(base) };
return wrapped;
}
fn zigSliceToLibsqlSlice(slice: []const u8) c.libsql_slice_t {
return .{ .ptr = @ptrCast(slice.ptr), .len = slice.len + 1 };
}