-
Notifications
You must be signed in to change notification settings - Fork 52
/
sqlite.zig
4061 lines (3453 loc) · 140 KB
/
sqlite.zig
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const builtin = @import("builtin");
const build_options = @import("build_options");
const debug = std.debug;
const heap = std.heap;
const io = std.io;
const mem = std.mem;
const testing = std.testing;
pub const c = @import("c.zig").c;
const versionGreaterThanOrEqualTo = @import("c.zig").versionGreaterThanOrEqualTo;
pub const ParsedQuery = @import("query.zig").ParsedQuery;
const errors = @import("errors.zig");
pub const errorFromResultCode = errors.errorFromResultCode;
pub const Error = errors.Error;
pub const DetailedError = errors.DetailedError;
const getLastDetailedErrorFromDb = errors.getLastDetailedErrorFromDb;
const getDetailedErrorFromResultCode = errors.getDetailedErrorFromResultCode;
const getTestDb = @import("test.zig").getTestDb;
pub const vtab = @import("vtab.zig");
const helpers = @import("helpers.zig");
test {
_ = @import("vtab.zig");
}
const logger = std.log.scoped(.sqlite);
// Returns true if the passed type is a struct.
fn isStruct(comptime T: type) bool {
const type_info = @typeInfo(T);
return type_info == .@"struct";
}
// Returns true if the passed type will coerce to []const u8.
//
// NOTE(vincent): this is straight from the Zig stdlib before it was removed.
fn isZigString(comptime T: type) bool {
return comptime blk: {
// Only pointer types can be strings, no optionals
const info = @typeInfo(T);
if (info != .pointer) break :blk false;
const ptr = &info.pointer;
// Check for CV qualifiers that would prevent coerction to []const u8
if (ptr.is_volatile or ptr.is_allowzero) break :blk false;
// If it's already a slice, simple check.
if (ptr.size == .Slice) {
break :blk ptr.child == u8;
}
// Otherwise check if it's an array type that coerces to slice.
if (ptr.size == .One) {
const child = @typeInfo(ptr.child);
if (child == .array) {
const arr = &child.array;
break :blk arr.child == u8;
}
}
break :blk false;
};
}
/// Text is used to represent a SQLite TEXT value when binding a parameter or reading a column.
pub const Text = struct { data: []const u8 };
/// ZeroBlob is a blob with a fixed length containing only zeroes.
///
/// A ZeroBlob is intended to serve as a placeholder; content can later be written with incremental i/o.
///
/// Here is an example allowing you to write up to 1024 bytes to a blob with incremental i/o.
///
/// try db.exec("INSERT INTO user VALUES(1, ?)", .{}, .{sqlite.ZeroBlob{ .length = 1024 }});
/// const row_id = db.getLastInsertRowID();
///
/// var blob = try db.openBlob(.main, "user", "data", row_id, .{ .write = true });
///
/// var blob_writer = blob.writer();
/// try blob_writer.writeAll("foobar");
///
/// try blob.close();
///
/// Search for "zeroblob" on https://sqlite.org/c3ref/blob_open.html for more details.
pub const ZeroBlob = struct {
length: usize,
};
/// Blob is a wrapper for a sqlite BLOB.
///
/// This type is useful when reading or binding data and for doing incremental i/o.
pub const Blob = struct {
const Self = @This();
pub const OpenFlags = struct {
read: bool = true,
write: bool = false,
};
pub const DatabaseName = union(enum) {
main,
temp,
attached: [:0]const u8,
fn toString(self: @This()) [:0]const u8 {
return switch (self) {
.main => "main",
.temp => "temp",
.attached => |name| name,
};
}
};
// Used when reading or binding data.
data: []const u8,
// Used for incremental i/o.
handle: *c.sqlite3_blob = undefined,
offset: c_int = 0,
size: c_int = 0,
/// close closes the blob.
pub fn close(self: *Self) Error!void {
const result = c.sqlite3_blob_close(self.handle);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
pub const Reader = io.Reader(*Self, errors.Error, read);
/// reader returns a io.Reader.
pub fn reader(self: *Self) Reader {
return .{ .context = self };
}
fn read(self: *Self, buffer: []u8) Error!usize {
if (self.offset >= self.size) {
return 0;
}
const tmp_buffer = blk: {
const remaining: usize = @as(usize, @intCast(self.size)) - @as(usize, @intCast(self.offset));
break :blk if (buffer.len > remaining) buffer[0..remaining] else buffer;
};
const result = c.sqlite3_blob_read(
self.handle,
tmp_buffer.ptr,
@intCast(tmp_buffer.len),
self.offset,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
self.offset += @intCast(tmp_buffer.len);
return tmp_buffer.len;
}
pub const Writer = io.Writer(*Self, Error, write);
/// writer returns a io.Writer.
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
fn write(self: *Self, data: []const u8) Error!usize {
const result = c.sqlite3_blob_write(
self.handle,
data.ptr,
@intCast(data.len),
self.offset,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
self.offset += @intCast(data.len);
return data.len;
}
/// Reset the offset used for reading and writing.
pub fn reset(self: *Self) void {
self.offset = 0;
}
pub const ReopenError = error{
CannotReopenBlob,
};
/// reopen moves this blob to another row of the same table.
///
/// See https://sqlite.org/c3ref/blob_reopen.html.
pub fn reopen(self: *Self, row: i64) ReopenError!void {
const result = c.sqlite3_blob_reopen(self.handle, row);
if (result != c.SQLITE_OK) {
return error.CannotReopenBlob;
}
self.size = c.sqlite3_blob_bytes(self.handle);
self.offset = 0;
}
pub const OpenError = error{
CannotOpenBlob,
};
/// open opens a blob for incremental i/o.
fn open(db: *c.sqlite3, db_name: DatabaseName, table: [:0]const u8, column: [:0]const u8, row: i64, comptime flags: OpenFlags) OpenError!Blob {
comptime if (!flags.read and !flags.write) {
@compileError("must open a blob for either read, write or both");
};
const open_flags: c_int = if (flags.write) 1 else 0;
var blob: Blob = undefined;
const result = c.sqlite3_blob_open(
db,
db_name.toString(),
table,
column,
row,
open_flags,
@ptrCast(&blob.handle),
);
if (result == c.SQLITE_MISUSE) debug.panic("sqlite misuse while opening a blob", .{});
if (result != c.SQLITE_OK) {
return error.CannotOpenBlob;
}
blob.size = c.sqlite3_blob_bytes(blob.handle);
blob.offset = 0;
return blob;
}
};
/// ThreadingMode controls the threading mode used by SQLite.
///
/// See https://sqlite.org/threadsafe.html
pub const ThreadingMode = enum {
/// SingleThread makes SQLite unsafe to use with more than a single thread at once.
SingleThread,
/// MultiThread makes SQLite safe to use with multiple threads at once provided that
/// a single database connection is not by more than a single thread at once.
MultiThread,
/// Serialized makes SQLite safe to use with multiple threads at once with no restriction.
Serialized,
};
/// Diagnostics can be used by the library to give more information in case of failures.
pub const Diagnostics = struct {
message: []const u8 = "",
err: ?DetailedError = null,
pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
if (self.err) |err| {
if (self.message.len > 0) {
_ = try writer.print("{{message: {s}, detailed error: {s}}}", .{ self.message, err });
return;
}
_ = try err.format(fmt, options, writer);
return;
}
if (self.message.len > 0) {
_ = try writer.write(self.message);
return;
}
_ = try writer.write("none");
}
};
pub const InitOptions = struct {
/// mode controls how the database is opened.
///
/// Defaults to a in-memory database.
mode: Db.Mode = .Memory,
/// open_flags controls the flags used when opening a database.
///
/// Defaults to a read only database.
open_flags: Db.OpenFlags = .{},
/// threading_mode controls the threading mode used by SQLite.
///
/// Defaults to Serialized.
threading_mode: ThreadingMode = .Serialized,
/// shared_cache controls whether or not concurrent SQLite
/// connections share the same cache.
///
/// Defaults to false.
shared_cache: bool = false,
/// if provided, diags will be populated in case of failures.
diags: ?*Diagnostics = null,
};
fn isThreadSafe() bool {
return c.sqlite3_threadsafe() > 0;
}
/// Db is a wrapper around a SQLite database, providing high-level functions for executing queries.
/// A Db can be opened with a file database or a in-memory database:
///
/// // File database
/// var db = try sqlite.Db.init(.{ .mode = .{ .File = "/tmp/data.db" } });
///
/// // In memory database
/// var db = try sqlite.Db.init(.{ .mode = .{ .Memory = {} } });
///
pub const Db = struct {
const Self = @This();
db: *c.sqlite3,
/// Mode determines how the database will be opened.
///
/// * File means opening the database at this path with sqlite3_open_v2.
/// * Memory means opening the database in memory.
/// This works by opening the :memory: path with sqlite3_open_v2 with the flag SQLITE_OPEN_MEMORY.
pub const Mode = union(enum) {
File: [:0]const u8,
Memory,
};
/// OpenFlags contains various flags used when opening a SQLite databse.
///
/// These flags partially map to the flags defined in https://sqlite.org/c3ref/open.html
/// * write=false and create=false means SQLITE_OPEN_READONLY
/// * write=true and create=false means SQLITE_OPEN_READWRITE
/// * write=true and create=true means SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE
pub const OpenFlags = struct {
write: bool = false,
create: bool = false,
};
pub const InitError = error{
SQLiteBuildNotThreadSafe,
} || Error;
/// init creates a database with the provided options.
pub fn init(options: InitOptions) InitError!Self {
var dummy_diags = Diagnostics{};
var diags = options.diags orelse &dummy_diags;
// Validate the threading mode
if (options.threading_mode != .SingleThread and !isThreadSafe()) {
return error.SQLiteBuildNotThreadSafe;
}
// Compute the flags
var flags: c_int = c.SQLITE_OPEN_URI;
flags |= @as(c_int, if (options.open_flags.write) c.SQLITE_OPEN_READWRITE else c.SQLITE_OPEN_READONLY);
if (options.open_flags.create) {
flags |= c.SQLITE_OPEN_CREATE;
}
if (options.shared_cache) {
flags |= c.SQLITE_OPEN_SHAREDCACHE;
}
switch (options.threading_mode) {
.MultiThread => flags |= c.SQLITE_OPEN_NOMUTEX,
.Serialized => flags |= c.SQLITE_OPEN_FULLMUTEX,
else => {},
}
switch (options.mode) {
.File => |path| {
var db: ?*c.sqlite3 = undefined;
const result = c.sqlite3_open_v2(path.ptr, &db, flags, null);
if (result != c.SQLITE_OK or db == null) {
if (db) |v| {
diags.err = getLastDetailedErrorFromDb(v);
} else {
diags.err = getDetailedErrorFromResultCode(result);
}
return errors.errorFromResultCode(result);
}
return Self{ .db = db.? };
},
.Memory => {
flags |= c.SQLITE_OPEN_MEMORY;
var db: ?*c.sqlite3 = undefined;
const result = c.sqlite3_open_v2(":memory:", &db, flags, null);
if (result != c.SQLITE_OK or db == null) {
if (db) |v| {
diags.err = getLastDetailedErrorFromDb(v);
} else {
diags.err = getDetailedErrorFromResultCode(result);
}
return errors.errorFromResultCode(result);
}
return Self{ .db = db.? };
},
}
}
/// deinit closes the database.
pub fn deinit(self: *Self) void {
_ = c.sqlite3_close(self.db);
}
// getDetailedError returns the detailed error for the last API call if it failed.
pub fn getDetailedError(self: *Self) DetailedError {
return getLastDetailedErrorFromDb(self.db);
}
fn getPragmaQuery(comptime name: []const u8, comptime arg: ?[]const u8) []const u8 {
if (arg) |a| {
return std.fmt.comptimePrint("PRAGMA {s} = {s}", .{ name, a });
}
return std.fmt.comptimePrint("PRAGMA {s}", .{name});
}
/// getLastInsertRowID returns the last inserted rowid.
pub fn getLastInsertRowID(self: *Self) i64 {
const rowid = c.sqlite3_last_insert_rowid(self.db);
return rowid;
}
/// pragmaAlloc is like `pragma` but can allocate memory.
///
/// Useful when the pragma command returns text, for example:
///
/// const journal_mode = try db.pragma([]const u8, allocator, .{}, "journal_mode", null);
///
pub fn pragmaAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, options: QueryOptions, comptime name: []const u8, comptime arg: ?[]const u8) !?Type {
const query = comptime getPragmaQuery(name, arg);
var stmt = try self.prepare(query);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, .{});
}
/// pragma is a convenience function to use the PRAGMA statement.
///
/// Here is how to set a pragma value:
///
/// _ = try db.pragma(void, .{}, "foreign_keys", "1");
///
/// Here is how to query a pragma value:
///
/// const journal_mode = try db.pragma([128:0]const u8, .{}, "journal_mode", null);
///
/// The pragma name must be known at comptime.
///
/// This cannot allocate memory. If your pragma command returns text you must use an array or call `pragmaAlloc`.
pub fn pragma(self: *Self, comptime Type: type, options: QueryOptions, comptime name: []const u8, comptime arg: ?[]const u8) !?Type {
const query = comptime getPragmaQuery(name, arg);
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, .{});
}
/// exec is a convenience function which prepares a statement and executes it directly.
pub fn exec(self: *Self, comptime query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
try stmt.exec(options, values);
}
/// execDynamic is a convenience function which prepares a statement and executes it directly.
pub fn execDynamic(self: *Self, query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
try stmt.exec(options, values);
}
/// execAlloc is like `exec` but can allocate memory.
pub fn execAlloc(self: *Self, allocator: mem.Allocator, comptime query: []const u8, options: QueryOptions, values: anytype) !void {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
try stmt.execAlloc(allocator, options, values);
}
/// one is a convenience function which prepares a statement and reads a single row from the result set.
pub fn one(self: *Self, comptime Type: type, comptime query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, values);
}
/// oneDynamic is a convenience function which prepares a statement and reads a single row from the result set.
pub fn oneDynamic(self: *Self, comptime Type: type, query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
return try stmt.one(Type, options, values);
}
/// oneAlloc is like `one` but can allocate memory.
pub fn oneAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, comptime query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareWithDiags(query, options);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, values);
}
/// oneDynamicAlloc is like `oneDynamic` but can allocate memory.
pub fn oneDynamicAlloc(self: *Self, comptime Type: type, allocator: mem.Allocator, query: []const u8, options: QueryOptions, values: anytype) !?Type {
var stmt = try self.prepareDynamicWithDiags(query, options);
defer stmt.deinit();
return try stmt.oneAlloc(Type, allocator, options, values);
}
/// prepareWithDiags is like `prepare` but takes an additional options argument.
pub fn prepareWithDiags(self: *Self, comptime query: []const u8, options: QueryOptions) DynamicStatement.PrepareError!blk: {
@setEvalBranchQuota(100000);
break :blk StatementType(.{}, query);
} {
@setEvalBranchQuota(100000);
return StatementType(.{}, query).prepare(self, options, 0);
}
/// prepareDynamicWithDiags is like `prepareDynamic` but takes an additional options argument.
pub fn prepareDynamicWithDiags(self: *Self, query: []const u8, options: QueryOptions) DynamicStatement.PrepareError!DynamicStatement {
return try DynamicStatement.prepare(self, query, options, 0);
}
/// prepare prepares a statement for the `query` provided.
///
/// The query is analysed at comptime to search for bind markers.
/// prepare enforces having as much fields in the `values` tuple as there are bind markers.
///
/// Example usage:
///
/// var stmt = try db.prepare("INSERT INTO foo(id, name) VALUES(?, ?)");
/// defer stmt.deinit();
///
/// The statement returned is only compatible with the number of bind markers in the input query.
/// This is done because we type check the bind parameters when executing the statement later.
///
/// If you want additional error information in case of failures, use `prepareWithDiags`.
pub fn prepare(self: *Self, comptime query: []const u8) DynamicStatement.PrepareError!blk: {
@setEvalBranchQuota(100000);
break :blk StatementType(.{}, query);
} {
@setEvalBranchQuota(100000);
return StatementType(.{}, query).prepare(self, .{}, 0);
}
/// prepareDynamic prepares a dynamic statement for the `query` provided.
///
/// The query will be directly sent to create statement without analysing.
/// That means such statements does not support comptime type-checking.
///
/// Dynamic statement supports host parameter names. See `DynamicStatement`.
pub fn prepareDynamic(self: *Self, query: []const u8) DynamicStatement.PrepareError!DynamicStatement {
return try self.prepareDynamicWithDiags(query, .{});
}
/// rowsAffected returns the number of rows affected by the last statement executed.
pub fn rowsAffected(self: *Self) usize {
return @intCast(c.sqlite3_changes(self.db));
}
/// openBlob opens a blob for incremental i/o.
///
/// Incremental i/o enables writing and reading data using a std.io.Writer and std.io.Reader:
/// * the writer type wraps sqlite3_blob_write, see https://sqlite.org/c3ref/blob_write.html
/// * the reader type wraps sqlite3_blob_read, see https://sqlite.org/c3ref/blob_read.html
///
/// Note that:
/// * the blob must exist before writing; you must use INSERT to create one first (either with data or using a placeholder with ZeroBlob).
/// * the blob is not extensible, if you want to change the blob size you must use an UPDATE statement.
///
/// You can get a std.io.Writer to write data to the blob:
///
/// var blob = try db.openBlob(.main, "mytable", "mycolumn", 1, .{ .write = true });
/// var blob_writer = blob.writer();
///
/// try blob_writer.writeAll(my_data);
///
/// You can get a std.io.Reader to read the blob data:
///
/// var blob = try db.openBlob(.main, "mytable", "mycolumn", 1, .{});
/// var blob_reader = blob.reader();
///
/// const data = try blob_reader.readAlloc(allocator);
///
/// See https://sqlite.org/c3ref/blob_open.html for more details on incremental i/o.
///
pub fn openBlob(self: *Self, db_name: Blob.DatabaseName, table: [:0]const u8, column: [:0]const u8, row: i64, comptime flags: Blob.OpenFlags) Blob.OpenError!Blob {
return Blob.open(self.db, db_name, table, column, row, flags);
}
/// savepoint starts a new named transaction.
///
/// The returned type is a helper useful for managing commits and rollbacks, for example:
///
/// var savepoint = try db.savepoint("foobar");
/// defer savepoint.rollback();
///
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 1, "foo" });
///
/// savepoint.commit();
///
pub fn savepoint(self: *Self, name: []const u8) Savepoint.InitError!Savepoint {
return Savepoint.init(self, name);
}
/// CreateFunctionFlag controls the flags used when creating a custom SQL function.
/// See https://sqlite.org/c3ref/c_deterministic.html.
///
/// The flags SQLITE_UTF16LE, SQLITE_UTF16BE are not supported yet. SQLITE_UTF8 is the default and always on.
///
/// SQLITE_DIRECTONLY is only available on SQLite >= 3.30.0 so we create a different type based on the SQLite version.
///
/// TODO(vincent): allow these flags when we know how to handle UTF16 data.
/// TODO(vincent): can we refactor this somehow to share the common stuff ?
pub const CreateFunctionFlag = if (c.SQLITE_VERSION_NUMBER >= 3030000) struct {
/// Equivalent to SQLITE_DETERMINISTIC
deterministic: bool = true,
/// Equivalent to SQLITE_DIRECTONLY
direct_only: bool = true,
fn toCFlags(self: *const @This()) c_int {
var flags: c_int = c.SQLITE_UTF8;
if (self.deterministic) {
flags |= c.SQLITE_DETERMINISTIC;
}
if (self.direct_only) {
flags |= c.SQLITE_DIRECTONLY;
}
return flags;
}
} else struct {
/// Equivalent to SQLITE_DETERMINISTIC
deterministic: bool = true,
fn toCFlags(self: *const @This()) c_int {
var flags: c_int = c.SQLITE_UTF8;
if (self.deterministic) {
flags |= c.SQLITE_DETERMINISTIC;
}
return flags;
}
};
/// Creates an aggregate SQLite function with the given name.
///
/// `step_func` and `finalize_func` must be two functions. The first argument of both functions _must_ be of the type FunctionContext.
///
/// When the SQLite function is called in a statement, `step_func` will be called for each row with the input arguments.
/// Each SQLite argument is converted to a Zig value according to 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
///
/// The final result of the SQL function call will be what `finalize_func` returns.
pub fn createAggregateFunction(self: *Self, comptime name: [:0]const u8, user_ctx: anytype, comptime step_func: anytype, comptime finalize_func: anytype, comptime create_flags: CreateFunctionFlag) Error!void {
// Validate the functions
const step_fn_info = switch (@typeInfo(@TypeOf(step_func))) {
.@"fn" => |fn_info| fn_info,
else => @compileError("cannot use func, expecting a function"),
};
if (step_fn_info.is_generic) @compileError("step function can't be generic");
if (step_fn_info.is_var_args) @compileError("step function can't be variadic");
const finalize_fn_info = switch (@typeInfo(@TypeOf(finalize_func))) {
.@"fn" => |fn_info| fn_info,
else => @compileError("cannot use func, expecting a function"),
};
if (finalize_fn_info.params.len != 1) @compileError("finalize function must take exactly one argument");
if (finalize_fn_info.is_generic) @compileError("finalize function can't be generic");
if (finalize_fn_info.is_var_args) @compileError("finalize function can't be variadic");
if (step_fn_info.params[0].type.? != finalize_fn_info.params[0].type.?) {
@compileError("both step and finalize functions must have the same first argument and it must be a FunctionContext");
}
if (step_fn_info.params[0].type.? != FunctionContext) {
@compileError("both step and finalize functions must have a first argument of type FunctionContext");
}
// subtract the context argument
const real_args_len = step_fn_info.params.len - 1;
//
const flags = create_flags.toCFlags();
const result = c.sqlite3_create_function_v2(
self.db,
name,
real_args_len,
flags,
user_ctx,
null, // xFunc
struct {
fn xStep(ctx: ?*c.sqlite3_context, argc: c_int, argv: [*c]?*c.sqlite3_value) callconv(.C) void {
debug.assert(argc == real_args_len);
const sqlite_args = argv[0..real_args_len];
var args: std.meta.ArgsTuple(@TypeOf(step_func)) = undefined;
// Pass the function context
args[0] = FunctionContext{ .ctx = ctx };
comptime var i: usize = 0;
inline while (i < real_args_len) : (i += 1) {
// Remember the firt argument is always the function context
const arg = step_fn_info.params[i + 1];
const arg_ptr = &args[i + 1];
const ArgType = arg.type.?;
helpers.setTypeFromValue(ArgType, arg_ptr, sqlite_args[i].?);
}
@call(.auto, step_func, args);
}
}.xStep,
struct {
fn xFinal(ctx: ?*c.sqlite3_context) callconv(.C) void {
var args: std.meta.ArgsTuple(@TypeOf(finalize_func)) = undefined;
// Pass the function context
args[0] = FunctionContext{ .ctx = ctx };
const result = @call(.auto, finalize_func, args);
helpers.setResult(ctx, result);
}
}.xFinal,
null,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
/// Creates a scalar SQLite function with the given name.
///
/// When the SQLite function is called in a statement, `func` will be called with the input arguments.
/// Each SQLite argument is converted to a Zig value according to 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
///
/// The return type of the function is converted to a SQLite value according to the same rules but reversed.
///
pub fn createScalarFunction(self: *Self, func_name: [:0]const u8, comptime func: anytype, comptime create_flags: CreateFunctionFlag) Error!void {
const Type = @TypeOf(func);
const fn_info = switch (@typeInfo(Type)) {
.@"fn" => |fn_info| fn_info,
else => @compileError("expecting a function"),
};
if (fn_info.is_generic) @compileError("function can't be generic");
if (fn_info.is_var_args) @compileError("function can't be variadic");
const ArgTuple = std.meta.ArgsTuple(Type);
//
const flags = create_flags.toCFlags();
const result = c.sqlite3_create_function_v2(
self.db,
func_name,
fn_info.params.len,
flags,
null,
struct {
fn xFunc(ctx: ?*c.sqlite3_context, argc: c_int, argv: [*c]?*c.sqlite3_value) callconv(.C) void {
debug.assert(argc == fn_info.params.len);
const sqlite_args = argv[0..fn_info.params.len];
var fn_args: ArgTuple = undefined;
inline for (fn_info.params, 0..) |arg, i| {
const ArgType = arg.type.?;
helpers.setTypeFromValue(ArgType, &fn_args[i], sqlite_args[i].?);
}
const result = @call(.auto, func, fn_args);
helpers.setResult(ctx, result);
}
}.xFunc,
null,
null,
null,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
/// This is a convenience function to run statements that do not need
/// bindings to values, but have multiple commands inside.
///
/// Exmaple: 'create table a(); create table b();'
pub fn execMulti(self: *Self, query: []const u8, options: QueryOptions) !void {
var new_options = options;
var sql_tail_ptr: ?[*:0]const u8 = null;
new_options.sql_tail_ptr = &sql_tail_ptr;
while (true) {
// continuously prepare and execute (dynamically as there's no
// values to bind in this case)
var stmt: DynamicStatement = undefined;
if (sql_tail_ptr != null) {
const new_query = std.mem.span(sql_tail_ptr.?);
if (new_query.len == 0) break;
stmt = self.prepareDynamicWithDiags(new_query, new_options) catch |err| switch (err) {
error.EmptyQuery => break,
else => return err,
};
} else {
stmt = self.prepareDynamicWithDiags(query, new_options) catch |err| switch (err) {
error.EmptyQuery => break,
else => return err,
};
}
defer stmt.deinit();
try stmt.exec(new_options, .{});
}
}
pub fn createVirtualTable(
self: *Self,
comptime name: [:0]const u8,
module_context: *vtab.ModuleContext,
comptime Table: type,
) !void {
const VirtualTableType = vtab.VirtualTable(name, Table);
const result = c.sqlite3_create_module_v2(
self.db,
name,
&VirtualTableType.module,
module_context,
null,
);
if (result != c.SQLITE_OK) {
return errors.errorFromResultCode(result);
}
}
};
/// FunctionContext is the context passed as first parameter in the `step` and `finalize` functions used with `createAggregateFunction`.
/// It provides two functions:
/// * userContext to retrieve the user provided context
/// * aggregateContext to create or retrieve the aggregate context
///
/// Both functions take a type as parameter and take care of casting so the caller doesn't have to do it.
pub const FunctionContext = struct {
ctx: ?*c.sqlite3_context,
pub fn userContext(self: FunctionContext, comptime Type: type) ?Type {
const Types = splitPtrTypes(Type);
_ = Types;
if (c.sqlite3_user_data(self.ctx)) |value| {
return @ptrCast(@alignCast(value));
}
return null;
}
pub fn aggregateContext(self: FunctionContext, comptime Type: type) ?Type {
const Types = splitPtrTypes(Type);
if (c.sqlite3_aggregate_context(self.ctx, @sizeOf(Types.ValueType))) |value| {
return @ptrCast(@alignCast(value));
}
return null;
}
const SplitPtrTypes = struct {
ValueType: type,
PointerType: type,
};
fn splitPtrTypes(comptime Type: type) SplitPtrTypes {
switch (@typeInfo(Type)) {
.pointer => |ptr_info| switch (ptr_info.size) {
.One => return SplitPtrTypes{
.ValueType = ptr_info.child,
.PointerType = Type,
},
else => @compileError("cannot use type " ++ @typeName(Type) ++ ", must be a single-item pointer"),
},
.void => return SplitPtrTypes{
.ValueType = void,
.PointerType = undefined,
},
else => @compileError("cannot use type " ++ @typeName(Type) ++ ", must be a single-item pointer"),
}
}
};
/// Savepoint is a helper type for managing savepoints.
///
/// A savepoint creates a transaction like BEGIN/COMMIT but they're named and can be nested.
/// See https://sqlite.org/lang_savepoint.html.
///
/// You can create a savepoint like this:
///
/// var savepoint = try db.savepoint("foobar");
/// defer savepoint.rollback();
///
/// ...
///
/// Savepoint.commit();
///
/// This is equivalent to BEGIN/COMMIT/ROLLBACK.
///
/// Savepoints are more useful for _nesting_ transactions, for example:
///
/// var savepoint = try db.savepoint("outer");
/// defer savepoint.rollback();
///
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 1, "foo" });
///
/// {
/// var savepoint2 = try db.savepoint("inner");
/// defer savepoint2.rollback();
///
/// var i: usize = 0;
/// while (i < 30) : (i += 1) {
/// try db.exec("INSERT INTO foo(id, name) VALUES(?, ?)", .{ 2, "bar" });
/// }
///
/// savepoint2.commit();
/// }
///
/// try db.exec("UPDATE bar SET processed = ? WHERE id = ?", .{ true, 20 });
///
/// savepoint.commit();
///
/// In this example if any query in the inner transaction fail, all previously executed queries are discarded but the outer transaction is untouched.
///
pub const Savepoint = struct {
const Self = @This();
db: *Db,
committed: bool,
commit_stmt: DynamicStatement,
rollback_stmt: DynamicStatement,
pub const InitError = error{
SavepointNameTooShort,
SavepointNameTooLong,
SavepointNameInvalid,
// From execDynamic
ExecReturnedData,
// From DynamiStatement
EmptyQuery,
} || std.fmt.AllocPrintError || Error;
fn init(db: *Db, name: []const u8) InitError!Self {
if (name.len < 1) return error.SavepointNameTooShort;
if (name.len > 20) return error.SavepointNameTooLong;
if (!std.ascii.isAlphabetic(name[0])) return error.SavepointNameInvalid;
for (name) |b| {
if (b != '_' and !std.ascii.isAlphanumeric(b)) {
return error.SavepointNameInvalid;
}
}
var buffer: [256]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const commit_query = try std.fmt.allocPrint(allocator, "RELEASE SAVEPOINT {s}", .{name});
const rollback_query = try std.fmt.allocPrint(allocator, "ROLLBACK TRANSACTION TO SAVEPOINT {s}", .{name});
var res = Self{
.db = db,
.committed = false,
.commit_stmt = try db.prepareDynamic(commit_query),
.rollback_stmt = try db.prepareDynamic(rollback_query),
};
try res.db.execDynamic(
try std.fmt.allocPrint(allocator, "SAVEPOINT {s}", .{name}),
.{},