laminar-db 0.18.11

Unified database facade for LaminarDB
Documentation
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! FFI query result functions.
//!
//! Provides `extern "C"` wrappers for query result operations.

use std::ptr;

use arrow::array::RecordBatch;

use crate::api::{QueryResult, QueryStream};

use super::error::{clear_last_error, set_last_error, LAMINAR_ERR_NULL_POINTER, LAMINAR_OK};
use super::schema::LaminarSchema;

/// Opaque query result handle for FFI.
///
/// Contains materialized query results (all batches in memory).
#[repr(C)]
pub struct LaminarQueryResult {
    inner: QueryResult,
}

impl LaminarQueryResult {
    /// Create from `QueryResult`.
    pub(crate) fn new(result: QueryResult) -> Self {
        Self { inner: result }
    }
}

/// Opaque query stream handle for FFI.
///
/// Provides streaming access to query results.
#[repr(C)]
pub struct LaminarQueryStream {
    inner: QueryStream,
}

impl LaminarQueryStream {
    /// Create from `QueryStream`.
    pub(crate) fn new(stream: QueryStream) -> Self {
        Self { inner: stream }
    }
}

/// Opaque record batch handle for FFI.
///
/// Wraps an Arrow `RecordBatch`. Create from query results, free with `laminar_batch_free`.
#[repr(C)]
pub struct LaminarRecordBatch {
    inner: RecordBatch,
}

impl LaminarRecordBatch {
    /// Create from `RecordBatch`.
    pub(crate) fn new(batch: RecordBatch) -> Self {
        Self { inner: batch }
    }

    /// Consume and return inner `RecordBatch`.
    pub(crate) fn into_inner(self) -> RecordBatch {
        self.inner
    }

    /// Get reference to inner `RecordBatch`.
    #[allow(dead_code)]
    pub(crate) fn inner(&self) -> &RecordBatch {
        &self.inner
    }
}

// ============================================================================
// Query Result Functions
// ============================================================================

/// Get the schema from a query result.
///
/// # Arguments
///
/// * `result` - Query result handle
/// * `out` - Pointer to receive schema handle
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `result` must be a valid query result handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_result_schema(
    result: *mut LaminarQueryResult,
    out: *mut *mut LaminarSchema,
) -> i32 {
    clear_last_error();

    if result.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: result is non-null (checked above)
    let schema = unsafe { (*result).inner.schema() };
    let handle = Box::new(LaminarSchema::new(schema));

    // SAFETY: out is non-null (checked above)
    unsafe { *out = Box::into_raw(handle) };
    LAMINAR_OK
}

/// Get the total row count from a query result.
///
/// # Arguments
///
/// * `result` - Query result handle
/// * `out` - Pointer to receive row count
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `result` must be a valid query result handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_result_num_rows(
    result: *mut LaminarQueryResult,
    out: *mut usize,
) -> i32 {
    clear_last_error();

    if result.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: result and out are non-null (checked above)
    unsafe {
        *out = (*result).inner.num_rows();
    }
    LAMINAR_OK
}

/// Get the number of batches in a query result.
///
/// # Arguments
///
/// * `result` - Query result handle
/// * `out` - Pointer to receive batch count
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `result` must be a valid query result handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_result_num_batches(
    result: *mut LaminarQueryResult,
    out: *mut usize,
) -> i32 {
    clear_last_error();

    if result.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: result and out are non-null (checked above)
    unsafe {
        *out = (*result).inner.num_batches();
    }
    LAMINAR_OK
}

/// Get a batch by index from a query result.
///
/// # Arguments
///
/// * `result` - Query result handle
/// * `index` - Batch index (0-based)
/// * `out` - Pointer to receive batch handle
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `result` must be a valid query result handle
/// * `index` must be less than the batch count
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_result_get_batch(
    result: *mut LaminarQueryResult,
    index: usize,
    out: *mut *mut LaminarRecordBatch,
) -> i32 {
    clear_last_error();

    if result.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: result is non-null (checked above)
    let result_ref = unsafe { &(*result).inner };

    if let Some(batch) = result_ref.batch(index) {
        let handle = Box::new(LaminarRecordBatch::new(batch.clone()));
        // SAFETY: out is non-null (checked above)
        unsafe { *out = Box::into_raw(handle) };
        LAMINAR_OK
    } else {
        // Index out of bounds
        // SAFETY: out is non-null
        unsafe { *out = ptr::null_mut() };
        LAMINAR_ERR_NULL_POINTER
    }
}

