const std = @import("std"); const sqlite = @import("sqlite"); const assert = std.debug.assert; 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; inline for (&table_names, &table_types, &table_values, tables, 0..) |*table_name, *table_type, *table_value, 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; 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"); // TODO: use `column_field_value` to build `CREATE TABLE` SQLite statement column_name.* = column.name; column_type.* = column_field_value.type; column_value.* = column_index; } 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; } const TagTables = @Enum(TagIntTables, .exhaustive, &table_names, &table_values); const Tables = @Union(.auto, TagTables, &table_names, &table_types, &@splat(.{})); return struct { handle: *sqlite.sqlite3, pub const Deinit = enum { ok, 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 Kind = union(enum) { temp_in_memory, temp_on_disk, path: []const u8, }; const Schema = Tables; const Self = @This(); // Source: https://sqlite.org/c3ref/open.html pub fn init(kind: Kind) Error!Self { const name = switch (kind) { .temp_in_memory => ":memory:", .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(); if (primary != .ok) return result.toError(Error, handle); return .{ .handle = handle.? }; } // 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(); if (primary == .busy) return .busy; self.* = undefined; return .ok; } // 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 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 : []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 Schema: type, comptime from: std.meta.Tag(Schema), comptime columns: []const std.meta.Tag(@FieldType(Schema, @tagName(from)))) type { if (columns.len == 0) @compileError("At least one column must be selected"); 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(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 { handle: *sqlite.sqlite3, 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 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) { 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; } // 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 { 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); std.debug.print("{s}\n", .{ string }); } 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(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(';'); } }; } /// 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) { _, // zig fmt: off /// Primary result codes. const Primary = enum(u8) { 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, /// Returns the primary result code as type `T`. fn as(self: Primary, comptime T: type) T { return @as(T, @intFromEnum(self)); } }; /// 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)), }; // 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); } /// 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)), }; 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)), } } /// Returns the primary result code. fn asPrimary(self: Result) Primary { return @enumFromInt(0x000000FF & @intFromEnum(self)); } }; 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 = 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); _ = query; } // 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(); // }