diff --git a/src/migrate.zig b/src/migrate.zig index b2729d8..45e27b6 100644 --- a/src/migrate.zig +++ b/src/migrate.zig @@ -40,7 +40,7 @@ pub fn migrate(allocator: std.mem.Allocator, filename: [:0]const u8, ddl: []cons fn migrateObjects(db: *Session, pristine: *Session, kind: []const u8) !void { for (try sqlite_master.objects(pristine, kind)) |obj| { // Check if object exists - const curr = try db.query(sqlite_master).where(.type, kind).firstWhere(.name, obj.name) orelse { + const curr = try db.query(sqlite_master).where(.type, kind).findBy(.name, obj.name) orelse { logObject(obj, .create); try db.conn.execAll(obj.sql); continue; @@ -94,7 +94,7 @@ fn migrateObjects(db: *Session, pristine: *Session, kind: []const u8) !void { // Now we can check for extraneous objects and drop them for (try sqlite_master.objects(db, kind)) |obj| { - if (try pristine.query(sqlite_master).where(.type, kind).firstWhere(.name, obj.name) == null) { + if (try pristine.query(sqlite_master).where(.type, kind).findBy(.name, obj.name) == null) { logObject(obj, .drop); const drop_sql = try std.fmt.allocPrint(db.arena, "DROP {s} {s}", .{ kind, obj.name }); @@ -116,6 +116,6 @@ const sqlite_master = struct { return db.query(sqlite_master) .where(.type, kind) .whereRaw("name NOT LIKE ?", .{"sqlite_%"}) - .all(); + .findAll(); } }; diff --git a/src/query.zig b/src/query.zig index d9d7d5c..458eaaa 100644 --- a/src/query.zig +++ b/src/query.zig @@ -113,18 +113,22 @@ pub fn Query(comptime T: type, comptime R: type) type { try stmt.exec(); } - pub fn first(self: Q) !?R { + pub fn find(self: Q, id: std.meta.FieldType(T, .id)) !?R { + return self.findBy(.id, id); + } + + pub fn findBy(self: Q, comptime col: Col, val: std.meta.FieldType(T, col)) !?R { + return self.where(col, val).findFirst(); + } + + pub fn findFirst(self: Q) !?R { var stmt = try self.limit(1).prepare(); defer stmt.deinit(); return stmt.row(R); } - pub fn firstWhere(self: Q, comptime col: Col, val: std.meta.FieldType(T, col)) !?R { - return self.where(col, val).first(); - } - - pub fn all(self: Q) ![]const R { + pub fn findAll(self: Q) ![]const R { var stmt = try self.prepare(); defer stmt.deinit(); diff --git a/src/session.zig b/src/session.zig index 425d3b3..bf1ca39 100644 --- a/src/session.zig +++ b/src/session.zig @@ -66,7 +66,7 @@ pub const Session = struct { /// Find a record by its primary key. pub fn find(self: *Session, comptime T: type, id: std.meta.FieldType(T, .id)) !?T { - return self.query(T).firstWhere(.id, id); + return self.query(T).find(id); } /// Insert a new record. @@ -131,7 +131,7 @@ test "db.query(T).findAll()" { try t.expectEqualDeep(&[_]Person{ .{ .id = 1, .name = "Alice" }, .{ .id = 2, .name = "Bob" }, - }, db.query(Person).all()); + }, db.query(Person).findAll()); } test "db.find(T, id)" {