From 9a2ed3ddf6ebbcc46d0aea394ca92b76f65e16e7 Mon Sep 17 00:00:00 2001
From: Ekaitz Zarraga <ekaitz@elenq.tech>
Date: Tue, 30 Jul 2024 00:19:50 +0200
Subject: No way to know length! try with `duckdb_result_chunk_count` and so

---
 src/db.zig | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)

(limited to 'src')

diff --git a/src/db.zig b/src/db.zig
index 1b9f653..b0aa63a 100644
--- a/src/db.zig
+++ b/src/db.zig
@@ -1,4 +1,5 @@
 const std = @import("std");
+const assert = std.debug.assert;
 const c = @cImport({
     @cInclude("duckdb.h");
 });
@@ -8,12 +9,23 @@ const Result = struct {
     _res:   c.duckdb_result,
     _chunk: c.duckdb_data_chunk,
 
+    pub fn init() Result {
+        return .{
+            ._res   = undefined,
+            ._chunk = null
+        };
+    }
     pub fn deinit(self: *Result) void {
         c.duckdb_destroy_result(&self._res);
         c.duckdb_destroy_data_chunk(&self._chunk);
     }
 
-    pub fn getRowCount(self: Result) usize {
+    /// 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: Result) usize {
+        if (self._chunk != null) {
+            return 0;
+        }
         return c.duckdb_data_chunk_get_size(self._chunk);
     }
 
@@ -21,7 +33,13 @@ const Result = struct {
         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.
     pub fn fetchDataChunk(self: *Result) void{
+        if (self._chunk != null){
+            c.duckdb_destroy_data_chunk(&self._chunk);
+        }
         self._chunk = c.duckdb_fetch_chunk(self._res);
     }
 
@@ -47,7 +65,7 @@ const Connection = struct {
     }
 
     pub fn query(self: *Connection, q: [*c]const u8) !Result{
-        var result: Result = undefined;
+        var result = Result.init();
         const state = c.duckdb_query(self._conn, q, &result._res);
         if ( state == c.DuckDBError){
             return error.DuckDBError;
@@ -96,6 +114,5 @@ test "Query size" {
     var result = try connection.query("SELECT * FROM integers;");
     defer result.deinit();
 
-    try std.testing.expect(3 == result.getRowCount());
     try std.testing.expect(2 == result.getColumnCount());
 }
-- 
cgit v1.2.3