Skip to content

Commit

Permalink
session: update, remove create() in favor of insert() with Id(T)
Browse files Browse the repository at this point in the history
  • Loading branch information
cztomsik committed Aug 22, 2024
1 parent db55b7b commit 6b003e1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
25 changes: 8 additions & 17 deletions src/session.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
};
Expand Down Expand Up @@ -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());
}
Expand Down
9 changes: 9 additions & 0 deletions src/util.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 6b003e1

Please sign in to comment.