diff --git a/src/session.zig b/src/session.zig index b6d26c9..5aa822a 100644 --- a/src/session.zig +++ b/src/session.zig @@ -60,32 +60,23 @@ 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 { + pub fn find(self: *Session, comptime T: type, id: util.Id(T)) !?T { return self.query(T).find(id); } - /// Create a new record and return it. - pub fn create(self: *Session, comptime T: type, data: anytype) !T { - try self.insert(T, data); - return try self.find(T, @intCast(try self.conn.lastInsertRowId())) orelse error.NotFound; - } - - /// Insert a new record. - pub fn insert(self: *Session, comptime T: type, data: anytype) !void { - comptime util.checkFields(T, @TypeOf(data)); - - return self.query(T).insert(data); + /// Insert a new record and return its primary key + pub fn insert(self: *Session, comptime T: type, data: anytype) !util.Id(T) { + try self.query(T).insert(data); // TODO: returning id? + return @intCast(try self.conn.lastInsertRowId()); } /// Update a record by its primary key. - pub fn update(self: *Session, comptime T: type, id: std.meta.FieldType(T, .id), data: anytype) !void { - comptime util.checkFields(T, @TypeOf(data)); - + pub fn update(self: *Session, comptime T: type, id: util.Id(T), data: anytype) !void { return self.query(T).where(.id, id).update(data); } /// Delete a record by its primary key. - pub fn delete(self: *Session, comptime T: type, id: std.meta.FieldType(T, .id)) !void { + pub fn delete(self: *Session, comptime T: type, id: util.Id(T)) !void { try self.query(T).where(.id, id).delete(); } }; @@ -149,7 +140,7 @@ test "db.insert(T, data)" { var db = try open(); defer close(&db); - try db.insert(Person, .{ .name = "Charlie" }); + _ = try db.insert(Person, .{ .name = "Charlie" }); try t.expectEqualDeep(3, db.conn.lastInsertRowId()); try t.expectEqual(1, db.conn.rowsAffected()); } diff --git a/src/util.zig b/src/util.zig index 2713369..1d564b6 100644 --- a/src/util.zig +++ b/src/util.zig @@ -11,6 +11,15 @@ pub const log = if (builtin.is_test) struct { // zig build test captures stderr } } else std.log.scoped(.fridge); +pub fn Id(comptime T: type) type { + const Col = std.meta.FieldType(T, .id); + + return switch (@typeInfo(Col)) { + .Optional => |o| o.child, + else => Col, + }; +} + pub fn tableName(comptime T: type) []const u8 { return comptime brk: { if (@hasDecl(T, "sql_table_name")) break :brk T.sql_table_name;