linkrs-api 0.1.0

Transport-independent core API for Linkrs
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! C API Session Management Module
//!
//! It provides functions for creating, destroying, and performing basic management of sessions.

use crate::embedded::c_api::database::LinkrsHandle;
use crate::embedded::c_api::error::{
    error_code_from_core_error, extended_error_code_from_core_error, linkrs_error_code_t,
    set_last_error_message,
};
use crate::embedded::c_api::types::{
    linkrs_commit_hook_callback, linkrs_extended_error_code_t, linkrs_rollback_hook_callback,
    linkrs_session_t, linkrs_t, linkrs_trace_callback, linkrs_update_hook_callback,
};
use crate::embedded::Session;
use linkrs_storage::GraphStorage;
use std::ffi::{c_char, c_int, c_void, CStr, CString};
use std::ptr;

/// Internal structure of the session handler
pub struct LinkrsSessionHandle {
    pub(crate) inner: Session<GraphStorage>,
    pub(crate) last_error: Option<CString>,
    /// Busy wait timeout (in milliseconds)
    pub(crate) busy_timeout_ms: u32,
    /// Offset of the last error location
    pub(crate) last_error_offset: Option<usize>,
    /// Finally, the error code was expanded.
    pub(crate) last_extended_error: Option<linkrs_extended_error_code_t>,
    /// SQL tracing callback
    pub(crate) trace_callback: linkrs_trace_callback,
    /// SQL tracking callback for user data
    pub(crate) trace_user_data: *mut c_void,
    /// User data for the commit hook, returned to the caller on replacement.
    pub(crate) commit_hook_user_data: *mut c_void,
    /// Bridge registration id of the commit hook on the transaction
    /// manager's veto registry (`None` when no hook is installed). The C
    /// callback and the Rust veto share one evaluation point.
    pub(crate) commit_veto_id: Option<linkrs_core::event_dispatch::SubscriptionId>,
    /// Rollback hook callback
    pub(crate) rollback_hook: linkrs_rollback_hook_callback,
    /// Roll back the user data associated with the hook.
    pub(crate) rollback_hook_user_data: *mut c_void,
    /// Update the hook callback
    pub(crate) update_hook: linkrs_update_hook_callback,
    /// Update the user data for the hook.
    pub(crate) update_hook_user_data: *mut c_void,
}

// The Send and Sync functions need to be implemented manually, because the type *mut c_void is not thread-safe.
// Thread-safety contract: a session handle must not be shared across threads
// concurrently. Hook callbacks (commit veto, update, trace) always run on the
// thread performing the operation that triggers them; `user_data` must stay
// valid from registration until replacement, session close, or explicit NULL
// deregistration, whichever comes first.
unsafe impl Send for LinkrsSessionHandle {}
unsafe impl Sync for LinkrsSessionHandle {}

impl LinkrsSessionHandle {
    /// Create a new session handle.
    pub(crate) fn new(inner: Session<GraphStorage>) -> Self {
        Self {
            inner,
            last_error: None,
            busy_timeout_ms: 5000, // Default value: 5 seconds
            last_error_offset: None,
            last_extended_error: None,
            trace_callback: None,
            trace_user_data: ptr::null_mut(),
            commit_hook_user_data: ptr::null_mut(),
            commit_veto_id: None,
            rollback_hook: None,
            rollback_hook_user_data: ptr::null_mut(),
            update_hook: None,
            update_hook_user_data: ptr::null_mut(),
        }
    }

    /// Whether an update hook is installed.
    ///
    /// Fast path so query execution can skip statement classification
    /// (`detect_data_modification`, including a full-string uppercase scan
    /// for `MATCH`-family queries) when nobody listens.
    pub(crate) fn has_update_hook(&self) -> bool {
        self.update_hook.is_some()
    }

