aboutsummaryrefslogtreecommitdiff
path: root/src/db/sqlite.zig
diff options
context:
space:
mode:
authorAlexander Rolley <arolley35@gmail.com>2026-10-10 15:19:49 +0200
committerAlexander Rolley <arolley35@gmail.com>2026-10-10 15:19:49 +0200
commitd5c1b186e41b74046a5cf13528727cb5171663f2 (patch)
tree19f579e2844842b0534f8124f88fd8fb8e8fc124 /src/db/sqlite.zig
parentdc90bc811648da695e4cb47826ea6479cfd22a06 (diff)
Continue.
Diffstat (limited to 'src/db/sqlite.zig')
-rw-r--r--src/db/sqlite.zig581
1 files changed, 313 insertions, 268 deletions
diff --git a/src/db/sqlite.zig b/src/db/sqlite.zig
index 9a9d5bf..1d27dd5 100644
--- a/src/db/sqlite.zig
+++ b/src/db/sqlite.zig
@@ -1,7 +1,8 @@
-const std = @import("std");
+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;
@@ -16,11 +17,12 @@ pub fn Database(comptime T: type) type {
// 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_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, tables, 0..) |*table_name, *table_type, *table_value, table, table_index| {
+ 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`"),
@@ -32,32 +34,45 @@ pub fn Database(comptime T: type) type {
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_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 column_field_value = std.builtin.Type.StructField.defaultValue(column) orelse @compileError("Column `" ++ column.name ++ "` is missing value");
+ const typename = std.builtin.Type.StructField.defaultValue(column) orelse @compileError("Column `" ++ column.name ++ "` is missing value");
+ const separator = if (column_index == 0) "" else ", ";
- // TODO: use `column_field_value` to build `CREATE TABLE` SQLite statement
+ 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.* = column_field_value.type;
+ 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(.{}));
+ const Columns = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
- table_name.* = table.name;
- table_type.* = Columns;
+ 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 Tables = @Union(.auto, TagTables, &table_names, &table_types, &@splat(.{}));
+
+ const create_tables = statements;
return struct {
handle: *sqlite.sqlite3,
@@ -67,62 +82,151 @@ pub fn Database(comptime T: type) type {
busy,
};
- pub const Error = set: {
- var set: type = error{};
-
- for (std.meta.fieldNames(Result.Primary)) |name| {
- set = set || @TypeOf(@field(anyerror, name));
- }
- for (std.meta.fieldNames(Result.Extended)) |name| {
- set = set || @TypeOf(@field(anyerror, name));
- }
-
- break :set set;
- };
+ pub const Error = Result.Error;
pub const Kind = union(enum) {
temp_in_memory,
temp_on_disk,
- path: []const u8,
+ 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,
+ .temp_on_disk => "",
+ .path => |path| path,
};
- var handle: ?*sqlite.sqlite3 = null;
- const result: Result = .from(sqlite.sqlite3_open(name.ptr, &handle));
- const primary = result.asPrimary();
+ const self: Self = open: {
+ var handle : ?*sqlite.sqlite3 = null;
- if (primary != .ok) return result.toError(Error, handle);
-
- return .{ .handle = handle.? };
+ 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 result: Result = .from(sqlite.sqlite3_close(self.handle));
- const primary = result.asPrimary();
+ const close: Result = .from(sqlite.sqlite3_close(self.handle));
- if (primary == .busy) return .busy;
+ if (close == .ok) {
+ self.* = undefined;
+ return .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(Schema, from, columns) {
- return .{ .handle = self.handle };
+ 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,
+// },
+// };
+// }
};
}
@@ -138,7 +242,7 @@ const Affinity = enum {
const Value = union(Affinity) {
integer: i64,
real : f64,
- text : []const u8,
+ text : [:0]const u8,
fn FieldType(comptime field: std.meta.Tag(Value)) type {
return @FieldType(Value, @tagName(field));
@@ -241,9 +345,10 @@ fn isTypename(comptime T: type) bool {
return T == Typename(affinity);
}
-fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime columns: []const std.meta.Tag(@FieldType(Schema, @tagName(from)))) type {
+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;
@@ -253,7 +358,7 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
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(Schema, @tagName(from)), @tagName(column));
+ column_type.* = @FieldType(@FieldType(Db.Schema, @tagName(from)), @tagName(column));
}
// NOTE: Uniqueness of selected columns is enforced here.
@@ -261,7 +366,7 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
const Selected = @Union(.auto, TagColumns, &column_names, &column_types, &@splat(.{}));
return struct {
- handle: *sqlite.sqlite3,
+ database: *Db,
filter: Filter = .none,
// sort: ..., // ORDER BY
@@ -318,97 +423,6 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
.some => |n| n,
};
}
-
- // pub fn format(self: Filter, writer: *Writer) Writer.Error!void {
- // const State = struct {
- // index: usize = 0,
- // node : ?*const Filter.Node = null,
- // last_node: enum{ binary_expression, cmp, none } = .none,
- // parentheses: isize = -1,
- //
- // const init: @This() = .{};
- // };
- //
- // var state: State = .init;
- //
- // while (state.index < self.nodes.len) {
- // switch (self.nodes[state.index]) {
- // .@"and", .@"or" => {
- // if (state.node) |node| {
- // if (state.last_node == .cmp) {
- // try writer.print(" {f} ", .{ node });
- // }
- // }
- // if (state.parentheses >= 0) try writer.writeByte('(');
- // state.node = &self.nodes[state.index];
- // state.index += 1;
- // state.last_node = .binary_expression;
- // state.parentheses += 1;
- // },
- // .cmp => {
- // if (state.node) |node| {
- // const index = node[0..1] - self.nodes.ptr;
- // const parent = if (index > 0) &self.nodes[index - 1] else null;
- //
- // switch (node.*) {
- // .@"and" => |value| {
- // switch (self.nodes[index + value.lhs]) {
- // .cmp => {
- // try writer.print("{f}", .{ self.nodes[index + value.lhs] });
- // state.index += 1;
- // },
- // else => {},
- // }
- // try writer.print(" {f} ", .{ node });
- // switch (self.nodes[index + value.rhs]) {
- // .cmp => {
- // try writer.print("{f}", .{ self.nodes[index + value.rhs] });
- // state.index += 1;
- // },
- // else => {},
- // }
- // if (state.parentheses > 0) try writer.writeByte(')');
- //
- // state.node = parent;
- // state.parentheses -= 1;
- // },
- // .@"or" => |value| {
- // switch (self.nodes[index + value.lhs]) {
- // .cmp => {
- // try writer.print("{f}", .{ self.nodes[index + value.lhs] });
- // state.index += 1;
- // },
- // else => {},
- // }
- // try writer.print(" {f} ", .{ node });
- // switch (self.nodes[index + value.rhs]) {
- // .cmp => {
- // try writer.print("{f}", .{ self.nodes[index + value.rhs] });
- // state.index += 1;
- // },
- // else => {},
- // }
- // if (state.parentheses > 0) try writer.writeByte(')');
- //
- // state.node = parent;
- // state.parentheses -= 1;
- // },
- // .cmp => unreachable,
- // }
- // } else {
- // try writer.print("{f}", .{ self.nodes[state.index] });
- // state.index += 1;
- // }
- // state.last_node = .cmp;
- // },
- // }
- // }
- //
- // var index = state.parentheses;
- // while (index > 0) : (index -= 1) {
- // try writer.writeByte(')');
- // }
- // }
};
pub const Limit = union(enum) {
@@ -450,9 +464,8 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
return this;
}
- // FIXME: change return type to sql stmt and update error type
- // TODO: return type must be SQLite stmt value; can error also be SQLite error? if so, make union with allocator.error
- pub fn prepare(self: Self, allocator: Allocator) Allocator.Error!void {
+ // TODO
+ pub fn prepare(self: Self, allocator: Allocator) PrepareError!Statement {
var allocating_writer: std.Io.Writer.Allocating = .init(allocator);
defer allocating_writer.deinit();
@@ -463,7 +476,9 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
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 {
@@ -482,7 +497,7 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
try writer.writeAll(" DISTINCT");
}
- const all_columns_selected: bool = columns.len == std.meta.fields(@FieldType(Schema, @tagName(from))).len;
+ const all_columns_selected: bool = columns.len == std.meta.fields(@FieldType(Db.Schema, @tagName(from))).len;
if (all_columns_selected) {
try writer.writeAll(" *");
@@ -611,19 +626,41 @@ fn Select(comptime Schema: type, comptime from: std.meta.Tag(Schema), comptime c
};
}
-/// SQLite result codes.
-///
-/// Primary result codes define a broad category of results, whereas extended
-/// result codes provide more detail. The primary result code is always part of
-/// an extended result code.
-///
-/// See https://sqlite.org/rescode.html
-const Result = enum(i32) {
- _,
+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
- /// Primary result codes.
- const Primary = enum(u8) {
+ const Primary = enum(i32) {
ok = 0,
@"error" = 1,
internal = 2,
@@ -656,124 +693,125 @@ const Result = enum(i32) {
row = 100,
done = 101,
- /// Returns the primary result code as type `T`.
- fn as(self: Primary, comptime T: type) T {
- return @as(T, @intFromEnum(self));
+ fn isError(self: Primary) bool {
+ return switch (self) {
+ .ok, .row, .done => false,
+ else => true,
+ };
}
};
- /// Extended result codes.
const Extended = enum(i32) {
- error_missing_collseq = (Primary.@"error".as(i32) | ( 1 << 8)),
- error_retry = (Primary.@"error".as(i32) | ( 2 << 8)),
- error_snapshot = (Primary.@"error".as(i32) | ( 3 << 8)),
- error_reservesize = (Primary.@"error".as(i32) | ( 4 << 8)),
- error_key = (Primary.@"error".as(i32) | ( 5 << 8)),
- error_unable = (Primary.@"error".as(i32) | ( 6 << 8)),
- ioerr_read = (Primary.ioerr.as(i32) | ( 1 << 8)),
- ioerr_short_read = (Primary.ioerr.as(i32) | ( 2 << 8)),
- ioerr_write = (Primary.ioerr.as(i32) | ( 3 << 8)),
- ioerr_fsync = (Primary.ioerr.as(i32) | ( 4 << 8)),
- ioerr_dir_fsync = (Primary.ioerr.as(i32) | ( 5 << 8)),
- ioerr_truncate = (Primary.ioerr.as(i32) | ( 6 << 8)),
- ioerr_fstat = (Primary.ioerr.as(i32) | ( 7 << 8)),
- ioerr_unlock = (Primary.ioerr.as(i32) | ( 8 << 8)),
- ioerr_rdlock = (Primary.ioerr.as(i32) | ( 9 << 8)),
- ioerr_delete = (Primary.ioerr.as(i32) | (10 << 8)),
- ioerr_blocked = (Primary.ioerr.as(i32) | (11 << 8)),
- ioerr_nomem = (Primary.ioerr.as(i32) | (12 << 8)),
- ioerr_access = (Primary.ioerr.as(i32) | (13 << 8)),
- ioerr_checkreservedlock = (Primary.ioerr.as(i32) | (14 << 8)),
- ioerr_lock = (Primary.ioerr.as(i32) | (15 << 8)),
- ioerr_close = (Primary.ioerr.as(i32) | (16 << 8)),
- ioerr_dir_close = (Primary.ioerr.as(i32) | (17 << 8)),
- ioerr_shmopen = (Primary.ioerr.as(i32) | (18 << 8)),
- ioerr_shmsize = (Primary.ioerr.as(i32) | (19 << 8)),
- ioerr_shmlock = (Primary.ioerr.as(i32) | (20 << 8)),
- ioerr_shmmap = (Primary.ioerr.as(i32) | (21 << 8)),
- ioerr_seek = (Primary.ioerr.as(i32) | (22 << 8)),
- ioerr_delete_noent = (Primary.ioerr.as(i32) | (23 << 8)),
- ioerr_mmap = (Primary.ioerr.as(i32) | (24 << 8)),
- ioerr_gettemppath = (Primary.ioerr.as(i32) | (25 << 8)),
- ioerr_convpath = (Primary.ioerr.as(i32) | (26 << 8)),
- ioerr_vnode = (Primary.ioerr.as(i32) | (27 << 8)),
- ioerr_auth = (Primary.ioerr.as(i32) | (28 << 8)),
- ioerr_begin_atomic = (Primary.ioerr.as(i32) | (29 << 8)),
- ioerr_commit_atomic = (Primary.ioerr.as(i32) | (30 << 8)),
- ioerr_rollback_atomic = (Primary.ioerr.as(i32) | (31 << 8)),
- ioerr_data = (Primary.ioerr.as(i32) | (32 << 8)),
- ioerr_corruptfs = (Primary.ioerr.as(i32) | (33 << 8)),
- ioerr_in_page = (Primary.ioerr.as(i32) | (34 << 8)),
- ioerr_badkey = (Primary.ioerr.as(i32) | (35 << 8)),
- ioerr_codec = (Primary.ioerr.as(i32) | (36 << 8)),
- locked_sharedcache = (Primary.locked.as(i32) | ( 1 << 8)),
- locked_vtab = (Primary.locked.as(i32) | ( 2 << 8)),
- busy_recovery = (Primary.busy.as(i32) | ( 1 << 8)),
- busy_snapshot = (Primary.busy.as(i32) | ( 2 << 8)),
- busy_timeout = (Primary.busy.as(i32) | ( 3 << 8)),
- cantopen_notempdir = (Primary.cantopen.as(i32) | ( 1 << 8)),
- cantopen_isdir = (Primary.cantopen.as(i32) | ( 2 << 8)),
- cantopen_fullpath = (Primary.cantopen.as(i32) | ( 3 << 8)),
- cantopen_convpath = (Primary.cantopen.as(i32) | ( 4 << 8)),
- cantopen_symlink = (Primary.cantopen.as(i32) | ( 6 << 8)),
- corrupt_vtab = (Primary.corrupt.as(i32) | ( 1 << 8)),
- corrupt_sequence = (Primary.corrupt.as(i32) | ( 2 << 8)),
- corrupt_index = (Primary.corrupt.as(i32) | ( 3 << 8)),
- readonly_recovery = (Primary.readonly.as(i32) | ( 1 << 8)),
- readonly_cantlock = (Primary.readonly.as(i32) | ( 2 << 8)),
- readonly_rollback = (Primary.readonly.as(i32) | ( 3 << 8)),
- readonly_dbmoved = (Primary.readonly.as(i32) | ( 4 << 8)),
- readonly_cantinit = (Primary.readonly.as(i32) | ( 5 << 8)),
- readonly_directory = (Primary.readonly.as(i32) | ( 6 << 8)),
- abort_rollback = (Primary.abort.as(i32) | ( 2 << 8)),
- constraint_check = (Primary.constraint.as(i32) | ( 1 << 8)),
- constraint_commithook = (Primary.constraint.as(i32) | ( 2 << 8)),
- constraint_foreignkey = (Primary.constraint.as(i32) | ( 3 << 8)),
- constraint_function = (Primary.constraint.as(i32) | ( 4 << 8)),
- constraint_notnull = (Primary.constraint.as(i32) | ( 5 << 8)),
- constraint_primarykey = (Primary.constraint.as(i32) | ( 6 << 8)),
- constraint_trigger = (Primary.constraint.as(i32) | ( 7 << 8)),
- constraint_unique = (Primary.constraint.as(i32) | ( 8 << 8)),
- constraint_vtab = (Primary.constraint.as(i32) | ( 9 << 8)),
- constraint_rowid = (Primary.constraint.as(i32) | (10 << 8)),
- constraint_pinned = (Primary.constraint.as(i32) | (11 << 8)),
- constraint_datatype = (Primary.constraint.as(i32) | (12 << 8)),
- notice_recover_wal = (Primary.notice.as(i32) | ( 1 << 8)),
- notice_recover_rollback = (Primary.notice.as(i32) | ( 2 << 8)),
- notice_rbu = (Primary.notice.as(i32) | ( 3 << 8)),
- warning_autoindex = (Primary.warning.as(i32) | ( 1 << 8)),
- auth_user = (Primary.auth.as(i32) | ( 1 << 8)),
- ok_load_permanently = (Primary.ok.as(i32) | ( 1 << 8)),
+ 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
- /// Returns the result code corresponding to the given integer value.
- fn from(integer: anytype) Result {
- assert(std.enums.fromInt(Primary, integer) != null or std.enums.fromInt(Extended, integer) != null);
-
- return @enumFromInt(integer);
+ 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;
+ }
}
- /// Returns the error name corresponding to the result code. The `handle` is
- /// needed to fetch the extended result code, if it exists, only if `self`
- /// is not already an extended result code.
- fn toError(self: Result, comptime Error: type, handle: ?*sqlite.sqlite3) Error {
- if (std.enums.fromInt(Extended, @intFromEnum(self))) |extended| switch (extended) {
- inline else => |code| return @field(Error, @tagName(code)),
- };
+ fn orElse(self: Result, function: anytype, args: anytype) Result {
+ comptime { assert(@typeInfo(@TypeOf(function)).@"fn".return_type == c_int); }
- const value: Result = .from(sqlite.sqlite3_extended_errcode(handle));
-
- if (std.enums.fromInt(Extended, @intFromEnum(value))) |extended| switch (extended) {
- inline else => |code| return @field(Error, @tagName(code)),
- } else switch (self.asPrimary()) {
- inline else => |code| return @field(Error, @tagName(code)),
- }
+ return switch (self) {
+ .ok => self,
+ .err => .from(@call(.auto, function, args)),
+ };
}
- /// Returns the primary result code.
- fn asPrimary(self: Result) Primary {
- return @enumFromInt(0x000000FF & @intFromEnum(self));
+ fn toErrorUnion(self: Result) Error!Ok {
+ return switch (self) {
+ .ok => |okay| okay,
+ .err => |error_name| error_name,
+ };
}
};
@@ -832,18 +870,25 @@ test {
var db: Database(Schema) = try .init(.temp_in_memory);
defer assert(db.deinit() == .ok);
- const query = try 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 })
- .prepare(allocator);
+ 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();
- _ = query;
+ // var rows = statement.iterator();
+ //
+ // while (rows.next()) |row| {
+ // // TODO: row contains row_data,col_idx,col_name
+ // _ = row;
+ // }
}
// test {