fediglam/src/api/services/notes.zig

60 lines
1.2 KiB
Zig
Raw Normal View History

2022-09-08 07:52:23 +00:00
const std = @import("std");
const util = @import("util");
2022-10-02 05:18:24 +00:00
const sql = @import("sql");
2022-09-08 07:52:23 +00:00
const Uuid = util.Uuid;
const DateTime = util.DateTime;
pub const Note = struct {
id: Uuid,
author_id: Uuid,
content: []const u8,
created_at: DateTime,
};
2022-10-02 05:18:24 +00:00
pub const CreateError = error{
DatabaseFailure,
2022-09-08 07:52:23 +00:00
};
pub fn create(
db: anytype,
author: Uuid,
content: []const u8,
2022-10-02 05:18:24 +00:00
alloc: std.mem.Allocator,
) CreateError!Uuid {
2022-10-08 20:47:54 +00:00
const id = Uuid.randV4(util.getThreadPrng());
2022-09-08 07:52:23 +00:00
2022-10-02 05:18:24 +00:00
db.insert("note", .{
2022-09-08 07:52:23 +00:00
.id = id,
.author_id = author,
.content = content,
.created_at = DateTime.now(),
2022-10-02 05:18:24 +00:00
}, alloc) catch return error.DatabaseFailure;
2022-09-08 07:52:23 +00:00
return id;
}
2022-10-02 05:18:24 +00:00
pub const GetError = error{
DatabaseFailure,
NotFound,
};
2022-10-08 07:51:22 +00:00
const selectStarFromNote = std.fmt.comptimePrint(
\\SELECT {s}
\\FROM note
\\
, .{util.comptimeJoin(",", std.meta.fieldNames(Note))});
2022-10-02 05:18:24 +00:00
pub fn get(db: anytype, id: Uuid, alloc: std.mem.Allocator) GetError!Note {
return db.queryRow(
Note,
2022-10-08 07:51:22 +00:00
selectStarFromNote ++
2022-10-02 05:18:24 +00:00
\\WHERE id = $1
\\LIMIT 1
,
2022-09-08 07:52:23 +00:00
.{id},
alloc,
2022-10-02 05:18:24 +00:00
) catch |err| switch (err) {
error.NoRows => error.NotFound,
else => error.DatabaseFailure,
2022-09-08 07:52:23 +00:00
};
}