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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
const std = @import("std");
const c = @cImport({
@cInclude("duckdb.h");
});
const DataChunk = struct {
_chunk: c.duckdb_data_chunk,
pub fn deinit(self: * DataChunk) void {
c.duckdb_destroy_data_chunk(&self._chunk);
}
pub fn getSize(self: DataChunk) usize {
return c.duckdb_data_chunk_get_size(self._chunk);
}
};
const Result = struct {
_res: c.duckdb_result,
pub fn deinit(self: *Result) void {
c.duckdb_destroy_result(&self._res);
}
pub fn fetchDataChunk(self: Result) ?DataChunk{
var chunk : DataChunk = undefined;
chunk._chunk = c.duckdb_fetch_chunk(self._res);
return chunk;
}
};
const Connection = struct {
_conn: c.duckdb_connection,
pub fn init(db: Self) !Connection {
var conn: Connection = undefined;
if( c.duckdb_connect(db._db, &conn._conn) == c.DuckDBError ){
return error.DuckDBError;
}
return conn;
}
pub fn deinit(self: *Connection) void {
c.duckdb_disconnect(&self._conn);
}
pub fn query(self: *Connection, q: [*c]const u8) !Result{
var result: Result = undefined;
const state = c.duckdb_query(self._conn, q, &result._res);
if ( state == c.DuckDBError){
return error.DuckDBError;
}
return result;
}
};
pub const Self = @This();
_db: c.duckdb_database,
pub fn init(file: [*c]const u8) !Self{
var db : Self = undefined;
if (c.duckdb_open(file, &db._db) == c.DuckDBError) {
return error.DuckDBError;
}
return db;
}
pub fn deinit(self: *Self) void{
c.duckdb_close(&self._db);
}
pub fn connect(self: Self) !Connection {
return Connection.init(self);
}
test "Open and connect" {
var database = try Self.init(":memory:");
defer database.deinit();
var connection = try database.connect();
defer connection.deinit();
}
test "Query size" {
var database = try Self.init(":memory:");
defer database.deinit();
var connection = try database.connect();
defer connection.deinit();
_ = try connection.query("CREATE TABLE integers (i INTEGER, j INTEGER);");
_ = try connection.query("INSERT INTO integers VALUES (3, 4), (5, 6), (7, NULL);");
var result = try connection.query("SELECT * FROM integers;");
defer result.deinit();
var chunk = result.fetchDataChunk() orelse return error.DuckDBError;
defer chunk.deinit();
try std.testing.expect(3 == chunk.getSize());
}
|