    /// Call the update hook.
    ///
    /// Statement-level DML notification (not per-row): `database` carries
    /// the space name and `table` is an empty string (there is no table
    /// concept). `rowid` carries the affected row count from the result
    /// metadata, not a stable row id.
    ///
    /// The callback runs with panic isolation: a panicking C callback is
    /// caught, logged, and skipped so the query result is still returned.
    /// C callbacks must not unwind across the FFI boundary.
    pub(crate) fn invoke_update_hook(&self, operation: i32, space_name: &str, rowid: i64) {
        if let Some(callback) = self.update_hook {
            if let Ok(c_space) = CString::new(space_name) {
                // For graph databases, the `table` parameter should be set to an empty string.
                if let Ok(empty_table) = CString::new("") {
                    let user_data = self.update_hook_user_data;
                    let space_ptr = c_space.as_ptr();
                    let table_ptr = empty_table.as_ptr();
                    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        callback(user_data, operation, space_ptr, table_ptr, rowid);
                    }))
                    .is_err()
                    {
                        log::error!("update hook panicked; continuing query");
                    }
                }
            }
        }
    }

    /// Calling the SQL tracing callback with panic isolation.
    pub(crate) fn trace(&self, sql: &str) {
        if let Some(callback) = self.trace_callback {
            if let Ok(c_sql) = CString::new(sql) {
                let user_data = self.trace_user_data;
                let sql_ptr = c_sql.as_ptr();
                if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    callback(sql_ptr, user_data);
                }))
                .is_err()
                {
                    log::error!("trace callback panicked; continuing query");
                }
            }
        }
    }

    /// Setting error messages
    pub(crate) fn set_error(
        &mut self,
        message: String,
        offset: Option<usize>,
        extended_code: Option<linkrs_extended_error_code_t>,
    ) {
        self.last_error = CString::new(message.clone()).ok();
        self.last_error_offset = offset;
        self.last_extended_error = extended_code;
        set_last_error_message(message);
    }

    /// Clear the error messages.
    pub(crate) fn clear_error(&mut self) {
        self.last_error = None;
        self.last_error_offset = None;
        self.last_extended_error = None;
    }
}

/// Create a session
///
/// # Arguments
/// - `db`: Database handle
/// - `session`: Output parameter, session handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `db` must be a valid database handle created by `linkrs_open` or `linkrs_open_with_config`
/// - `session` must be a valid pointer to store the session handle
/// - The caller is responsible for closing the session using `linkrs_session_close` when done
/// - The session handle must not be used after closing
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_create(
    db: *mut linkrs_t,
    session: *mut *mut linkrs_session_t,
) -> c_int {
    if db.is_null() || session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let db_handle = &*(db as *mut LinkrsHandle);

    match db_handle.inner.session() {
        Ok(sess) => {
            let mut handle = Box::new(LinkrsSessionHandle::new(sess));
            // Inherit the database default timeout so the C
            // `linkrs_config_set_timeout` setting takes effect instead of
            // the fixed 5s fallback inside the handle constructor.
            let timeout_ms = db_handle.inner.config().default_timeout.as_millis();
            handle.busy_timeout_ms = timeout_ms.min(u32::MAX as u128) as u32;
            *session = Box::into_raw(handle) as *mut linkrs_session_t;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let (error_code, _) = error_code_from_core_error(&e);
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            *session = ptr::null_mut();
            error_code
        }
    }
}

