summaryrefslogtreecommitdiff
path: root/src/duckdb/Result.zig
blob: 2b5b992ab01aea3dbee9b5a8d79b30dab555ddc3 (plain)
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
const std = @import("std");
const c = @cImport({
    @cInclude("duckdb.h");
});


pub fn Result(comptime T: type) type{

    return struct {
        _res:   c.duckdb_result,
        _chunk: c.duckdb_data_chunk,

        const Self = @This();

        pub fn init(conn : c.duckdb_connection, query: [:0]const u8) !Self {
            var self : Self = .{
                ._res   = undefined,
                ._chunk = null
            };
            const state = c.duckdb_query(conn, query, &self._res);
            if ( state == c.DuckDBError){
                return error.DuckDBError;
            }
            self.fetchDataChunk();

            // Get column vectors
            switch (@typeInfo(T)) {
                .Struct => |v| {
                    const column_count = v.fields.len;
                    var columns : [column_count]c.duckdb_vector = undefined;
                    for (columns, 0..) |_, i| {
                        columns[i] = c.duckdb_data_chunk_get_vector(self._chunk, i);
                    }
                    std.debug.print("{any}", .{columns});
                },
                .Void => {},
                else => @compileError("Expecting struct or void in query result type"),
            }

            return self;
        }
        pub fn deinit(self: *Self) void {
            c.duckdb_destroy_result(&self._res);
            c.duckdb_destroy_data_chunk(&self._chunk);
        }

        /// There's not way to know how many total elements we have, but we can
        /// know how many we have in the current chunk.
        fn getCurrentChunkSize(self: Self) usize {
            if (self._chunk != null) {
                return 0;
            }
            return c.duckdb_data_chunk_get_size(self._chunk);
        }

        pub fn getColumnCount(self: Self) usize {
            return c.duckdb_data_chunk_get_column_count(self._chunk);
        }

        /// This needs to be called repeatedly to obtain the next blocks of
        /// data. There's no way to know how many elements we'll obtain from
        /// it.
        fn fetchDataChunk(self: *Self) void{
            if (self._chunk != null){
                c.duckdb_destroy_data_chunk(&self._chunk);
            }
            self._chunk = c.duckdb_fetch_chunk(self._res);
        }

        pub fn exausted(self: Self) bool{
            return self._chunk != null;
        }

        /// We need some comptime magic to create the output structures from
        /// the T.
        pub fn next(self: *Self) T{
            const result: T = undefined;
            _ = self;
            return result;
        }
    };
}