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
// 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.

//! Database lifecycle and query execution 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::common::version::VERSION;

use super::error;
use super::types::{StoolapDB, StoolapRows, StoolapValue};
use super::value;
use super::{STOOLAP_ERROR, STOOLAP_OK};

/// Version string with static lifetime, initialized once.
static VERSION_CSTR: std::sync::OnceLock<CString> = std::sync::OnceLock::new();

/// Returns the stoolap version string.
///
/// The returned pointer is static and must NOT be freed.
#[no_mangle]
pub extern "C" fn stoolap_version() -> *const c_char {
    VERSION_CSTR
        .get_or_init(|| CString::new(VERSION).unwrap_or_default())
        .as_ptr()
}

/// Open a database connection.
///
/// # Safety
///
/// - `dsn` must be a valid null-terminated UTF-8 string.
/// - `out_db` must be a valid pointer to a `*mut StoolapDB`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_open(dsn: *const c_char, out_db: *mut *mut StoolapDB) -> i32 {
    if out_db.is_null() {
        return STOOLAP_ERROR;
    }
    *out_db = std::ptr::null_mut();

    if dsn.is_null() {
        error::set_global_error("DSN string is NULL");
        return STOOLAP_ERROR;
    }

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        let dsn_str = match CStr::from_ptr(dsn).to_str() {
            Ok(s) => s,
            Err(e) => {
                error::set_global_error(&format!("invalid UTF-8 in DSN: {}", e));
                return STOOLAP_ERROR;
            }
        };

        match Database::open(dsn_str) {
            Ok(db) => {
                let handle = Box::new(StoolapDB {
                    db,
                    last_error: None,
                    _engine_keepalive: None,
                });
                *out_db = Box::into_raw(handle);
                STOOLAP_OK
            }
            Err(e) => {
                error::set_global_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        error::set_global_error("panic during stoolap_open");
        STOOLAP_ERROR
    })
}

/// Open an in-memory database.
///
/// # Safety
///
/// `out_db` must be a valid pointer to a `*mut StoolapDB`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_open_in_memory(out_db: *mut *mut StoolapDB) -> i32 {
    if out_db.is_null() {
        return STOOLAP_ERROR;
    }
    *out_db = std::ptr::null_mut();

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        match Database::open_in_memory() {
            Ok(db) => {
                let handle = Box::new(StoolapDB {
                    db,
                    last_error: None,
                    _engine_keepalive: None,
                });
                *out_db = Box::into_raw(handle);
                STOOLAP_OK
            }
            Err(e) => {
                error::set_global_error(&e.to_string());
                STOOLAP_ERROR
            }
        }
    }));

    result.unwrap_or_else(|_| {
        error::set_global_error("panic during stoolap_open_in_memory");
        STOOLAP_ERROR
    })
}

/// Close a database connection and free resources.
///
/// Safe to call with NULL (no-op).
///
/// # Safety
///
/// `db` must be a pointer returned by `stoolap_open*`, or NULL.
/// After this call, the pointer is invalid.
#[no_mangle]
pub unsafe extern "C" fn stoolap_close(db: *mut StoolapDB) -> i32 {
    if db.is_null() {
        return STOOLAP_OK;
    }

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

        // Try to clean up the registry entry for the engine-owning
        // DatabaseInner. The method only removes the entry if the caller
        // holds the last non-registry reference (strong_count == 2).
        //
        // For original handles opened via stoolap_open(): self.inner IS
        //   the registry entry. If another handle from the same DSN is still
        //   alive, the count is > 2 and we skip removal.
        // For clone handles: the keepalive Arc points to the original,
        //   engine-owning DatabaseInner. If we're the last clone (and the
        //   original is already closed), count == 2 and we clean up.
        match &handle._engine_keepalive {
            None => Database::try_unregister_arc(handle.db.inner_arc()),
            Some(keepalive) => Database::try_unregister_arc(keepalive),
        }

        // Drop the handle. The underlying engine is reference-counted (Arc)
        // and will be closed automatically when the last handle drops.
        // We intentionally do NOT call handle.db.close() here because it
        // would shut down the shared engine, breaking any cloned handles.
        drop(handle);
        STOOLAP_OK
    }));

    result.unwrap_or(STOOLAP_ERROR)
}

