diff --git a/src/Item.zig b/src/Item.zig index ab6f3ab..9b67186 100644 --- a/src/Item.zig +++ b/src/Item.zig @@ -57,6 +57,21 @@ pub fn persist(self: *Self, db: *sqlite.Db) !void { } } +pub fn getTagsById(id: i64, db: *sqlite.Db, allocator: std.mem.Allocator) !?[]Tag { + var stmt = try db.prepare("SELECT tag, value FROM item_tag WHERE item = ?"); + defer stmt.deinit(); + + const res = try stmt.all(Tag, allocator, .{}, .{ .id = id }); + + if (res.len < 1) { + // Detect wether it returns 0 because it has no tags or because it doesn't exist + const exists = (try db.one(i64, "SELECT COUNT(id) FROM item WHERE id = ?", .{}, .{id})).?; + return if (exists == 0) null else res; + } + + return res; +} + /// Convert into a JSON object. A call to deinit() is necessary from the caller's side pub fn toJson(self: Self) json.Obj { // Main object diff --git a/src/main.zig b/src/main.zig index 588bd49..a065774 100644 --- a/src/main.zig +++ b/src/main.zig @@ -46,5 +46,8 @@ pub fn main() !void { var jobj = item2.toJson(); defer jobj.deinit(); + const tags = try Item.getTagsById(item2.id.?, &db, allocator); + std.debug.print("{any}\n", .{tags}); + std.debug.print("{s}\n", .{jobj.toString()}); }