/// Free a query result handle.
///
/// # Arguments
///
/// * `result` - Query result handle to free
///
/// # Safety
///
/// `result` must be a valid handle from a laminar function, or NULL.
#[no_mangle]
pub unsafe extern "C" fn laminar_result_free(result: *mut LaminarQueryResult) {
    if !result.is_null() {
        // SAFETY: result is non-null and was allocated by Box
        drop(unsafe { Box::from_raw(result) });
    }
}

// ============================================================================
// Query Stream Functions
// ============================================================================

/// Get the schema from a query stream.
///
/// # Arguments
///
/// * `stream` - Query stream handle
/// * `out` - Pointer to receive schema handle
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `stream` must be a valid query stream handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_schema(
    stream: *mut LaminarQueryStream,
    out: *mut *mut LaminarSchema,
) -> i32 {
    clear_last_error();

    if stream.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: stream is non-null (checked above)
    let schema = unsafe { (*stream).inner.schema() };
    let handle = Box::new(LaminarSchema::new(schema));

    // SAFETY: out is non-null (checked above)
    unsafe { *out = Box::into_raw(handle) };
    LAMINAR_OK
}

/// Get the next batch from a query stream (blocking).
///
/// # Arguments
///
/// * `stream` - Query stream handle
/// * `out` - Pointer to receive batch handle (NULL when stream exhausted)
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `stream` must be a valid query stream handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_next(
    stream: *mut LaminarQueryStream,
    out: *mut *mut LaminarRecordBatch,
) -> i32 {
    clear_last_error();

    if stream.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: stream is non-null (checked above)
    let stream_ref = unsafe { &mut (*stream).inner };

    match stream_ref.next() {
        Ok(Some(batch)) => {
            let handle = Box::new(LaminarRecordBatch::new(batch));
            // SAFETY: out is non-null (checked above)
            unsafe { *out = Box::into_raw(handle) };
            LAMINAR_OK
        }
        Ok(None) => {
            // Stream exhausted
            // SAFETY: out is non-null
            unsafe { *out = ptr::null_mut() };
            LAMINAR_OK
        }
        Err(e) => {
            // SAFETY: out is non-null
            unsafe { *out = ptr::null_mut() };
            let code = e.code();
            set_last_error(e);
            code
        }
    }
}

/// Try to get the next batch from a query stream (non-blocking).
///
/// # Arguments
///
/// * `stream` - Query stream handle
/// * `out` - Pointer to receive batch handle (NULL if none available)
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `stream` must be a valid query stream handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_try_next(
    stream: *mut LaminarQueryStream,
    out: *mut *mut LaminarRecordBatch,
) -> i32 {
    clear_last_error();

    if stream.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: stream is non-null (checked above)
    let stream_ref = unsafe { &mut (*stream).inner };

    match stream_ref.try_next() {
        Ok(Some(batch)) => {
            let handle = Box::new(LaminarRecordBatch::new(batch));
            // SAFETY: out is non-null (checked above)
            unsafe { *out = Box::into_raw(handle) };
            LAMINAR_OK
        }
        Ok(None) => {
            // No batch available
            // SAFETY: out is non-null
            unsafe { *out = ptr::null_mut() };
            LAMINAR_OK
        }
        Err(e) => {
            // SAFETY: out is non-null
            unsafe { *out = ptr::null_mut() };
            let code = e.code();
            set_last_error(e);
            code
        }
    }
}

/// Check if a query stream is still active.
///
/// # Arguments
///
/// * `stream` - Query stream handle
/// * `out` - Pointer to receive result (true if active)
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `stream` must be a valid query stream handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_is_active(
    stream: *mut LaminarQueryStream,
    out: *mut bool,
) -> i32 {
    clear_last_error();

    if stream.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: stream and out are non-null (checked above)
    unsafe {
        *out = (*stream).inner.is_active();
    }
    LAMINAR_OK
}

/// Cancel a query stream.
///
/// # Arguments
///
/// * `stream` - Query stream handle
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// `stream` must be a valid query stream handle.
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_cancel(stream: *mut LaminarQueryStream) -> i32 {
    clear_last_error();

    if stream.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: stream is non-null (checked above)
    unsafe {
        (*stream).inner.cancel();
    }
    LAMINAR_OK
}

/// Free a query stream handle.
///
/// # Arguments
///
/// * `stream` - Query stream handle to free
///
/// # Safety
///
/// `stream` must be a valid handle from a laminar function, or NULL.
#[no_mangle]
pub unsafe extern "C" fn laminar_stream_free(stream: *mut LaminarQueryStream) {
    if !stream.is_null() {
        // SAFETY: stream is non-null and was allocated by Box
        drop(unsafe { Box::from_raw(stream) });
    }
}