/// Close the session.
///
/// # Arguments
/// - `session`: Session handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - After calling this function, the session handle becomes invalid and must not be used
/// - All pending transactions will be rolled back
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_close(session: *mut linkrs_session_t) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = Box::from_raw(session as *mut LinkrsSessionHandle);
    // Retire the commit-hook bridge so a closed session's user_data can
    // never be invoked by a later commit on the shared manager.
    if let Some(id) = handle.commit_veto_id {
        handle.inner.txn_manager().unregister_commit_veto(id);
    }
    drop(handle);

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Switch to the image space
///
/// # Arguments
/// - `session`: Session handle
/// - `space_name`: Graph space name (UTF-8 encoded)
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `space_name` must be a valid pointer to a null-terminated UTF-8 string
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_use_space(
    session: *mut linkrs_session_t,
    space_name: *const c_char,
) -> c_int {
    if session.is_null() || space_name.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let name_str = match CStr::from_ptr(space_name).to_str() {
        Ok(s) => s,
        Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let handle = &mut *(session as *mut LinkrsSessionHandle);

    match handle.inner.use_space(name_str) {
        Ok(_) => {
            handle.clear_error();
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let (error_code, _) = error_code_from_core_error(&e);
            let error_msg = format!("{}", e);
            let offset = e.error_offset();
            let extended_code = Some(extended_error_code_from_core_error(&e));
            handle.set_error(error_msg, offset, extended_code);
            error_code
        }
    }
}

/// Obtain the current image space
///
/// # Arguments
/// - `session`: Session handle
///
/// # Returns
/// - Current graph space name (UTF-8 encoded), returns NULL if none
///
/// # Memory Management
/// The returned string is dynamically allocated and must be freed by the caller using `linkrs_free_string`
/// to avoid memory leaks.
///
/// # Example
/// ```c
/// char* space = linkrs_session_current_space(session);
/// if (space) {
///     printf("Current space: %s\n", space);
///     linkrs_free_string(space);  // Must free
/// }
/// ```
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - The returned pointer must be freed by the caller to avoid memory leaks
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_current_space(
    session: *mut linkrs_session_t,
) -> *mut c_char {
    if session.is_null() {
        return ptr::null_mut();
    }

    let handle = &*(session as *mut LinkrsSessionHandle);

    match handle.inner.current_space() {
        Some(name) => {
            match CString::new(name) {
                Ok(c_name) => {
                    // Convert a CString to the original pointer
                    // The caller needs to use `linkrs_free_string` to release the resource.
                    c_name.into_raw()
                }
                Err(_) => ptr::null_mut(),
            }
        }
        None => ptr::null_mut(),
    }
}

/// Enable the automatic submission mode.
///
/// # Arguments
/// - `session`: Session handle
/// - `autocommit`: Whether to enable autocommit
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_set_autocommit(
    session: *mut linkrs_session_t,
    autocommit: bool,
) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    handle.inner.set_auto_commit(autocommit);
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Enable the automatic submission mode.
///
/// # Arguments
/// - `session`: Session handle
///
/// # Returns
/// - Whether autocommit is enabled
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_session_get_autocommit(session: *mut linkrs_session_t) -> bool {
    if session.is_null() {
        return true; // Default automatic submission
    }

    let handle = &*(session as *mut LinkrsSessionHandle);
    handle.inner.auto_commit()
}

/// Setting the busy wait timeout
///
/// # Arguments
/// - `session`: Session handle
/// - `timeout_ms`: Timeout in milliseconds
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_busy_timeout(
    session: *mut linkrs_session_t,
    timeout_ms: c_int,
) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    // The storage timeout settings are applied to the handle.
    handle.busy_timeout_ms = timeout_ms.max(0) as u32;
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Busy wait timeout has occurred.
///
/// # Arguments
/// - `session`: Session handle
///
/// # Returns
/// - Timeout in milliseconds, returns -1 on error
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_busy_timeout_get(session: *mut linkrs_session_t) -> c_int {
    if session.is_null() {
        return 0;
    }

    let handle = &*(session as *mut LinkrsSessionHandle);
    handle.busy_timeout_ms as c_int
}

/// Setting up an SQL tracing callback
///
/// # Arguments
/// - `session`: Session handle
/// - `callback`: Trace callback function, NULL to disable tracing
/// - `user_data`: User data pointer, will be passed to the callback
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Example
/// ```c
/// extern void my_trace_callback(const char* sql, void* data) {
///     printf("Executing: %s\n", sql);
/// }
///
/// linkrs_trace(session, my_trace_callback, NULL);
/// ```
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `callback` must be a valid function pointer, or NULL to disable tracing
/// - `user_data` is passed to the callback and must remain valid for the lifetime of the callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_trace(
    session: *mut linkrs_session_t,
    callback: linkrs_trace_callback,
    user_data: *mut c_void,
) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    handle.trace_callback = callback;
    handle.trace_user_data = user_data;
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Setting up the commit hook
///
/// # Arguments
/// - `session`: Session handle
/// - `callback`: Commit hook callback function, NULL to disable the hook
/// - `user_data`: User data pointer, will be passed to the callback
///
/// # Returns
/// - Previous hook user data pointer (if any)
///
/// # Description
/// The commit hook is called before a transaction is committed. If the callback returns a non-zero value,
/// the transaction will be rolled back.
///
/// The C callback is bridged into the transaction manager's commit-veto
/// registry, so it shares one evaluation point with Rust
/// `register_commit_veto` hooks (first veto wins). A panicking callback is
/// isolated and treated as allow.
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `callback` must be a valid function pointer, or NULL to disable the hook
/// - `user_data` is passed to the callback and must remain valid for the lifetime of the callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_commit_hook(
    session: *mut linkrs_session_t,
    callback: linkrs_commit_hook_callback,
    user_data: *mut c_void,
) -> *mut c_void {
    if session.is_null() {
        return ptr::null_mut();
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    let old_user_data = handle.commit_hook_user_data;
    // Retire the previous bridge registration, if any.
    if let Some(id) = handle.commit_veto_id.take() {
        handle.inner.txn_manager().unregister_commit_veto(id);
    }
    handle.commit_hook_user_data = user_data;
    if let Some(func) = callback {
        // `usize` round-trips the raw pointer into the `'static` closure
        // without claiming `Send` for it; the callback always runs on the
        // thread performing the commit, and lifetime is bounded by the
        // unregister above / session close.
        let user_data_addr = user_data as usize;
        let bridge: std::sync::Arc<
            dyn Fn(&linkrs_transaction::CommitVetoContext) -> linkrs_transaction::VetoDecision
                + Send
                + Sync,
        > = std::sync::Arc::new(move |_| {
            let restored = user_data_addr as *mut c_void;
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| func(restored)));
            match outcome {
                Ok(0) => linkrs_transaction::VetoDecision::allow(),
                Ok(_) => linkrs_transaction::VetoDecision::veto("c commit hook vetoed"),
                Err(_) => {
                    log::error!("commit hook panicked; treating as allow");
                    linkrs_transaction::VetoDecision::allow()
                }
            }
        });
        let id = handle.inner.txn_manager().register_commit_veto(bridge);
        handle.commit_veto_id = Some(id);
    }
    old_user_data
}

