diff options
| -rw-r--r-- | sqlite.zig | 27 |
1 files changed, 27 insertions, 0 deletions
| @@ -125,6 +125,13 @@ pub const Db = struct { | |||
| 125 | try stmt.exec(values); | 125 | try stmt.exec(values); |
| 126 | } | 126 | } |
| 127 | 127 | ||
| 128 | /// one is a convenience function which prepares a statement and reads a single row from the result set. | ||
| 129 | pub fn one(self: *Self, comptime Type: type, comptime query: []const u8, options: anytype, values: anytype) !?Type { | ||
| 130 | var stmt = try self.prepare(query); | ||
| 131 | defer stmt.deinit(); | ||
| 132 | return try stmt.one(Type, options, values); | ||
| 133 | } | ||
| 134 | |||
| 128 | /// prepare prepares a statement for the `query` provided. | 135 | /// prepare prepares a statement for the `query` provided. |
| 129 | /// | 136 | /// |
| 130 | /// The query is analysed at comptime to search for bind markers. | 137 | /// The query is analysed at comptime to search for bind markers. |
| @@ -853,6 +860,26 @@ test "sqlite: read a single user into a struct" { | |||
| 853 | testing.expectEqualStrings(test_users[0].name, row.name); | 860 | testing.expectEqualStrings(test_users[0].name, row.name); |
| 854 | testing.expectEqual(test_users[0].age, row.age); | 861 | testing.expectEqual(test_users[0].age, row.age); |
| 855 | } | 862 | } |
| 863 | |||
| 864 | // Read a row with db.one() | ||
| 865 | { | ||
| 866 | var row = try db.one( | ||
| 867 | struct { | ||
| 868 | id: usize, | ||
| 869 | name: Text, | ||
| 870 | age: usize, | ||
| 871 | }, | ||
| 872 | "SELECT id, name, age FROM user WHERE id = ?{usize}", | ||
| 873 | .{ .allocator = &arena.allocator }, | ||
| 874 | .{@as(usize, 20)}, | ||
| 875 | ); | ||
| 876 | testing.expect(row != null); | ||
| 877 | |||
| 878 | const exp = test_users[0]; | ||
| 879 | testing.expectEqual(exp.id, row.?.id); | ||
| 880 | testing.expectEqualStrings(exp.name, row.?.name.data); | ||
| 881 | testing.expectEqual(exp.age, row.?.age); | ||
| 882 | } | ||
| 856 | } | 883 | } |
| 857 | 884 | ||
| 858 | test "sqlite: read all users into a struct" { | 885 | test "sqlite: read all users into a struct" { |