// ============================================================================
// Record Batch Functions
// ============================================================================

/// Get the number of rows in a record batch.
///
/// # Arguments
///
/// * `batch` - Record batch handle
/// * `out` - Pointer to receive row count
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `batch` must be a valid record batch handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_batch_num_rows(
    batch: *mut LaminarRecordBatch,
    out: *mut usize,
) -> i32 {
    clear_last_error();

    if batch.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: batch and out are non-null (checked above)
    unsafe {
        *out = (*batch).inner.num_rows();
    }
    LAMINAR_OK
}

/// Get the number of columns in a record batch.
///
/// # Arguments
///
/// * `batch` - Record batch handle
/// * `out` - Pointer to receive column count
///
/// # Returns
///
/// `LAMINAR_OK` on success, or an error code.
///
/// # Safety
///
/// * `batch` must be a valid record batch handle
/// * `out` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn laminar_batch_num_columns(
    batch: *mut LaminarRecordBatch,
    out: *mut usize,
) -> i32 {
    clear_last_error();

    if batch.is_null() || out.is_null() {
        return LAMINAR_ERR_NULL_POINTER;
    }

    // SAFETY: batch and out are non-null (checked above)
    unsafe {
        *out = (*batch).inner.num_columns();
    }
    LAMINAR_OK
}

/// Free a record batch handle.
///
/// # Arguments
///
/// * `batch` - Record batch handle to free
///
/// # Safety
///
/// `batch` must be a valid handle from a laminar function, or NULL.
#[no_mangle]
pub unsafe extern "C" fn laminar_batch_free(batch: *mut LaminarRecordBatch) {
    if !batch.is_null() {
        // SAFETY: batch is non-null and was allocated by Box
        drop(unsafe { Box::from_raw(batch) });
    }
}

#[cfg(test)]
#[allow(clippy::borrow_as_ptr)]
mod tests {
    use super::*;
    use crate::ffi::connection::{laminar_close, laminar_open, laminar_query};
    use crate::ffi::schema::laminar_schema_free;

    #[test]
    fn test_result_schema() {
        let mut conn: *mut super::super::connection::LaminarConnection = ptr::null_mut();
        let mut result: *mut LaminarQueryResult = ptr::null_mut();
        let mut schema: *mut LaminarSchema = ptr::null_mut();

        // SAFETY: Test code with valid pointers
        unsafe {
            laminar_open(&mut conn);

            // Create table (not source) for point-in-time queries
            let create_sql = b"CREATE TABLE query_test (id BIGINT, val DOUBLE)\0";
            crate::ffi::connection::laminar_execute(
                conn,
                create_sql.as_ptr().cast(),
                ptr::null_mut(),
            );

            let query_sql = b"SELECT * FROM query_test\0";
            let rc = laminar_query(conn, query_sql.as_ptr().cast(), &mut result);
            assert_eq!(rc, LAMINAR_OK);

            // Get schema
            let rc = laminar_result_schema(result, &mut schema);
            assert_eq!(rc, LAMINAR_OK);
            assert!(!schema.is_null());

            laminar_schema_free(schema);
            laminar_result_free(result);
            laminar_close(conn);
        }
    }

    #[test]
    fn test_result_counts() {
        let mut conn: *mut super::super::connection::LaminarConnection = ptr::null_mut();
        let mut result: *mut LaminarQueryResult = ptr::null_mut();

        // SAFETY: Test code with valid pointers
        unsafe {
            laminar_open(&mut conn);

            // Create table (not source) for point-in-time queries
            let create_sql = b"CREATE TABLE count_test (id BIGINT)\0";
            crate::ffi::connection::laminar_execute(
                conn,
                create_sql.as_ptr().cast(),
                ptr::null_mut(),
            );

            let query_sql = b"SELECT * FROM count_test\0";
            laminar_query(conn, query_sql.as_ptr().cast(), &mut result);

            let mut num_rows: usize = 999;
            let rc = laminar_result_num_rows(result, &mut num_rows);
            assert_eq!(rc, LAMINAR_OK);
            assert_eq!(num_rows, 0); // Empty table

            let mut num_batches: usize = 999;
            let rc = laminar_result_num_batches(result, &mut num_batches);
            assert_eq!(rc, LAMINAR_OK);

            laminar_result_free(result);
            laminar_close(conn);
        }
    }

    #[test]
    fn test_batch_free_null() {
        // SAFETY: Testing null handling
        unsafe {
            laminar_batch_free(ptr::null_mut());
        }
        // Should not crash
    }
}