stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Transaction FFI functions.

use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::panic;
use std::sync::Arc;

use crate::api::Database;
use crate::core::types::IsolationLevel;

use super::types::{StoolapDB, StoolapRows, StoolapStmt, StoolapTx, StoolapValue};
use super::value;
use super::{
    STOOLAP_ERROR, STOOLAP_ISOLATION_READ_COMMITTED, STOOLAP_ISOLATION_SNAPSHOT, STOOLAP_OK,
};

/// Begin a transaction with the default isolation level (READ COMMITTED).
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` pointer.
/// - `out_tx` must be a valid pointer to a `*mut StoolapTx`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_begin(db: *mut StoolapDB, out_tx: *mut *mut StoolapTx) -> i32 {
    if out_tx.is_null() {
        super::error::set_global_error("out_tx pointer is NULL");
        return STOOLAP_ERROR;
    }
    *out_tx = std::ptr::null_mut();

    let handle = match db.as_mut() {
        Some(h) => h,
        None => {
            super::error::set_global_error("db handle is NULL");
            return STOOLAP_ERROR;
        }
    };
    handle.last_error = None;

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| match handle.db.begin() {
        Ok(tx) => {
            let tx_handle = Box::new(StoolapTx {
                tx: Some(tx),
                last_error: None,
                _db_keepalive: handle.db.keepalive(),
                _engine_keepalive: handle._engine_keepalive.clone(),
            });
            *out_tx = Box::into_raw(tx_handle);
            STOOLAP_OK
        }
        Err(e) => {
            handle.set_error(&e.to_string());
            STOOLAP_ERROR
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_begin");
        STOOLAP_ERROR
    })
}

/// Begin a transaction with a specific isolation level.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` pointer.
/// - `isolation` must be `STOOLAP_ISOLATION_READ_COMMITTED` or `STOOLAP_ISOLATION_SNAPSHOT`.
/// - `out_tx` must be a valid pointer to a `*mut StoolapTx`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_begin_with_isolation(
    db: *mut StoolapDB,
    isolation: i32,
    out_tx: *mut *mut StoolapTx,
) -> i32 {
    if out_tx.is_null() {
        super::error::set_global_error("out_tx pointer is NULL");
        return STOOLAP_ERROR;
    }
    *out_tx = std::ptr::null_mut();

    let handle = match db.as_mut() {
        Some(h) => h,
        None => {
            super::error::set_global_error("db handle is NULL");
            return STOOLAP_ERROR;
        }
    };
    handle.last_error = None;

    let level = match isolation {
        STOOLAP_ISOLATION_READ_COMMITTED => IsolationLevel::ReadCommitted,
        STOOLAP_ISOLATION_SNAPSHOT => IsolationLevel::SnapshotIsolation,
        _ => {
            handle.set_error("invalid isolation level");
            return STOOLAP_ERROR;
        }
    };

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        match handle.db.begin_with_isolation(level) {
            Ok(tx) => {
                let tx_handle = Box::new(StoolapTx {
                    tx: Some(tx),
                    last_error: None,
                    _db_keepalive: handle.db.keepalive(),
                    _engine_keepalive: handle._engine_keepalive.clone(),
                });
                *out_tx = Box::into_raw(tx_handle);
                STOOLAP_OK
            }
            Err(e) => {
                handle.set_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_begin_with_isolation");
        STOOLAP_ERROR
    })
}

/// Execute a SQL statement within a transaction (no parameters).
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `rows_affected` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_exec(
    tx: *mut StoolapTx,
    sql: *const c_char,
    rows_affected: *mut i64,
) -> i32 {
    stoolap_tx_exec_params(tx, sql, std::ptr::null(), 0, rows_affected)
}

