-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblob_test.zig
65 lines (49 loc) · 2.15 KB
/
blob_test.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const std = @import("std");
const testing = std.testing;
const sqlite3 = @import("sqlite3.zig");
test "should be able to open blob for reading" {
const allocator = std.testing.allocator;
const db = try sqlite3.open("file::memory:", .{ .ReadWrite = true });
defer db.close() catch {};
// create a temporary table with a blob column
var stmt = try db.prepare("CREATE TABLE x(a)");
_ = try stmt.step();
try stmt.finalize();
stmt = try db.prepare("INSERT INTO x (a) VALUES (?)");
try stmt.bind(.{ .Index = 1 }, sqlite3.blob.ZeroBlob{ .len = 5 });
_ = try stmt.step();
try stmt.finalize();
const id = db.lastInsertRowid(); // rowid of the last inserted row
const blob = try db.openBlob(.main, "x", "a", id, false);
defer blob.close() catch {};
try testing.expectEqual(@as(usize, 5), blob.len());
var buffer = try allocator.alloc(u8, blob.len());
defer allocator.free(buffer);
const n = try blob.read(0, buffer);
try testing.expectEqual(blob.len(), n);
try testing.expectEqualSlices(u8, &[_]u8{ 0, 0, 0, 0, 0 }, buffer);
}
test "should be able to open blob for writing" {
const allocator = std.testing.allocator;
const db = try sqlite3.open("file::memory:", .{ .ReadWrite = true });
defer db.close() catch {};
// create a temporary table with a blob column
var stmt = try db.prepare("CREATE TABLE x(a)");
_ = try stmt.step();
try stmt.finalize();
stmt = try db.prepare("INSERT INTO x (a) VALUES (?)");
try stmt.bind(.{ .Index = 1 }, sqlite3.blob.ZeroBlob{ .len = 5 });
_ = try stmt.step();
try stmt.finalize();
const id = db.lastInsertRowid(); // rowid of the last inserted row
const blob = try db.openBlob(.main, "x", "a", id, true);
defer blob.close() catch {};
try testing.expectEqual(@as(usize, 5), blob.len());
const nw = try blob.write(0, @as([]const u8, "hello"));
try testing.expectEqual(@as(usize, 5), nw);
var buffer = try allocator.alloc(u8, blob.len());
defer allocator.free(buffer);
const nr = try blob.read(0, buffer);
try testing.expectEqual(blob.len(), nr);
try testing.expectEqualSlices(u8, "hello", buffer);
}