/// Setting up a rollback hook
///
/// # Arguments
/// - `session`: Session handle
/// - `callback`: Rollback hook callback function, NULL to disable the hook
/// - `user_data`: User data pointer, will be passed to the callback
///
/// # Returns
/// - Previous hook user data pointer (if any)
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `callback` must be a valid function pointer, or NULL to disable the hook
/// - `user_data` is passed to the callback and must remain valid for the lifetime of the callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_rollback_hook(
    session: *mut linkrs_session_t,
    callback: linkrs_rollback_hook_callback,
    user_data: *mut c_void,
) -> *mut c_void {
    if session.is_null() {
        return ptr::null_mut();
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    let old_user_data = handle.rollback_hook_user_data;
    handle.rollback_hook = callback;
    handle.rollback_hook_user_data = user_data;
    old_user_data
}

/// Set up the update hook
///
/// When data in the database changes, the callback function is called
///
/// # Arguments
/// - `session`: Session handle
/// - `callback`: Update hook callback function, NULL to disable the hook
/// - `user_data`: User data pointer, will be passed to the callback
///
/// # Returns
/// - Previous hook user data pointer (if any)
///
/// # Callback Parameters
/// - `operation`: Operation type (1=INSERT, 2=UPDATE, 3=DELETE)
/// - `database`: Database/space name
/// - `table`: Table name (empty string for graph database)
/// - `rowid`: Affected row ID
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `callback` must be a valid function pointer, or NULL to disable the hook
/// - `user_data` is passed to the callback and must remain valid for the lifetime of the callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_update_hook(
    session: *mut linkrs_session_t,
    callback: linkrs_update_hook_callback,
    user_data: *mut c_void,
) -> *mut c_void {
    if session.is_null() {
        return ptr::null_mut();
    }

    let handle = &mut *(session as *mut LinkrsSessionHandle);
    let old_user_data = handle.update_hook_user_data;
    handle.update_hook = callback;
    handle.update_hook_user_data = user_data;
    old_user_data
}