/// Execute a SQL statement within a transaction (with parameters).
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `params` must point to `params_len` valid `StoolapValue` structs (or be NULL).
/// - `rows_affected` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_exec_params(
    tx: *mut StoolapTx,
    sql: *const c_char,
    params: *const StoolapValue,
    params_len: i32,
    rows_affected: *mut i64,
) -> i32 {
    let handle = match tx.as_mut() {
        Some(h) => h,
        None => return STOOLAP_ERROR,
    };
    handle.last_error = None;

    if sql.is_null() {
        handle.set_error("SQL string is NULL");
        return STOOLAP_ERROR;
    }

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let inner_tx = match &mut handle.tx {
            Some(t) => t,
            None => {
                handle.set_error("transaction already ended");
                return STOOLAP_ERROR;
            }
        };

        let sql_str = match CStr::from_ptr(sql).to_str() {
            Ok(s) => s,
            Err(e) => {
                handle.set_error(&format!("invalid UTF-8 in SQL: {}", e));
                return STOOLAP_ERROR;
            }
        };

        let param_vec = value::params_to_vec(params, params_len);

        match inner_tx.execute(sql_str, param_vec) {
            Ok(affected) => {
                if !rows_affected.is_null() {
                    *rows_affected = affected;
                }
                STOOLAP_OK
            }
            Err(e) => {
                handle.set_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_tx_exec_params");
        STOOLAP_ERROR
    })
}

/// Query within a transaction (no parameters).
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `out_rows` must be a valid pointer to a `*mut StoolapRows`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_query(
    tx: *mut StoolapTx,
    sql: *const c_char,
    out_rows: *mut *mut StoolapRows,
) -> i32 {
    stoolap_tx_query_params(tx, sql, std::ptr::null(), 0, out_rows)
}

/// Query within a transaction (with parameters).
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `params` must point to `params_len` valid `StoolapValue` structs (or be NULL).
/// - `out_rows` must be a valid pointer to a `*mut StoolapRows`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_query_params(
    tx: *mut StoolapTx,
    sql: *const c_char,
    params: *const StoolapValue,
    params_len: i32,
    out_rows: *mut *mut StoolapRows,
) -> i32 {
    if out_rows.is_null() {
        return STOOLAP_ERROR;
    }
    *out_rows = std::ptr::null_mut();

    let handle = match tx.as_mut() {
        Some(h) => h,
        None => return STOOLAP_ERROR,
    };
    handle.last_error = None;

    if sql.is_null() {
        handle.set_error("SQL string is NULL");
        return STOOLAP_ERROR;
    }

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let inner_tx = match &mut handle.tx {
            Some(t) => t,
            None => {
                handle.set_error("transaction already ended");
                return STOOLAP_ERROR;
            }
        };

        let sql_str = match CStr::from_ptr(sql).to_str() {
            Ok(s) => s,
            Err(e) => {
                handle.set_error(&format!("invalid UTF-8 in SQL: {}", e));
                return STOOLAP_ERROR;
            }
        };

        let param_vec = value::params_to_vec(params, params_len);

        match inner_tx.query(sql_str, param_vec) {
            Ok(rows) => {
                let column_names: Vec<CString> = rows
                    .columns()
                    .iter()
                    .map(|name| CString::new(name.as_str()).unwrap_or_default())
                    .collect();
                let affected = rows.rows_affected();

                let rows_handle = Box::new(StoolapRows {
                    rows: Some(rows),
                    has_row: false,
                    last_error: None,
                    column_names: Arc::new(column_names),
                    text_cache: Vec::new(),
                    text_cache_dirty: false,
                    rows_affected: affected,
                });
                *out_rows = Box::into_raw(rows_handle);
                STOOLAP_OK
            }
            Err(e) => {
                handle.set_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_tx_query_params");
        STOOLAP_ERROR
    })
}

