2022-10-20 11:23:15 +00:00
|
|
|
const std = @import("std");
|
|
|
|
const Db = @import("Db.zig");
|
2022-10-21 16:58:44 +00:00
|
|
|
const sqlite = @import("sqlite");
|
|
|
|
const Self = @This();
|
2022-10-20 11:23:15 +00:00
|
|
|
|
2022-10-21 16:58:44 +00:00
|
|
|
pub const Tag = struct{
|
|
|
|
// :0 for C compatility
|
|
|
|
name: [:0]const u8,
|
|
|
|
value: ?[:0]const u8,
|
|
|
|
};
|
|
|
|
|
|
|
|
id: ?i64, // If null, the object hasn't been persisted
|
2022-10-20 11:23:15 +00:00
|
|
|
tags: ?[]Tag,
|
2022-10-21 16:58:44 +00:00
|
|
|
|
|
|
|
pub fn persist(self: *Self, db: *sqlite.Db) !void {
|
|
|
|
///////////////////////////////////
|
|
|
|
// ** Insert item **
|
|
|
|
/////////////////////////////////
|
|
|
|
|
|
|
|
// Insert only if there's no ID.
|
|
|
|
if (self.id == null) {
|
|
|
|
const query = "INSERT INTO item VALUES(NULL);";
|
|
|
|
try db.exec(query, .{}, .{});
|
|
|
|
|
|
|
|
// Update the ID field
|
|
|
|
self.id = try Db.getLastId(db);
|
|
|
|
}
|
|
|
|
|
|
|
|
///////////////////////////////////
|
|
|
|
// ** Insert tags **
|
|
|
|
/////////////////////////////////
|
|
|
|
|
|
|
|
// If the tags haven't been initialized, don't touch anything
|
|
|
|
if (self.tags) |tags| {
|
|
|
|
// TODO: Remove unused tag relations
|
|
|
|
// If the count drops to zero, delete.
|
|
|
|
|
|
|
|
// Create new tags if they don't exist
|
|
|
|
for (tags) |*tags_i| {
|
|
|
|
try db.exec(
|
|
|
|
"INSERT INTO tag (name) VALUES (?);",
|
|
|
|
.{},
|
|
|
|
.{ .name = tags_i.name }
|
|
|
|
);
|
|
|
|
|
|
|
|
try db.exec(
|
|
|
|
"INSERT INTO item_tag (item, tag, value) VALUES (?, ?, ?);",
|
|
|
|
.{},
|
|
|
|
.{ .item = self.id, .tag = tags_i.name, .value = tags_i.value }
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|