prefect server in zig
at main 75 lines 2.7 kB view raw
1const std = @import("std"); 2const Allocator = std.mem.Allocator; 3const backend = @import("backend.zig"); 4const log = @import("../logging.zig"); 5 6const Col = enum(u8) { id = 0, created = 1, flow_run_id = 2, type_ = 3, name = 4, timestamp = 5 }; 7 8pub const FlowRunStateRow = struct { 9 id: []const u8, 10 created: []const u8, 11 flow_run_id: []const u8, 12 type: []const u8, 13 name: []const u8, 14 timestamp: []const u8, 15 16 pub fn toJson(self: FlowRunStateRow, alloc: Allocator) ![]const u8 { 17 var output: std.Io.Writer.Allocating = .init(alloc); 18 var jw: std.json.Stringify = .{ .writer = &output.writer }; 19 try jw.beginObject(); 20 try jw.objectField("id"); 21 try jw.write(self.id); 22 try jw.objectField("created"); 23 try jw.write(self.created); 24 try jw.objectField("flow_run_id"); 25 try jw.write(self.flow_run_id); 26 try jw.objectField("type"); 27 try jw.write(self.type); 28 try jw.objectField("name"); 29 try jw.write(self.name); 30 try jw.objectField("timestamp"); 31 try jw.write(self.timestamp); 32 try jw.endObject(); 33 return output.toOwnedSlice(); 34 } 35}; 36 37fn rowFromResult(alloc: Allocator, r: anytype) !FlowRunStateRow { 38 return FlowRunStateRow{ 39 .id = try alloc.dupe(u8, r.text(@intFromEnum(Col.id))), 40 .created = try alloc.dupe(u8, r.text(@intFromEnum(Col.created))), 41 .flow_run_id = try alloc.dupe(u8, r.text(@intFromEnum(Col.flow_run_id))), 42 .type = try alloc.dupe(u8, r.text(@intFromEnum(Col.type_))), 43 .name = try alloc.dupe(u8, r.text(@intFromEnum(Col.name))), 44 .timestamp = try alloc.dupe(u8, r.text(@intFromEnum(Col.timestamp))), 45 }; 46} 47 48pub fn getById(alloc: Allocator, id: []const u8) !?FlowRunStateRow { 49 var r = backend.db.row( 50 "SELECT id, created, flow_run_id, type, name, timestamp FROM flow_run_state WHERE id = ?", 51 .{id}, 52 ) catch return null; 53 if (r) |*row| { 54 defer row.deinit(); 55 return try rowFromResult(alloc, row); 56 } 57 return null; 58} 59 60pub fn listByFlowRunId(alloc: Allocator, flow_run_id: []const u8) ![]FlowRunStateRow { 61 var results = std.ArrayListUnmanaged(FlowRunStateRow){}; 62 errdefer results.deinit(alloc); 63 var rows = backend.db.query( 64 "SELECT id, created, flow_run_id, type, name, timestamp FROM flow_run_state WHERE flow_run_id = ? ORDER BY timestamp ASC", 65 .{flow_run_id}, 66 ) catch |err| { 67 log.err("database", "list flow_run_states error: {}", .{err}); 68 return err; 69 }; 70 defer rows.deinit(); 71 while (rows.next()) |r| { 72 try results.append(alloc, try rowFromResult(alloc, &r)); 73 } 74 return results.toOwnedSlice(alloc); 75}