/// Commit a transaction. The tx handle is consumed (freed).
///
/// # Safety
///
/// `tx` must be a valid `StoolapTx` pointer.
/// After this call (success or failure), the pointer is invalid.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_commit(tx: *mut StoolapTx) -> i32 {
    if tx.is_null() {
        return STOOLAP_ERROR;
    }

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let mut handle = Box::from_raw(tx);

        let rc = match handle.tx.take() {
            Some(mut inner_tx) => match inner_tx.commit() {
                Ok(()) => STOOLAP_OK,
                Err(e) => {
                    // Transaction is consumed regardless; log the error globally
                    super::error::set_global_error(&e.to_string());
                    STOOLAP_ERROR
                }
            },
            None => {
                super::error::set_global_error("transaction already ended");
                STOOLAP_ERROR
            }
        };

        // Retry registry cleanup: the tx keepalive Arcs may have been the
        // last non-registry references to the engine-owning DatabaseInner.
        let engine_owning = match &handle._engine_keepalive {
            Some(arc) => Arc::clone(arc),
            None => Arc::clone(&handle._db_keepalive),
        };
        drop(handle);
        Database::try_unregister_arc(&engine_owning);

        rc
    }));

    result.unwrap_or(STOOLAP_ERROR)
}

/// Rollback a transaction. The tx handle is consumed (freed).
///
/// # Safety
///
/// `tx` must be a valid `StoolapTx` pointer.
/// After this call (success or failure), the pointer is invalid.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_rollback(tx: *mut StoolapTx) -> i32 {
    if tx.is_null() {
        return STOOLAP_ERROR;
    }

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let mut handle = Box::from_raw(tx);

        let rc = match handle.tx.take() {
            Some(mut inner_tx) => match inner_tx.rollback() {
                Ok(()) => STOOLAP_OK,
                Err(e) => {
                    super::error::set_global_error(&e.to_string());
                    STOOLAP_ERROR
                }
            },
            None => {
                super::error::set_global_error("transaction already ended");
                STOOLAP_ERROR
            }
        };

        let engine_owning = match &handle._engine_keepalive {
            Some(arc) => Arc::clone(arc),
            None => Arc::clone(&handle._db_keepalive),
        };
        drop(handle);
        Database::try_unregister_arc(&engine_owning);

        rc
    }));

    result.unwrap_or(STOOLAP_ERROR)
}

/// Execute a prepared statement within a transaction (with parameters).
///
/// This gives both parse-once performance AND transaction atomicity.
/// The statement must have been created via `stoolap_prepare()`.
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `stmt` must be a valid `StoolapStmt` pointer.
/// - `params` must point to `params_len` valid `StoolapValue` structs (or be NULL).
/// - `rows_affected` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_stmt_exec(
    tx: *mut StoolapTx,
    stmt: *const StoolapStmt,
    params: *const StoolapValue,
    params_len: i32,
    rows_affected: *mut i64,
) -> i32 {
    let handle = match tx.as_mut() {
        Some(h) => h,
        None => return STOOLAP_ERROR,
    };
    handle.last_error = None;

    let stmt_handle = match stmt.as_ref() {
        Some(h) => h,
        None => {
            handle.set_error("statement handle is NULL");
            return STOOLAP_ERROR;
        }
    };

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let inner_tx = match &mut handle.tx {
            Some(t) => t,
            None => {
                handle.set_error("transaction already ended");
                return STOOLAP_ERROR;
            }
        };

        let ast_stmt = match stmt_handle.stmt.ast_statement() {
            Some(s) => s,
            None => {
                // Multi-statement SQL: fall back to SQL-based execution
                let sql_str = stmt_handle.sql_cstr.to_str().unwrap_or("");
                let param_vec = value::params_to_vec(params, params_len);
                match inner_tx.execute(sql_str, param_vec) {
                    Ok(affected) => {
                        if !rows_affected.is_null() {
                            *rows_affected = affected;
                        }
                        return STOOLAP_OK;
                    }
                    Err(e) => {
                        handle.set_error(&e.to_string());
                        return STOOLAP_ERROR;
                    }
                }
            }
        };

        let param_vec = value::params_to_vec(params, params_len);
        match inner_tx.execute_prepared(ast_stmt, param_vec) {
            Ok(affected) => {
                if !rows_affected.is_null() {
                    *rows_affected = affected;
                }
                STOOLAP_OK
            }
            Err(e) => {
                handle.set_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_tx_stmt_exec");
        STOOLAP_ERROR
    })
}

