Get tags by ID implementation

This commit is contained in:
Dendy 2022-10-24 02:49:59 +02:00
parent 52a626fe12
commit 6b5c5aefdc
2 changed files with 18 additions and 0 deletions

View File

@ -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

View File

@ -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()});
}