summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEkaitz Zarraga <ekaitz@elenq.tech>2024-07-29 22:58:30 +0200
committerEkaitz Zarraga <ekaitz@elenq.tech>2024-07-29 22:58:30 +0200
commitdf5e800284b708cce97c309ccf3ac04743551b32 (patch)
treebd2b3baef96462b6cb188437f7b622e989a785f7
parentcf908fa9cadcf4bc29d65bfa89f1ec1b5d7c2d4f (diff)
More on the Database support
-rw-r--r--src/db.zig59
1 files changed, 57 insertions, 2 deletions
diff --git a/src/db.zig b/src/db.zig
index 751a50d..4c4da8d 100644
--- a/src/db.zig
+++ b/src/db.zig
@@ -1,11 +1,40 @@
+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{
+ pub fn init(db: Self) !Connection {
var conn: Connection = undefined;
if( c.duckdb_connect(db._db, &conn._conn) == c.DuckDBError ){
return error.DuckDBError;
@@ -13,9 +42,18 @@ const Connection = struct {
return conn;
}
- pub fn deinit(self: *Connection) void{
+ 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;
+ }
};
@@ -45,3 +83,20 @@ test "Open and connect" {
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());
+}