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
//! C API error handling
//!
//! Provide error code conversion and error message management functions.

use crate::api_core::{CoreError, ExtendedErrorCode};
use crate::embedded::c_api::types::{linkrs_extended_error_code_t, linkrs_session_t};
use std::cell::RefCell;
use std::ffi::CString;

fn transaction_extended_error_code(message: &str) -> linkrs_extended_error_code_t {
    let message = message.to_ascii_lowercase();
    if message.contains("write_transaction_conflict")
        || message.contains("transaction conflict")
        || message.contains("conflict")
    {
        linkrs_extended_error_code_t::LINKRS_ERROR_CONFLICT
    } else if message.contains("transaction_not_owner") || message.contains("not owned by another")
    {
        linkrs_extended_error_code_t::LINKRS_ERROR_NOT_OWNER
    } else if message.contains("invalid_state_for_commit")
        || message.contains("already committed")
        || message.contains("already aborted")
    {
        linkrs_extended_error_code_t::LINKRS_ERROR_ALREADY_COMPLETED
    } else if message.contains("timeout") {
        linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT
    } else {
        linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE
    }
}

thread_local! {
    static LAST_ERROR_MESSAGE: RefCell<Option<CString>> = const { RefCell::new(None) };
}

/// Set the final error message
pub(crate) fn set_last_error_message(msg: String) {
    LAST_ERROR_MESSAGE.with(|m| {
        *m.borrow_mut() = CString::new(msg).ok();
    });
}