/// Clone a database handle for use in another thread.
///
/// The new handle shares the same underlying engine (data, tables, indexes)
/// but has its own executor and error state. This is the recommended way to
/// use stoolap from multiple threads: clone once per thread.
///
/// The returned handle must be closed independently with `stoolap_close()`.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` pointer.
/// - `out_db` must be a valid pointer to a `*mut StoolapDB`.
#[no_mangle]
pub unsafe extern "C" fn stoolap_clone(db: *const StoolapDB, out_db: *mut *mut StoolapDB) -> i32 {
    if out_db.is_null() {
        error::set_global_error("out_db pointer is NULL");
        return STOOLAP_ERROR;
    }
    *out_db = std::ptr::null_mut();

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

    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {
        // Keep the original engine-owning DatabaseInner alive.
        // If the source is the original, grab its keepalive.
        // If the source is itself a clone, propagate the existing keepalive.
        let keepalive = match &handle._engine_keepalive {
            Some(arc) => std::sync::Arc::clone(arc),
            None => handle.db.keepalive(),
        };

        let cloned = handle.db.clone();
        let new_handle = Box::new(StoolapDB {
            db: cloned,
            last_error: None,
            _engine_keepalive: Some(keepalive),
        });
        *out_db = Box::into_raw(new_handle);
        STOOLAP_OK
    }));

    result.unwrap_or_else(|_| {
        error::set_global_error("panic during stoolap_clone");
        STOOLAP_ERROR
    })
}

/// Get the last error message for a database handle.
///
/// Returns `""` if no error. If `db` is NULL, returns the last global error
/// (from `stoolap_open` failures).
///
/// The returned pointer is valid until the next API call on this handle.
///
/// # Safety
///
/// `db` must be a valid `StoolapDB` pointer or NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_errmsg(db: *const StoolapDB) -> *const c_char {
    match db.as_ref() {
        Some(handle) => handle.error_ptr(),
        None => error::global_error_ptr(),
    }
}

/// Execute a SQL statement without parameters.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `rows_affected` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_exec(
    db: *mut StoolapDB,
    sql: *const c_char,
    rows_affected: *mut i64,
) -> i32 {
    let handle = match db.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 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;
            }
        };

        match handle.db.execute(sql_str, ()) {
            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_exec");
        STOOLAP_ERROR
    })
}

/// Execute a SQL statement with positional parameters.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` pointer.
/// - `sql` must be a valid null-terminated UTF-8 string.
/// - `params` must point to `params_len` valid `StoolapValue` structs (or be NULL if `params_len` is 0).
/// - `rows_affected` may be NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_exec_params(
    db: *mut StoolapDB,
    sql: *const c_char,
    params: *const StoolapValue,
    params_len: i32,
    rows_affected: *mut i64,
) -> i32 {
    let handle = match db.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 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 handle.db.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_exec_params");
        STOOLAP_ERROR
    })
}

/// Execute a query without parameters, returning a result set.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` 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_query(
    db: *mut StoolapDB,
    sql: *const c_char,
    out_rows: *mut *mut StoolapRows,
) -> i32 {
    stoolap_query_params(db, sql, std::ptr::null(), 0, out_rows)
}

/// Execute a query with positional parameters, returning a result set.
///
/// # Safety
///
/// - `db` must be a valid `StoolapDB` 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_query_params(
    db: *mut StoolapDB,
    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 db.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 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 handle.db.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_query_params");
        STOOLAP_ERROR
    })
}

/// Free a string allocated by the library.
///
/// Safe to call with NULL (no-op).
///
/// # Safety
///
/// `s` must be a pointer returned by a stoolap function that requires freeing, or NULL.
#[no_mangle]
pub unsafe extern "C" fn stoolap_string_free(s: *mut c_char) {
    if !s.is_null() {
        let _ = CString::from_raw(s);
    }
}