/// Interrupt a session's next query.
///
/// Cooperative cancellation at the entry gate: sets the session interrupt
/// flag so the next `execute` entry point fails fast with an interrupted
/// error. A query already running is not touched; stop those through the
/// executor kill path. Use `linkrs_connection_clear_interrupt` to resume
/// normal execution.
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_connection_interrupt(session: *mut linkrs_session_t) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(session as *const LinkrsSessionHandle);
    handle.inner.interrupt();
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Clear a previously requested session interrupt.
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
#[no_mangle]
pub unsafe extern "C" fn linkrs_connection_clear_interrupt(
    session: *mut linkrs_session_t,
) -> c_int {
    if session.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(session as *const LinkrsSessionHandle);
    handle.inner.clear_interrupt();
    linkrs_error_code_t::LINKRS_OK as c_int
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embedded::c_api::database::{linkrs_close, linkrs_open};
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn create_test_db() -> *mut linkrs_t {
        let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let temp_dir = std::env::temp_dir().join("linkrs_c_api_test");
        std::fs::create_dir_all(&temp_dir).ok();
        let db_path = temp_dir.join(format!(
            "test_session_{}_{}.db",
            std::process::id(),
            counter
        ));

        // Make sure the database file does not exist.
        if db_path.exists() {
            std::fs::remove_file(&db_path).ok();
            // Waiting for the file system to complete the deletion operation.
            std::thread::sleep(std::time::Duration::from_millis(50));
        }

        let path_cstring = CString::new(db_path.to_str().expect("Invalid path"))
            .expect("Failed to create CString");
        let mut db: *mut linkrs_t = ptr::null_mut();

        let rc = unsafe { linkrs_open(path_cstring.as_ptr(), &mut db) };
        if rc != linkrs_error_code_t::LINKRS_OK as c_int {
            panic!(
                "Failed to open database, error code: {}, path: {:?}",
                rc, db_path
            );
        }
        assert!(!db.is_null());

        db
    }

    #[test]
    fn test_session_create_close() {
        let db = create_test_db();
        let mut session: *mut linkrs_session_t = ptr::null_mut();

        // Create a session
        let rc = unsafe { linkrs_session_create(db, &mut session) };
        assert_eq!(rc, linkrs_error_code_t::LINKRS_OK as c_int);
        assert!(!session.is_null());

        // Close the session.
        let rc = unsafe { linkrs_session_close(session) };
        assert_eq!(rc, linkrs_error_code_t::LINKRS_OK as c_int);

        // Close the database.
        let rc = unsafe { linkrs_close(db) };
        assert_eq!(rc, linkrs_error_code_t::LINKRS_OK as c_int);
    }

    #[test]
    fn test_session_autocommit() {
        let db = create_test_db();
        let mut session: *mut linkrs_session_t = ptr::null_mut();

        let rc = unsafe { linkrs_session_create(db, &mut session) };
        assert_eq!(rc, linkrs_error_code_t::LINKRS_OK as c_int);

        // Default automatic submission
        let autocommit = unsafe { linkrs_session_get_autocommit(session) };
        assert!(autocommit);

        // Turn off automatic submission.
        let rc = unsafe { linkrs_session_set_autocommit(session, false) };
        assert_eq!(rc, linkrs_error_code_t::LINKRS_OK as c_int);

        let autocommit = unsafe { linkrs_session_get_autocommit(session) };
        assert!(!autocommit);

        unsafe { linkrs_session_close(session) };
        unsafe { linkrs_close(db) };
    }
}