/// Query using a prepared statement within a transaction (with parameters).
///
/// This gives both parse-once performance AND transaction atomicity.
///
/// # Safety
///
/// - `tx` must be a valid `StoolapTx` pointer.
/// - `stmt` must be a valid `StoolapStmt` pointer.
/// - `params` must point to `params_len` valid `StoolapValue` structs (or be NULL).
/// - `out_rows` must be a valid pointer to a `*mut StoolapRows`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_stmt_query(
    tx: *mut StoolapTx,
    stmt: *const StoolapStmt,
    params: *const StoolapValue,
    params_len: i32,
    out_rows: *mut *mut StoolapRows,
) -> i32 {
    if out_rows.is_null() {
        return STOOLAP_ERROR;
    }
    *out_rows = std::ptr::null_mut();

    let handle = match tx.as_mut() {
        Some(h) => h,
        None => return STOOLAP_ERROR,
    };
    handle.last_error = None;

    let stmt_handle = match stmt.as_ref() {
        Some(h) => h,
        None => {
            handle.set_error("statement handle is NULL");
            return STOOLAP_ERROR;
        }
    };

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let inner_tx = match &mut handle.tx {
            Some(t) => t,
            None => {
                handle.set_error("transaction already ended");
                return STOOLAP_ERROR;
            }
        };

        let ast_stmt = match stmt_handle.stmt.ast_statement() {
            Some(s) => s,
            None => {
                // Multi-statement SQL: fall back to SQL-based execution
                let sql_str = stmt_handle.sql_cstr.to_str().unwrap_or("");
                let param_vec = value::params_to_vec(params, params_len);
                match inner_tx.query(sql_str, param_vec) {
                    Ok(rows) => {
                        let column_names: Vec<CString> = rows
                            .columns()
                            .iter()
                            .map(|name| CString::new(name.as_str()).unwrap_or_default())
                            .collect();
                        let affected = rows.rows_affected();

                        let rows_handle = Box::new(StoolapRows {
                            rows: Some(rows),
                            has_row: false,
                            last_error: None,
                            column_names: Arc::new(column_names),
                            text_cache: Vec::new(),
                            text_cache_dirty: false,
                            rows_affected: affected,
                        });
                        *out_rows = Box::into_raw(rows_handle);
                        return STOOLAP_OK;
                    }
                    Err(e) => {
                        handle.set_error(&e.to_string());
                        return STOOLAP_ERROR;
                    }
                }
            }
        };

        let param_vec = value::params_to_vec(params, params_len);
        match inner_tx.query_prepared(ast_stmt, param_vec) {
            Ok(rows) => {
                let column_names: Vec<CString> = rows
                    .columns()
                    .iter()
                    .map(|name| CString::new(name.as_str()).unwrap_or_default())
                    .collect();
                let affected = rows.rows_affected();

                let rows_handle = Box::new(StoolapRows {
                    rows: Some(rows),
                    has_row: false,
                    last_error: None,
                    column_names: Arc::new(column_names),
                    text_cache: Vec::new(),
                    text_cache_dirty: false,
                    rows_affected: affected,
                });
                *out_rows = Box::into_raw(rows_handle);
                STOOLAP_OK
            }
            Err(e) => {
                handle.set_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        handle.set_error("panic during stoolap_tx_stmt_query");
        STOOLAP_ERROR
    })
}

/// Get the last error message for a transaction handle.
///
/// # Safety
///
/// `tx` must be a valid `StoolapTx` pointer.
#[no_mangle]
pub unsafe extern "C" fn stoolap_tx_errmsg(tx: *const StoolapTx) -> *const c_char {
    match tx.as_ref() {
        Some(handle) => handle.error_ptr(),
        None => super::error::global_error_ptr(),
    }
}