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
|
const std = @import("std");
const sqlite = @import("sqlite");
const assert = std.debug.assert;
const Alignment = std.mem.Alignment;
const Allocator = std.mem.Allocator;
const Writer = std.Io.Writer;
pub fn Database(comptime T: type) type {
const tables = switch (@typeInfo(T)) {
.@"struct" => |s| s.fields,
else => @compileError("Database schema must be of type `struct`"),
};
// NOTE: `std.math.log2_int_ceil(@TypeOf(tables.len), tables.len)` panics
// if `tables.len` is zero. The below properly handles the case of
// a (useless) schema that does not define any tables.
const TagIntTables = @Int(.unsigned, @bitSizeOf(@TypeOf(tables.len)) - @clz(tables.len));
var table_names : [tables.len][]const u8 = undefined;
var table_types : [tables.len]type = undefined;
var table_values: [tables.len]TagIntTables = undefined;
var statements : [tables.len][:0]const u8 = undefined;
inline for (&table_names, &table_types, &table_values, &statements, tables, 0..) |*table_name, *table_type, *table_value, *statement, table, table_index| {
const columns = switch (@typeInfo(table.type)) {
.@"struct" => |s| s.fields,
else => @compileError("Table `" ++ table.name ++ "` must be of type `struct`"),
};
// NOTE: A table must have at least one column; see
// https://sqlite.org/syntax/create-table-stmt.html.
if (columns.len == 0) @compileError("Table `" ++ table.name ++ "` must have at least one column");
const TagIntColumns = @Int(.unsigned, std.math.log2_int_ceil(@TypeOf(columns.len), columns.len));
var column_names : [columns.len][]const u8 = undefined;
var column_types : [columns.len]type = undefined;
var column_values: [columns.len]TagIntColumns = undefined;
var create_table : [:0]const u8 = "CREATE TABLE IF NOT EXISTS " ++ table.name ++ " (";
inline for (&column_names, &column_types, &column_values, columns, 0..) |*column_name, *column_type, *column_value, column, column_index| {
if (!isTypename(column.type)) @compileError("Column `" ++ column.name ++ "` must be of type `Typename`");
const typename = std.builtin.Type.StructField.defaultValue(column) orelse @compileError("Column `" ++ column.name ++ "` is missing value");
const separator = if (column_index == 0) "" else ", ";
const Context = struct {
typename: @TypeOf(typename),
pub fn format(self: @This(), writer: *Writer) Writer.Error!void {
try self.typename.serialise(writer);
}
};
const format = std.fmt.alt(Context{ .typename = typename }, .format);
column_name.* = column.name;
column_type.* = typename.type;
column_value.* = column_index;
create_table = create_table ++ std.fmt.comptimePrint("{s}{s} {f}", .{ separator, column.name, format });
}
const TagColumns = @Enum(TagIntColumns, .exhaustive, &column_names, &column_values);
const Columns = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
table_name.* = table.name;
table_type.* = Columns;
table_value.* = table_index;
statement.* = create_table ++ ");";
}
const TagTables = @Enum(TagIntTables, .exhaustive, &table_names, &table_values);
const Tables = @Union(.auto, TagTables, &table_names, &table_types, &@splat(.{}));
const create_tables = statements;
return struct {
handle: *sqlite.sqlite3,
pub const Deinit = enum {
ok,
busy,
};
pub const Error = Result.Error;
pub const Kind = union(enum) {
temp_in_memory,
temp_on_disk,
path: [:0]const u8,
};
const Schema = Tables;
const Self = @This();
// Source: https://sqlite.org/c3ref/open.html
// NOTE: caller must close db connection if fn returns error or if db
// is no longer needed to prevent ressource leaks
pub fn init(kind: Kind) Error!Self {
const name = switch (kind) {
.temp_in_memory => ":memory:",
.temp_on_disk => "",
.path => |path| path,
};
const self: Self = open: {
var handle : ?*sqlite.sqlite3 = null;
const open = try Result.from(sqlite.sqlite3_open(name.ptr, &handle))
.orElse(sqlite.sqlite3_extended_errcode, .{ handle })
.toErrorUnion();
const enable_extended = try Result.from(sqlite.sqlite3_extended_result_codes(handle, 1))
.toErrorUnion();
assert(open == .ok);
assert(enable_extended == .ok);
break :open .{ .handle = handle.? };
};
for (create_tables) |create_table| {
const exec = try Result.from(sqlite.sqlite3_exec(self.handle, create_table.ptr, null, null, null))
.toErrorUnion();
assert(exec == .ok);
}
return self;
}
// See https://sqlite.org/c3ref/close.html
pub fn deinit(self: *Self) Deinit {
const close: Result = .from(sqlite.sqlite3_close(self.handle));
if (close == .ok) {
self.* = undefined;
return .ok;
}
return .busy;
}
// NOTE: SELECT without FROM is non-conforming SQL
// https://stackoverflow.com/questions/3732422/select-from-nothing
// https://modern-sql.com/use-case/select-without-from
pub fn select(self: *Self, comptime from: std.meta.Tag(Schema), comptime columns: []const std.meta.Tag(@FieldType(Schema, @tagName(from)))) Select(Self, from, columns) {
return .{ .database = self };
}
// https://cs.stackexchange.com/questions/138556/how-to-find-the-largest-power-of-two-divisor-of-a-given-integer
// const num: usize = 24;
// std.debug.print("{}\n", .{ num & (~num + 1) }); // same as num & -num
// fn allocator(self: *const Self) Allocator {
// _ = self;
//
// const Functions = struct {
// // https://stackoverflow.com/questions/227897/how-to-allocate-aligned-memory-only-using-the-standard-library
// fn allocHeader(aligned_ptr: [*]u8) *[*]u8 {
// return @ptrCast(@alignCast(aligned_ptr - @sizeOf(usize)));
// }
//
// fn alloc(ctx: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 {
// _ = ctx;
// _ = ret_addr;
//
// // unaligned_ptr aligned_ptr
// // v v
// // +----------+----------+------------------------------+
// // | padding | header | usable bytes |
// // +----------+----------+------------------------------+
// const total_len = (alignment.toByteUnits() - 1) + @sizeOf(usize) + len;
// const allocation = sqlite.sqlite3_malloc64(total_len) orelse return null;
//
// const unaligned_ptr: [*]u8 = @ptrCast(allocation);
// const unaligned_addr = @intFromPtr(unaligned_ptr);
//
// const aligned_addr = alignment.forward(unaligned_addr + @sizeOf(usize));
// const aligned_ptr = unaligned_ptr + (aligned_addr - unaligned_addr);
//
// allocHeader(aligned_ptr).* = unaligned_ptr;
//
// return aligned_ptr;
// }
//
// fn free(ctx: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void {
// _ = ctx;
// _ = alignment;
// _ = ret_addr;
//
// sqlite.sqlite3_free(allocHeader(memory.ptr).*);
// }
//
// fn remap(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
// if (resize(ctx, memory, alignment, new_len, ret_addr)) return memory.ptr;
//
// // `sqlite.sqlite3_realloc64` may return a new allocation
// // with a different alignment than the original allocation,
// // so we just give up.
// return null;
// }
//
// fn resize(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool {
// _ = ctx;
// _ = alignment;
// _ = ret_addr;
//
// if (new_len <= memory.len) return true;
//
// const unaligned_ptr = allocHeader(memory.ptr).*;
// const overallocation = @intFromPtr(memory.ptr) - @intFromPtr(unaligned_ptr);
//
// const total_len = sqlite.sqlite3_msize(unaligned_ptr);
// const usable_len = total_len - overallocation;
//
// return new_len <= usable_len;
// }
// };
//
// return .{
// .ptr = undefined,
// .vtable = &.{
// .alloc = Functions.alloc,
// .free = Functions.free,
// .remap = Functions.remap,
// .resize = Functions.resize,
// },
// };
// }
};
}
pub const Integer = Typename(.integer);
pub const Real = Typename(.real);
pub const Text = Typename(.text);
const Affinity = enum {
integer,
real,
text,
const Value = union(Affinity) {
integer: i64,
real : f64,
text : [:0]const u8,
fn FieldType(comptime field: std.meta.Tag(Value)) type {
return @FieldType(Value, @tagName(field));
}
fn from(value: anytype) Value {
const T = @TypeOf(value);
inline for (std.meta.fields(Value)) |field| {
if (field.type == T) return @unionInit(Value, field.name, value);
}
@compileError("Cannot construct `Value` from value of type `" ++ @typeName(T) ++ "`");
}
fn serialise(self: Value, writer: *Writer) Writer.Error!void {
return switch (self) {
.integer => |value| writer.print("{d}", .{ value }),
.real => |value| writer.print("{d}", .{ value }),
.text => |value| writer.print("'{s}'", .{ value }),
};
}
};
fn serialise(self: Affinity, writer: *Writer) Writer.Error!void {
return switch (self) {
.integer => writer.writeAll("INTEGER"),
.real => writer.writeAll("REAL"),
.text => writer.writeAll("TEXT"),
};
}
};
// TODO: handle primary key (e.g. force every table to have one, etc.)
fn Typename(comptime affinity: Affinity) type {
const T = Affinity.Value.FieldType(affinity);
return struct {
type : type = T,
affinity: Affinity = affinity,
default_value: ?T = null,
is_not_null : bool = false,
is_unique : bool = false,
pub const any: Self = .{};
pub const Self = @This();
pub fn default(comptime self: Self, comptime value: T) Self {
if (self.default_value) |_| @compileError("Duplicate `DEFAULT` constraint");
var this = self;
this.default_value = value;
return this;
}
pub fn notNull(comptime self: Self) Self {
if (self.is_not_null) @compileError("Duplicate `NOT NULL` constraint");
var this = self;
this.is_not_null = true;
return this;
}
pub fn unique(comptime self: Self) Self {
if (self.is_unique) @compileError("Duplicate `UNIQUE` constraint");
var this = self;
this.is_unique = true;
return this;
}
fn serialise(self: Self, writer: *Writer) Writer.Error!void {
try self.affinity.serialise(writer);
if (self.default_value) |value| {
try writer.writeAll(" DEFAULT ");
try Affinity.Value.from(value).serialise(writer);
}
if (self.is_not_null) {
try writer.writeAll(" NOT NULL");
}
if (self.is_unique) {
try writer.writeAll(" UNIQUE");
}
}
};
}
fn isTypename(comptime T: type) bool {
if (!@hasField(T, "affinity")) return false;
const affinity = std.meta.fieldInfo(T, .affinity).defaultValue() orelse return false;
return T == Typename(affinity);
}
fn Select(comptime Db: type, comptime from: std.meta.Tag(Db.Schema), comptime columns: []const std.meta.Tag(@FieldType(Db.Schema, @tagName(from)))) type {
if (columns.len == 0) @compileError("At least one column must be selected");
const PrepareError = Allocator.Error || Db.Error;
const TagIntColumns = @Int(.unsigned, std.math.log2_int_ceil(@TypeOf(columns.len), columns.len));
var column_names : [columns.len][]const u8 = undefined;
var column_types : [columns.len]type = undefined;
var column_values: [columns.len]TagIntColumns = undefined;
inline for (&column_names, &column_types, &column_values, columns, 0..) |*column_name, *column_type, *column_value, column,column_index| {
column_name.* = @tagName(column);
column_value.* = column_index;
column_type.* = @FieldType(@FieldType(Db.Schema, @tagName(from)), @tagName(column));
}
// NOTE: Uniqueness of selected columns is enforced here.
const TagColumns = @Enum(TagIntColumns, .exhaustive, &column_names, &column_values);
const Selected = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
return struct {
database: *Db,
filter: Filter = .none,
// sort: ..., // ORDER BY
take : Take = .unlimited,
unique: bool = false,
pub const Filter = union(enum) {
none,
some: []const Node,
const Offset = u16;
const Node = union(enum) {
binary: struct {
operator: enum { @"and", @"or" },
lhs: Offset,
rhs: Offset,
},
cmp: struct {
column : std.meta.Tag(Columns),
operator: Operator,
value : Affinity.Value,
fn serialise(self: @This(), writer: *Writer) Writer.Error!void {
try writer.writeAll(@tagName(self.column));
try writer.writeByte(' ');
try self.operator.serialise(writer);
try writer.writeByte(' ');
try self.value.serialise(writer);
}
},
};
pub fn @"and"(comptime lhs: Filter, comptime rhs: Filter) Filter {
const node: Node = .{ .binary = .{ .operator = .@"and", .lhs = 1, .rhs = lhs.nodes().len + 1 } };
return .{ .some = .{ node } ++ lhs.nodes() ++ rhs.nodes() };
}
pub fn cmp(comptime column: std.meta.Tag(Columns), operator: Operator, value: @FieldType(Columns, @tagName(column))) Filter {
const node: Node = .{ .cmp = .{ .column = column, .operator = operator, .value = .from(value) } };
return .{ .some = &.{ node } };
}
pub fn @"or"(comptime lhs: Filter, comptime rhs: Filter) Filter {
const node: Node = .{ .binary = .{ .operator = .@"or", .lhs = 1, .rhs = lhs.nodes().len + 1 } };
return .{ .some = .{ node } ++ lhs.nodes() ++ rhs.nodes() };
}
fn nodes(comptime self: Filter) []const Node {
return switch (self) {
.none => &.{},
.some => |n| n,
};
}
};
pub const Limit = union(enum) {
const UInt = int: {
const info = @typeInfo(Affinity.Value.FieldType(.integer));
break :int @Int(.unsigned, info.int.bits - @intFromBool(info.int.signedness == .signed));
};
count : UInt,
offset: struct {
start: UInt,
count: UInt,
},
};
const Columns = Selected;
const Self = @This();
const Take = union(enum) {
unlimited,
limit: Limit,
};
pub fn distinct(self: Self) Self {
if (self.unique) @panic("Duplicate `DISTINCT` constraint");
var this = self;
this.unique = true;
return this;
}
pub fn limit(self: Self, lim: Limit) Self {
if (self.take != .unlimited) @panic("Duplicate `LIMIT` constraint");
var this = self;
this.take = .{ .limit = lim };
return this;
}
// TODO
pub fn prepare(self: Self, allocator: Allocator) PrepareError!Statement {
var allocating_writer: std.Io.Writer.Allocating = .init(allocator);
defer allocating_writer.deinit();
self.serialise(&allocating_writer.writer) catch |err| switch (err) {
error.WriteFailed => return error.OutOfMemory,
};
const string = try allocating_writer.toOwnedSlice();
defer allocator.free(string);
// TODO: prepare statement
std.debug.print("{s}\n", .{ string });
return .{};
}
pub fn where(self: Self, comptime filter: Filter) Self {
if (self.filter != .none) @panic("Duplicate `WHERE` constraint");
var this = self;
this.filter = filter;
return this;
}
fn serialise(self: Self, writer: *Writer) Writer.Error!void {
try writer.writeAll("SELECT");
if (self.unique) {
try writer.writeAll(" DISTINCT");
}
const all_columns_selected: bool = columns.len == std.meta.fields(@FieldType(Db.Schema, @tagName(from))).len;
if (all_columns_selected) {
try writer.writeAll(" *");
} else for (columns, 0..) |column, index| {
const separator = if (index == 0) " " else ", ";
try writer.writeAll(separator);
try writer.writeAll(@tagName(column));
}
switch (self.filter) {
.none => {},
.some => |nodes| {
try writer.writeAll(" WHERE ");
const State = struct {
parent :?Filter.Offset = null,
current: Filter.Offset = 0,
depth : Filter.Offset = 0,
const init: @This() = .{};
};
var state: State = .init;
while (state.current < nodes.len) {
switch (nodes[state.current]) {
.binary => {
if (state.parent) |parent| {
const operator = switch (nodes[parent]) {
.binary => |value| value.operator,
.cmp => unreachable,
};
// NOTE: This is always in bounds as the first node in `nodes`
// never has a parent, i.e. this branch is taken if and
// only if `state.current > 0` holds.
if (std.meta.activeTag(nodes[state.current - 1]) == .cmp) {
switch (operator) {
.@"and" => try writer.writeAll(" AND "),
.@"or" => try writer.writeAll(" OR "),
}
}
}
state.parent = state.current;
state.current += 1;
state.depth += 1;
if (state.depth > 1) try writer.writeByte('(');
},
.cmp => |current| {
if (state.parent == null) {
try current.serialise(writer);
state.current += 1;
continue;
}
const parent_index = state.parent.?;
const parent_has_parent = parent_index > 0 and std.meta.activeTag(nodes[parent_index - 1]) != .cmp;
const parent_of_parent = if (parent_has_parent) parent_index - 1 else null;
switch (nodes[parent_index]) {
.binary => |parent| {
switch (nodes[parent_index + parent.lhs]) {
.cmp => |lhs| {
try lhs.serialise(writer);
state.current += 1;
},
else => {},
}
switch (parent.operator) {
.@"and" => try writer.writeAll(" AND "),
.@"or" => try writer.writeAll(" OR "),
}
switch (nodes[parent_index + parent.rhs]) {
.cmp => |rhs| {
try rhs.serialise(writer);
state.current += 1;
},
else => {},
}
if (state.depth > 1) try writer.writeByte(')');
state.parent = parent_of_parent;
state.depth -= 1;
},
.cmp => unreachable,
}
},
}
}
while (state.depth > 1) : (state.depth -= 1) {
try writer.writeByte(')');
}
},
}
switch (self.take) {
.unlimited => {},
.limit => |lim| switch (lim) {
.count => |value| {
const count: Affinity.Value = .{ .integer = value };
try writer.writeAll(" LIMIT ");
try count.serialise(writer);
},
.offset => |value| {
const start: Affinity.Value = .{ .integer = value.start };
const count: Affinity.Value = .{ .integer = value.count };
try writer.writeByte(' ');
try start.serialise(writer);
try writer.writeAll(", ");
try count.serialise(writer);
},
},
}
try writer.writeByte(';');
}
};
}
pub const Statement = struct {
pub fn deinit(self: *Statement) void {
self.* = undefined;
}
};
// Result models Result Codes
// ok,done,row are the only non-error result codes
const Result = union(enum) {
err: Error,
ok : Ok,
// Error models Error Codes
const Error = set: {
var set: type = error{};
for (std.meta.tags(Primary)) |tag| {
if (!tag.isError()) continue;
set = set || @TypeOf(@field(anyerror, @tagName(tag)));
}
for (std.meta.fieldNames(Extended)) |name| {
set = set || @TypeOf(@field(anyerror, name));
}
break :set set;
};
const Ok = enum {
ok,
row,
done,
};
// zig fmt: off
const Primary = enum(i32) {
ok = 0,
@"error" = 1,
internal = 2,
perm = 3,
abort = 4,
busy = 5,
locked = 6,
nomem = 7,
readonly = 8,
interrupt = 9,
ioerr = 10,
corrupt = 11,
notfound = 12,
full = 13,
cantopen = 14,
protocol = 15,
empty = 16,
schema = 17,
toobig = 18,
constraint = 19,
mismatch = 20,
misuse = 21,
nolfs = 22,
auth = 23,
format = 24,
range = 25,
notadb = 26,
notice = 27,
warning = 28,
row = 100,
done = 101,
fn isError(self: Primary) bool {
return switch (self) {
.ok, .row, .done => false,
else => true,
};
}
};
const Extended = enum(i32) {
error_missing_collseq = @intFromEnum(Primary.@"error") | ( 1 << 8),
error_retry = @intFromEnum(Primary.@"error") | ( 2 << 8),
error_snapshot = @intFromEnum(Primary.@"error") | ( 3 << 8),
error_reservesize = @intFromEnum(Primary.@"error") | ( 4 << 8),
error_key = @intFromEnum(Primary.@"error") | ( 5 << 8),
error_unable = @intFromEnum(Primary.@"error") | ( 6 << 8),
ioerr_read = @intFromEnum(Primary.ioerr) | ( 1 << 8),
ioerr_short_read = @intFromEnum(Primary.ioerr) | ( 2 << 8),
ioerr_write = @intFromEnum(Primary.ioerr) | ( 3 << 8),
ioerr_fsync = @intFromEnum(Primary.ioerr) | ( 4 << 8),
ioerr_dir_fsync = @intFromEnum(Primary.ioerr) | ( 5 << 8),
ioerr_truncate = @intFromEnum(Primary.ioerr) | ( 6 << 8),
ioerr_fstat = @intFromEnum(Primary.ioerr) | ( 7 << 8),
ioerr_unlock = @intFromEnum(Primary.ioerr) | ( 8 << 8),
ioerr_rdlock = @intFromEnum(Primary.ioerr) | ( 9 << 8),
ioerr_delete = @intFromEnum(Primary.ioerr) | (10 << 8),
ioerr_blocked = @intFromEnum(Primary.ioerr) | (11 << 8),
ioerr_nomem = @intFromEnum(Primary.ioerr) | (12 << 8),
ioerr_access = @intFromEnum(Primary.ioerr) | (13 << 8),
ioerr_checkreservedlock = @intFromEnum(Primary.ioerr) | (14 << 8),
ioerr_lock = @intFromEnum(Primary.ioerr) | (15 << 8),
ioerr_close = @intFromEnum(Primary.ioerr) | (16 << 8),
ioerr_dir_close = @intFromEnum(Primary.ioerr) | (17 << 8),
ioerr_shmopen = @intFromEnum(Primary.ioerr) | (18 << 8),
ioerr_shmsize = @intFromEnum(Primary.ioerr) | (19 << 8),
ioerr_shmlock = @intFromEnum(Primary.ioerr) | (20 << 8),
ioerr_shmmap = @intFromEnum(Primary.ioerr) | (21 << 8),
ioerr_seek = @intFromEnum(Primary.ioerr) | (22 << 8),
ioerr_delete_noent = @intFromEnum(Primary.ioerr) | (23 << 8),
ioerr_mmap = @intFromEnum(Primary.ioerr) | (24 << 8),
ioerr_gettemppath = @intFromEnum(Primary.ioerr) | (25 << 8),
ioerr_convpath = @intFromEnum(Primary.ioerr) | (26 << 8),
ioerr_vnode = @intFromEnum(Primary.ioerr) | (27 << 8),
ioerr_auth = @intFromEnum(Primary.ioerr) | (28 << 8),
ioerr_begin_atomic = @intFromEnum(Primary.ioerr) | (29 << 8),
ioerr_commit_atomic = @intFromEnum(Primary.ioerr) | (30 << 8),
ioerr_rollback_atomic = @intFromEnum(Primary.ioerr) | (31 << 8),
ioerr_data = @intFromEnum(Primary.ioerr) | (32 << 8),
ioerr_corruptfs = @intFromEnum(Primary.ioerr) | (33 << 8),
ioerr_in_page = @intFromEnum(Primary.ioerr) | (34 << 8),
ioerr_badkey = @intFromEnum(Primary.ioerr) | (35 << 8),
ioerr_codec = @intFromEnum(Primary.ioerr) | (36 << 8),
locked_sharedcache = @intFromEnum(Primary.locked) | ( 1 << 8),
locked_vtab = @intFromEnum(Primary.locked) | ( 2 << 8),
busy_recovery = @intFromEnum(Primary.busy) | ( 1 << 8),
busy_snapshot = @intFromEnum(Primary.busy) | ( 2 << 8),
busy_timeout = @intFromEnum(Primary.busy) | ( 3 << 8),
cantopen_notempdir = @intFromEnum(Primary.cantopen) | ( 1 << 8),
cantopen_isdir = @intFromEnum(Primary.cantopen) | ( 2 << 8),
cantopen_fullpath = @intFromEnum(Primary.cantopen) | ( 3 << 8),
cantopen_convpath = @intFromEnum(Primary.cantopen) | ( 4 << 8),
cantopen_symlink = @intFromEnum(Primary.cantopen) | ( 6 << 8),
corrupt_vtab = @intFromEnum(Primary.corrupt) | ( 1 << 8),
corrupt_sequence = @intFromEnum(Primary.corrupt) | ( 2 << 8),
corrupt_index = @intFromEnum(Primary.corrupt) | ( 3 << 8),
readonly_recovery = @intFromEnum(Primary.readonly) | ( 1 << 8),
readonly_cantlock = @intFromEnum(Primary.readonly) | ( 2 << 8),
readonly_rollback = @intFromEnum(Primary.readonly) | ( 3 << 8),
readonly_dbmoved = @intFromEnum(Primary.readonly) | ( 4 << 8),
readonly_cantinit = @intFromEnum(Primary.readonly) | ( 5 << 8),
readonly_directory = @intFromEnum(Primary.readonly) | ( 6 << 8),
abort_rollback = @intFromEnum(Primary.abort) | ( 2 << 8),
constraint_check = @intFromEnum(Primary.constraint) | ( 1 << 8),
constraint_commithook = @intFromEnum(Primary.constraint) | ( 2 << 8),
constraint_foreignkey = @intFromEnum(Primary.constraint) | ( 3 << 8),
constraint_function = @intFromEnum(Primary.constraint) | ( 4 << 8),
constraint_notnull = @intFromEnum(Primary.constraint) | ( 5 << 8),
constraint_primarykey = @intFromEnum(Primary.constraint) | ( 6 << 8),
constraint_trigger = @intFromEnum(Primary.constraint) | ( 7 << 8),
constraint_unique = @intFromEnum(Primary.constraint) | ( 8 << 8),
constraint_vtab = @intFromEnum(Primary.constraint) | ( 9 << 8),
constraint_rowid = @intFromEnum(Primary.constraint) | (10 << 8),
constraint_pinned = @intFromEnum(Primary.constraint) | (11 << 8),
constraint_datatype = @intFromEnum(Primary.constraint) | (12 << 8),
notice_recover_wal = @intFromEnum(Primary.notice) | ( 1 << 8),
notice_recover_rollback = @intFromEnum(Primary.notice) | ( 2 << 8),
notice_rbu = @intFromEnum(Primary.notice) | ( 3 << 8),
warning_autoindex = @intFromEnum(Primary.warning) | ( 1 << 8),
auth_user = @intFromEnum(Primary.auth) | ( 1 << 8),
ok_load_permanently = @intFromEnum(Primary.ok) | ( 1 << 8),
};
// zig fmt: on
fn from(code: c_int) Result {
if (std.enums.fromInt(Primary, code)) |primary| switch (primary) {
.ok => return .{ .ok = .ok },
.row => return .{ .ok = .row },
.done => return .{ .ok = .done },
inline else => |error_name| return .{ .err = @field(Error, @tagName(error_name)) },
} else if (std.enums.fromInt(Extended, code)) |extended| switch (extended) {
inline else => |error_name| return .{ .err = @field(Error, @tagName(error_name)) },
} else {
unreachable;
}
}
fn orElse(self: Result, function: anytype, args: anytype) Result {
comptime { assert(@typeInfo(@TypeOf(function)).@"fn".return_type == c_int); }
return switch (self) {
.ok => self,
.err => .from(@call(.auto, function, args)),
};
}
fn toErrorUnion(self: Result) Error!Ok {
return switch (self) {
.ok => |okay| okay,
.err => |error_name| error_name,
};
}
};
pub const Operator = enum {
lt,
leq,
eql,
neq,
geq,
gt,
in,
not_in,
between,
is,
is_not,
fn serialise(self: Operator, writer: *Writer) Writer.Error!void {
return switch (self) {
.lt => writer.writeAll("<"),
.leq => writer.writeAll("<="),
.eql => writer.writeAll("=="),
.neq => writer.writeAll("!="),
.geq => writer.writeAll(">="),
.gt => writer.writeAll(">"),
.in => writer.writeAll("IN"),
.not_in => writer.writeAll("NOT IN"),
.between => writer.writeAll("BETWEEN"),
.is => writer.writeAll("IS"),
.is_not => writer.writeAll("IS NOT"),
};
}
};
test {
const allocator = std.testing.allocator;
const Schema = struct {
contacts: Contacts,
const Contacts = struct {
// Read as "any column value is possible"
contact_id: Integer = .any,
// Read as "any column value defaults to 'John' and is not null"
first_name: Text = .notNull(.default(.any, "John")),
// Read as "any column value defaults to 'Doe' and is not null"
last_name : Text = .notNull(.default(.any, "Doe")),
// Read as "any column value is not null"
age : Integer = .notNull(.any),
// Read as "any column value defaults to '0.0' and is not null"
net_worth : Real = .notNull(.default(.any, 0.0)),
};
};
var db: Database(Schema) = try .init(.temp_in_memory);
defer assert(db.deinit() == .ok);
const query = db.select(.contacts, &.{ .first_name , .last_name, .age })
// TODO: convert to tests
// .where(.cmp(.first_name, .eql, "Bob"))
// .where(.@"and"(.cmp(.first_name, .eql, "Bob"), .cmp(.age, .geq, 42)))
// .where(.@"and"(.@"and"(.cmp(.first_name, .eql, "Bob"), .cmp(.age, .geq, 42)), .cmp(.last_name, .is_not, "Smith")))
// .where(.@"or"(.@"and"(.cmp(.first_name, .eql, "Bob"), .cmp(.age, .geq, 42)), .@"and"(.cmp(.age, .eql, 69), .cmp(.last_name, .is_not, "Smith"))))
.where(.@"or"(.@"and"(.@"and"(.cmp(.first_name, .eql, "Bob"), .cmp(.age, .geq, 42)), .cmp(.last_name, .is_not, "Smith")), .cmp(.age, .eql, 69)))
.distinct()
.limit(.{ .count = 25 });
var statement = try query.prepare(allocator);
defer statement.deinit();
// var rows = statement.iterator();
//
// while (rows.next()) |row| {
// // TODO: row contains row_data,col_idx,col_name
// _ = row;
// }
}
// test {
// NOTE: we don't use `union(enum)` here as if a column has a default value,
// an integer tag type is needed explicitely, which, from a usability
// standpoint, is not great; we can calulate this value in `Schema.from`.
//
// CREATE TABLE contacts (
// contact_id INTEGER PRIMARY KEY,
// first_name TEXT NOT NULL DEFAULT "Hans",
// last_name TEXT NOT NULL DEFAULT "Mustermann",
// nickname TEXT,
// email TEXT NOT NULL UNIQUE,
// phone TEXT NOT NULL UNIQUE
// );
// const S = struct {
// contacts: struct {
// contact_id: PrimaryKey(Integer, .{}),
// first_name: VarChar(255, .{}) = "Hans",
// last_name: VarChar(255, .{}) = "Mustermann",
// nickname: ?VarChar(255, .{}),
// email: VarChar(255, .{.unique}),
// phone: VarChar(255, .{.unique}),
// },
// };
//
// // NOTE: init connects to DB and creates tables if not already present
// var db: Database(Schema(S)) = try .init(.temp_in_memory);
// db.deinit();
// }
|