/// The extended error code is inferred from the CoreError.
pub fn extended_error_code_from_core_error(error: &CoreError) -> linkrs_extended_error_code_t {
    match error {
        CoreError::DetailedQueryError { extended_code, .. } => {
            extended_error_code_from_internal(*extended_code)
        }
        CoreError::QueryExecutionFailed(msg) => {
            if msg.contains("syntax") {
                linkrs_extended_error_code_t::LINKRS_ERROR_SYNTAX
            } else if msg.contains("semantic") {
                linkrs_extended_error_code_t::LINKRS_ERROR_SEMANTIC
            } else if msg.contains("type mismatch") {
                linkrs_extended_error_code_t::LINKRS_ERROR_TYPE_MISMATCH
            } else if msg.contains("constraint") {
                linkrs_extended_error_code_t::LINKRS_ERROR_CHECK
            } else if msg.contains("division by zero") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DIVISION_BY_ZERO
            } else if msg.contains("out of range") {
                linkrs_extended_error_code_t::LINKRS_ERROR_OUT_OF_RANGE
            } else if msg.contains("duplicate") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DUPLICATE_KEY
            } else if msg.contains("not null") {
                linkrs_extended_error_code_t::LINKRS_ERROR_NOT_NULL
            } else if msg.contains("unique") {
                linkrs_extended_error_code_t::LINKRS_ERROR_UNIQUE
            } else if msg.contains("foreign key") {
                linkrs_extended_error_code_t::LINKRS_ERROR_FOREIGN_KEY
            } else if msg.contains("deadlock") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DEADLOCK
            } else if msg.contains("timeout") {
                linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT
            } else if msg.contains("connection") {
                linkrs_extended_error_code_t::LINKRS_ERROR_CONNECTION_LOST
            } else if msg.contains("vertex") {
                linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_VERTEX
            } else if msg.contains("edge") {
                linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_EDGE
            } else if msg.contains("path") {
                linkrs_extended_error_code_t::LINKRS_ERROR_PATH_NOT_FOUND
            } else {
                linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE
            }
        }
        CoreError::StorageError(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::TransactionFailed(message) => transaction_extended_error_code(message),
        CoreError::SchemaOperationFailed(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::InvalidParameter(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::NotFound(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::Internal(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::SyncError(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        CoreError::VectorError(_) => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
    }
}

/// Convert the internal ExtendedErrorCode to a C API extended error code.
fn extended_error_code_from_internal(code: ExtendedErrorCode) -> linkrs_extended_error_code_t {
    match code {
        ExtendedErrorCode::None => linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ExtendedErrorCode::SyntaxError => linkrs_extended_error_code_t::LINKRS_ERROR_SYNTAX,
        ExtendedErrorCode::SemanticError => linkrs_extended_error_code_t::LINKRS_ERROR_SEMANTIC,
        ExtendedErrorCode::UnexpectedToken => {
            linkrs_extended_error_code_t::LINKRS_ERROR_UNEXPECTED_TOKEN
        }
        ExtendedErrorCode::UnterminatedLiteral => {
            linkrs_extended_error_code_t::LINKRS_ERROR_UNTERMINATED_LITERAL
        }
        ExtendedErrorCode::TypeMismatch => linkrs_extended_error_code_t::LINKRS_ERROR_TYPE_MISMATCH,
        ExtendedErrorCode::DivisionByZero => {
            linkrs_extended_error_code_t::LINKRS_ERROR_DIVISION_BY_ZERO
        }
        ExtendedErrorCode::OutOfRange => linkrs_extended_error_code_t::LINKRS_ERROR_OUT_OF_RANGE,
        ExtendedErrorCode::DuplicateKey => linkrs_extended_error_code_t::LINKRS_ERROR_DUPLICATE_KEY,
        ExtendedErrorCode::ForeignKeyConstraint => {
            linkrs_extended_error_code_t::LINKRS_ERROR_FOREIGN_KEY
        }
        ExtendedErrorCode::NotNullConstraint => linkrs_extended_error_code_t::LINKRS_ERROR_NOT_NULL,
        ExtendedErrorCode::UniqueConstraint => linkrs_extended_error_code_t::LINKRS_ERROR_UNIQUE,
        ExtendedErrorCode::CheckConstraint => linkrs_extended_error_code_t::LINKRS_ERROR_CHECK,
        ExtendedErrorCode::ConnectionLost => {
            linkrs_extended_error_code_t::LINKRS_ERROR_CONNECTION_LOST
        }
        ExtendedErrorCode::Deadlock => linkrs_extended_error_code_t::LINKRS_ERROR_DEADLOCK,
        ExtendedErrorCode::LockTimeout => linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT,
        ExtendedErrorCode::InvalidVertex => {
            linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_VERTEX
        }
        ExtendedErrorCode::InvalidEdge => linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_EDGE,
        ExtendedErrorCode::PathNotFound => {
            linkrs_extended_error_code_t::LINKRS_ERROR_PATH_NOT_FOUND
        }
        ExtendedErrorCode::Internal => linkrs_extended_error_code_t::LINKRS_ERROR_INTERNAL,
    }
}

/// Error code
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(non_camel_case_types)]
pub enum linkrs_error_code_t {
    /// Success
    LINKRS_OK = 0,
    /// Common errors
    LINKRS_ERROR = 1,
    /// Internal error
    LINKRS_INTERNAL = 2,
    /// The permission was denied.
    LINKRS_PERM = 3,
    /// The operation was terminated.
    LINKRS_ABORT = 4,
    /// The database is busy.
    LINKRS_BUSY = 5,
    /// The database is locked.
    LINKRS_LOCKED = 6,
    /// Insufficient memory
    LINKRS_NOMEM = 7,
    /// Read-only
    LINKRS_READONLY = 8,
    /// The operation was interrupted.
    LINKRS_INTERRUPT = 9,
    /// IO error
    LINKRS_IOERR = 10,
    /// Data corruption
    LINKRS_CORRUPT = 11,
    /// Nothing was found.
    LINKRS_NOTFOUND = 12,
    /// The disk is full.
    LINKRS_FULL = 13,
    /// Unable to open.
    LINKRS_CANTOPEN = 14,
    /// Protocol error
    LINKRS_PROTOCOL = 15,
    /// Pattern error
    LINKRS_SCHEMA = 16,
    /// The data volume is too large.
    LINKRS_TOOBIG = 17,
    /// Violation of constraints
    LINKRS_CONSTRAINT = 18,
    /// Type mismatch.
    LINKRS_MISMATCH = 19,
    /// Misuse
    LINKRS_MISUSE = 20,
    /// Out of range
    LINKRS_RANGE = 21,
    /// Not implemented
    LINKRS_NOT_IMPLEMENTED = 22,
}

impl TryFrom<i32> for linkrs_error_code_t {
    type Error = ();

    fn try_from(code: i32) -> Result<Self, Self::Error> {
        Ok(match code {
            0 => linkrs_error_code_t::LINKRS_OK,
            1 => linkrs_error_code_t::LINKRS_ERROR,
            2 => linkrs_error_code_t::LINKRS_INTERNAL,
            3 => linkrs_error_code_t::LINKRS_PERM,
            4 => linkrs_error_code_t::LINKRS_ABORT,
            5 => linkrs_error_code_t::LINKRS_BUSY,
            6 => linkrs_error_code_t::LINKRS_LOCKED,
            7 => linkrs_error_code_t::LINKRS_NOMEM,
            8 => linkrs_error_code_t::LINKRS_READONLY,
            9 => linkrs_error_code_t::LINKRS_INTERRUPT,
            10 => linkrs_error_code_t::LINKRS_IOERR,
            11 => linkrs_error_code_t::LINKRS_CORRUPT,
            12 => linkrs_error_code_t::LINKRS_NOTFOUND,
            13 => linkrs_error_code_t::LINKRS_FULL,
            14 => linkrs_error_code_t::LINKRS_CANTOPEN,
            15 => linkrs_error_code_t::LINKRS_PROTOCOL,
            16 => linkrs_error_code_t::LINKRS_SCHEMA,
            17 => linkrs_error_code_t::LINKRS_TOOBIG,
            18 => linkrs_error_code_t::LINKRS_CONSTRAINT,
            19 => linkrs_error_code_t::LINKRS_MISMATCH,
            20 => linkrs_error_code_t::LINKRS_MISUSE,
            21 => linkrs_error_code_t::LINKRS_RANGE,
            22 => linkrs_error_code_t::LINKRS_NOT_IMPLEMENTED,
            _ => return Err(()),
        })
    }
}

/// Converting from core error codes to C error codes and extended error codes
pub fn error_code_from_core_error(error: &CoreError) -> (i32, linkrs_extended_error_code_t) {
    // Read-only violations surface as LINKRS_READONLY regardless of the
    // carrying variant (the session gate emits them as `StorageError`).
    if error.to_string().contains("read-only") {
        return (
            linkrs_error_code_t::LINKRS_READONLY as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        );
    }
    match error {
        CoreError::DetailedQueryError { extended_code, .. } => {
            let basic_code = match extended_code {
                ExtendedErrorCode::SyntaxError
                | ExtendedErrorCode::SemanticError
                | ExtendedErrorCode::UnexpectedToken
                | ExtendedErrorCode::UnterminatedLiteral => {
                    linkrs_error_code_t::LINKRS_ERROR as i32
                }
                ExtendedErrorCode::TypeMismatch => linkrs_error_code_t::LINKRS_MISMATCH as i32,
                ExtendedErrorCode::DivisionByZero => linkrs_error_code_t::LINKRS_RANGE as i32,
                ExtendedErrorCode::OutOfRange => linkrs_error_code_t::LINKRS_RANGE as i32,
                ExtendedErrorCode::DuplicateKey => linkrs_error_code_t::LINKRS_CONSTRAINT as i32,
                ExtendedErrorCode::ForeignKeyConstraint => {
                    linkrs_error_code_t::LINKRS_CONSTRAINT as i32
                }
                ExtendedErrorCode::NotNullConstraint => {
                    linkrs_error_code_t::LINKRS_CONSTRAINT as i32
                }
                ExtendedErrorCode::UniqueConstraint => {
                    linkrs_error_code_t::LINKRS_CONSTRAINT as i32
                }
                ExtendedErrorCode::CheckConstraint => linkrs_error_code_t::LINKRS_CONSTRAINT as i32,
                ExtendedErrorCode::ConnectionLost => linkrs_error_code_t::LINKRS_IOERR as i32,
                ExtendedErrorCode::Deadlock => linkrs_error_code_t::LINKRS_BUSY as i32,
                ExtendedErrorCode::LockTimeout => linkrs_error_code_t::LINKRS_BUSY as i32,
                ExtendedErrorCode::InvalidVertex
                | ExtendedErrorCode::InvalidEdge
                | ExtendedErrorCode::PathNotFound => linkrs_error_code_t::LINKRS_NOTFOUND as i32,
                ExtendedErrorCode::Internal => linkrs_error_code_t::LINKRS_ERROR as i32,
                ExtendedErrorCode::None => linkrs_error_code_t::LINKRS_OK as i32,
            };
            (
                basic_code,
                extended_error_code_from_internal(*extended_code),
            )
        }
        CoreError::StorageError(_) => (
            linkrs_error_code_t::LINKRS_IOERR as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::QueryExecutionFailed(msg) => {
            let extended_code = if msg.contains("syntax") {
                linkrs_extended_error_code_t::LINKRS_ERROR_SYNTAX
            } else if msg.contains("semantic") {
                linkrs_extended_error_code_t::LINKRS_ERROR_SEMANTIC
            } else if msg.contains("type mismatch") {
                linkrs_extended_error_code_t::LINKRS_ERROR_TYPE_MISMATCH
            } else if msg.contains("constraint") {
                linkrs_extended_error_code_t::LINKRS_ERROR_CHECK
            } else if msg.contains("division by zero") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DIVISION_BY_ZERO
            } else if msg.contains("out of range") {
                linkrs_extended_error_code_t::LINKRS_ERROR_OUT_OF_RANGE
            } else if msg.contains("duplicate") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DUPLICATE_KEY
            } else if msg.contains("not null") {
                linkrs_extended_error_code_t::LINKRS_ERROR_NOT_NULL
            } else if msg.contains("unique") {
                linkrs_extended_error_code_t::LINKRS_ERROR_UNIQUE
            } else if msg.contains("foreign key") {
                linkrs_extended_error_code_t::LINKRS_ERROR_FOREIGN_KEY
            } else if msg.contains("deadlock") {
                linkrs_extended_error_code_t::LINKRS_ERROR_DEADLOCK
            } else if msg.contains("timeout") {
                linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT
            } else if msg.contains("connection") {
                linkrs_extended_error_code_t::LINKRS_ERROR_CONNECTION_LOST
            } else if msg.contains("vertex") {
                linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_VERTEX
            } else if msg.contains("edge") {
                linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_EDGE
            } else if msg.contains("path") {
                linkrs_extended_error_code_t::LINKRS_ERROR_PATH_NOT_FOUND
            } else {
                linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE
            };
            (linkrs_error_code_t::LINKRS_ERROR as i32, extended_code)
        }
        CoreError::TransactionFailed(message) => {
            let extended_code = transaction_extended_error_code(message);
            let basic_code = match extended_code {
                linkrs_extended_error_code_t::LINKRS_ERROR_NOT_OWNER => {
                    linkrs_error_code_t::LINKRS_PERM
                }
                linkrs_extended_error_code_t::LINKRS_ERROR_CONFLICT
                | linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT => {
                    linkrs_error_code_t::LINKRS_BUSY
                }
                linkrs_extended_error_code_t::LINKRS_ERROR_RECOVERY_REQUIRED => {
                    linkrs_error_code_t::LINKRS_CORRUPT
                }
                linkrs_extended_error_code_t::LINKRS_ERROR_ALREADY_COMPLETED => {
                    linkrs_error_code_t::LINKRS_ABORT
                }
                _ => linkrs_error_code_t::LINKRS_ABORT,
            };
            (basic_code as i32, extended_code)
        }
        CoreError::SchemaOperationFailed(_) => (
            linkrs_error_code_t::LINKRS_SCHEMA as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::Internal(_) => (
            linkrs_error_code_t::LINKRS_INTERNAL as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::NotFound(_) => (
            linkrs_error_code_t::LINKRS_NOTFOUND as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::InvalidParameter(_) => (
            linkrs_error_code_t::LINKRS_MISUSE as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::SyncError(_) => (
            linkrs_error_code_t::LINKRS_IOERR as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
        CoreError::VectorError(_) => (
            linkrs_error_code_t::LINKRS_IOERR as i32,
            linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE,
        ),
    }
}

/// Retrieve the description message corresponding to the error code (termination if the value is null).
pub fn error_code_to_message(code: linkrs_error_code_t) -> &'static [u8] {
    match code {
        linkrs_error_code_t::LINKRS_OK => "OK\0".as_bytes(),
        linkrs_error_code_t::LINKRS_ERROR => "General error\0".as_bytes(),
        linkrs_error_code_t::LINKRS_INTERNAL => "Internal error\0".as_bytes(),
        linkrs_error_code_t::LINKRS_PERM => "Permission denied\0".as_bytes(),
        linkrs_error_code_t::LINKRS_ABORT => "Operation aborted\0".as_bytes(),
        linkrs_error_code_t::LINKRS_BUSY => "Database busy\0".as_bytes(),
        linkrs_error_code_t::LINKRS_LOCKED => "Database locked\0".as_bytes(),
        linkrs_error_code_t::LINKRS_NOMEM => "Out of memory\0".as_bytes(),
        linkrs_error_code_t::LINKRS_READONLY => "Read only\0".as_bytes(),
        linkrs_error_code_t::LINKRS_INTERRUPT => "Operation interrupted\0".as_bytes(),
        linkrs_error_code_t::LINKRS_IOERR => "IO error\0".as_bytes(),
        linkrs_error_code_t::LINKRS_CORRUPT => "Data corruption\0".as_bytes(),
        linkrs_error_code_t::LINKRS_NOTFOUND => "Not found\0".as_bytes(),
        linkrs_error_code_t::LINKRS_FULL => "Disk full\0".as_bytes(),
        linkrs_error_code_t::LINKRS_CANTOPEN => "Cannot open\0".as_bytes(),
        linkrs_error_code_t::LINKRS_PROTOCOL => "Protocol error\0".as_bytes(),
        linkrs_error_code_t::LINKRS_SCHEMA => "Schema error\0".as_bytes(),
        linkrs_error_code_t::LINKRS_TOOBIG => "Data too big\0".as_bytes(),
        linkrs_error_code_t::LINKRS_CONSTRAINT => "Constraint violation\0".as_bytes(),
        linkrs_error_code_t::LINKRS_MISMATCH => "Type mismatch\0".as_bytes(),
        linkrs_error_code_t::LINKRS_MISUSE => "Misuse\0".as_bytes(),
        linkrs_error_code_t::LINKRS_RANGE => "Out of range\0".as_bytes(),
        linkrs_error_code_t::LINKRS_NOT_IMPLEMENTED => "Not implemented\0".as_bytes(),
    }
}

/// Retrieve the description message corresponding to the extended error code (termination occurs if the value is null).
pub fn extended_error_code_to_message(code: linkrs_extended_error_code_t) -> &'static [u8] {
    match code {
        linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE => "No error\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_SYNTAX => "Syntax error\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_SEMANTIC => "Semantic error\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_UNEXPECTED_TOKEN => {
            "Unexpected token\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_UNTERMINATED_LITERAL => {
            "Unterminated literal\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_TYPE_MISMATCH => "Type mismatch\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_DIVISION_BY_ZERO => {
            "Division by zero\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_OUT_OF_RANGE => "Out of range\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_DUPLICATE_KEY => "Duplicate key\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_FOREIGN_KEY => {
            "Foreign key constraint\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_NOT_NULL => "Not null constraint\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_UNIQUE => "Unique constraint\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_CHECK => "Check constraint\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_CONNECTION_LOST => {
            "Connection lost\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_DEADLOCK => "Deadlock\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_LOCK_TIMEOUT => "Lock timeout\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_CONFLICT => "Transaction conflict\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_NOT_OWNER => {
            "Transaction owner mismatch\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_ALREADY_COMPLETED => {
            "Transaction already completed\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_RECOVERY_REQUIRED => {
            "Transaction recovery required\0".as_bytes()
        }
        linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_VERTEX => "Invalid vertex\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_INVALID_EDGE => "Invalid edge\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_PATH_NOT_FOUND => "Path not found\0".as_bytes(),
        linkrs_extended_error_code_t::LINKRS_ERROR_INTERNAL => "Internal error\0".as_bytes(),
    }
}

/// Retrieve the last error message (thread-safe).
///
/// # Arguments
/// - `msg`: Output buffer
/// - `len`: Buffer length
///
/// # Returns
/// - Number of characters actually written (excluding null terminator)
///
/// # Safety
/// - `msg` must be a valid pointer to a buffer with at least `len` bytes
/// - The buffer must be large enough to hold the error message including null terminator
/// - If the message is longer than `len - 1`, it will be truncated
#[no_mangle]
pub unsafe extern "C" fn linkrs_errmsg(msg: *mut std::ffi::c_char, len: usize) -> i32 {
    if msg.is_null() || len == 0 {
        return 0;
    }

    let message = LAST_ERROR_MESSAGE.with(|m| {
        m.borrow().as_ref().map(|s| s.clone()).unwrap_or_else(|| {
            CString::new("No error message").unwrap_or_else(|_| {
                CString::new("?").expect("Failed to create fallback error message")
            })
        })
    });

    let bytes = message.as_bytes_with_nul();
    let copy_len = std::cmp::min(len - 1, bytes.len() - 1);

    unsafe {
        std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const std::ffi::c_char, msg, copy_len);
        *msg.add(copy_len) = 0;
    }

    copy_len as i32
}

/// Retrieve the string description corresponding to the error code (similar to sqlite3_errstr in SQLite).
///
/// # Parameter
/// - `code`: Error Code
///
/// # Return
/// Error description string (static lifecycle; no need for release)
#[no_mangle]
pub extern "C" fn linkrs_errstr(code: i32) -> *const std::ffi::c_char {
    match linkrs_error_code_t::try_from(code) {
        Ok(code) => error_code_to_message(code).as_ptr() as *const std::ffi::c_char,
        Err(()) => b"Unknown error code\0".as_ptr() as *const std::ffi::c_char,
    }
}

/// Get the location of the SQL error (in terms of character offset).
///
/// # Parameters
/// - `session`: session handle
///
/// # Returns
/// - Character offset of the error location, if there is no error or invalid session return -1
#[no_mangle]
pub extern "C" fn linkrs_error_offset(session: *mut linkrs_session_t) -> std::ffi::c_int {
    if session.is_null() {
        return -1;
    }

    unsafe {
        let handle = &*(session as *mut crate::embedded::c_api::session::LinkrsSessionHandle);
        handle
            .last_error_offset
            .map(|o| o as std::ffi::c_int)
            .unwrap_or(-1)
    }
}

/// Get Extended Error Code
///
/// # Parameters
/// - `session`: session handle
///
/// # Returns
/// - Extended error code, returns 0 if no error or invalid session (LINKRS_EXTENDED_NONE)
#[no_mangle]
pub extern "C" fn linkrs_extended_errcode(session: *mut linkrs_session_t) -> std::ffi::c_int {
    if session.is_null() {
        return linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE as std::ffi::c_int;
    }

    unsafe {
        let handle = &*(session as *mut crate::embedded::c_api::session::LinkrsSessionHandle);
        handle
            .last_extended_error
            .map(|e| e as std::ffi::c_int)
            .unwrap_or(linkrs_extended_error_code_t::LINKRS_EXTENDED_NONE as std::ffi::c_int)
    }
}