fediglam/src/sql/common.zig

45 lines
1.5 KiB
Zig

const std = @import("std");
const util = @import("util");
const Uuid = util.Uuid;
const DateTime = util.DateTime;
const Allocator = std.mem.Allocator;
// Turns a value into its appropriate textual value (or null)
// as appropriate using the given arena allocator
pub fn prepareParamText(arena: std.heap.ArenaAllocator, val: anytype) !?[:0]const u8 {
if (comptime std.meta.trait.isZigString(@TypeOf(val))) return val;
return switch (@TypeOf(val)) {
[:0]u8, [:0]const u8 => val,
[]const u8, []u8 => try std.cstr.addNullByte(val),
DateTime, Uuid => try std.fmt.allocPrintZ(arena.allocator(), "{}", .{val}),
else => |T| switch (@typeInfo(T)) {
.Enum => return @tagName(val),
.Optional => if (val) |v| try prepareParamText(arena, v) else null,
.Int => try std.fmt.allocPrintZ(arena.allocator(), "{}", .{val}),
else => @compileError("Unsupported Type " ++ @typeName(T)),
},
};
}
fn parseEnum(comptime T: type, _: []const u8) !T {
@panic("not implemented");
}
// Parse a (not-null) value from a string
pub fn parseValueNotNull(alloc: ?Allocator, comptime T: type, str: []const u8) !T {
return switch (T) {
Uuid => Uuid.parse(str),
DateTime => DateTime.parse(str),
[]u8, []const u8 => if (alloc) |a| util.deepClone(a, str) else return error.AllocatorRequired,
else => switch (@typeInfo(T)) {
.Enum => parseEnum(T, str),
else => @compileError("Type " ++ @typeName(T) ++ " not supported"),
},
};
}