oxisql-sqlite-compat 0.3.1

Pure-Rust SQLite-compatible backend for OxiSQL via the oxisqlite Pure-Rust engine (C-free fork of limbo)
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
//! Value conversions between `limbo` and `oxisql_core`.
//!
//! # Mapping table
//!
//! | Limbo `limbo::Value`    | OxiSQL [`oxisql_core::Value`] |
//! |-------------------------|-------------------------------|
//! | `Integer(i64)`          | `Value::I64(i64)`             |
//! | `Real(f64)`             | `Value::F64(f64)`             |
//! | `Text(String)`          | `Value::Text(String)`         |
//! | `Blob(Vec<u8>)`         | `Value::Blob(Vec<u8>)`        |
//! | `Null`                  | `Value::Null`                 |
//!
//! The reverse mapping (OxiSQL → Limbo) is used when binding `$N` parameters
//! after they have been rewritten to `?` placeholders by [`rewrite_params`].
//! Rich OxiSQL types that have no Limbo counterpart (Timestamp, Date, Time,
//! Uuid, Decimal, Json) are stored as their string or integer representations.
//!
//! When the column's declared SQL type is known, [`limbo_to_core_typed`] can
//! produce richer typed [`oxisql_core::Value`] variants instead of the raw storage-class
//! representations.

use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use limbo::Value as LimboValue;
use oxisql_core::Value as CoreValue;

use crate::error::SqliteCompatError;

/// Unix epoch as a `NaiveDate` — used for day-count computations.
const UNIX_EPOCH_DATE: fn() -> NaiveDate =
    || NaiveDate::from_ymd_opt(1970, 1, 1).expect("epoch date is valid");

/// Convert a single `limbo::Value` into an `oxisql_core::Value`.
///
/// This is the untyped fallback — all five Limbo storage classes are mapped
/// directly without any enrichment.  Prefer [`limbo_to_core_typed`] when the
/// column's declared SQL type is available.
///
/// # Errors
///
/// Returns [`SqliteCompatError::TypeMap`] for value variants that cannot be
/// represented (currently none — all five Limbo types are mapped).
pub fn limbo_to_core(val: LimboValue) -> Result<CoreValue, SqliteCompatError> {
    limbo_to_core_typed(val, None)
}

/// Convert a single `limbo::Value` into a (possibly richer) `oxisql_core::Value`
/// using an optional declared SQL type hint.
///
/// When `decl_type` matches a known rich type the stored integer or text is
/// lifted into the corresponding typed variant:
///
/// | Declared type            | Storage       | Produced variant           |
/// |--------------------------|---------------|----------------------------|
/// | `DATE` (not DATETIME)    | Text / Int    | `Value::Date(days)`        |
/// | `DATETIME` / `TIMESTAMP` | Text / Int    | `Value::Timestamp(µs)`     |
/// | `TIME` (not TIMESTAMP)   | Text / Int    | `Value::Time(µs)`          |
/// | `UUID`                   | Text / Blob16 | `Value::Uuid(u128)`        |
///
/// Comparison is case-insensitive and prefix-based (e.g. `"timestamp with tz"`
/// still triggers `TIMESTAMP` handling).  If parsing fails the value falls back
/// to the untyped variant instead of returning an error.
///
/// # Errors
///
/// Returns [`SqliteCompatError::TypeMap`] for value variants that cannot be
/// represented (currently none — all five Limbo types are mapped).
pub fn limbo_to_core_typed(
    val: LimboValue,
    decl_type: Option<&str>,
) -> Result<CoreValue, SqliteCompatError> {
    // Normalise the declared type for prefix matching (upper-case once).
    let dt_upper: Option<String> = decl_type.map(|s| s.to_ascii_uppercase());
    let dt = dt_upper.as_deref();

    let v = match val {
        LimboValue::Null => CoreValue::Null,
        LimboValue::Real(f) => CoreValue::F64(f),

        LimboValue::Integer(n) => {
            if let Some(dt) = dt {
                if is_datetime_type(dt) {
                    return Ok(CoreValue::Timestamp(n));
                } else if is_date_type(dt) {
                    // Stored as days since epoch.
                    let days = i32::try_from(n).unwrap_or(n as i32);
                    return Ok(CoreValue::Date(days));
                } else if is_time_type(dt) {
                    return Ok(CoreValue::Time(n));
                }
            }
            CoreValue::I64(n)
        }

        LimboValue::Text(s) => {
            if let Some(dt) = dt {
                if is_datetime_type(dt) {
                    if let Some(ts) = parse_text_as_timestamp(&s) {
                        return Ok(CoreValue::Timestamp(ts));
                    }
                } else if is_date_type(dt) {
                    if let Some(days) = parse_text_as_date(&s) {
                        return Ok(CoreValue::Date(days));
                    }
                } else if is_time_type(dt) {
                    if let Some(us) = parse_text_as_time(&s) {
                        return Ok(CoreValue::Time(us));
                    }
                } else if is_uuid_type(dt) {
                    if let Some(u) = parse_text_as_uuid(&s) {
                        return Ok(CoreValue::Uuid(u));
                    }
                }
            }
            CoreValue::Text(s)
        }

        LimboValue::Blob(b) => {
            // UUID stored as raw 16-byte big-endian blob.
            if let Some(dt) = dt {
                if is_uuid_type(dt) && b.len() == 16 {
                    let mut arr = [0u8; 16];
                    arr.copy_from_slice(&b);
                    let u = u128::from_be_bytes(arr);
                    return Ok(CoreValue::Uuid(u));
                }
            }
            CoreValue::Blob(b)
        }
    };
    Ok(v)
}

// ── Declared-type predicate helpers ───────────────────────────────────────────

/// True when `dt` (already upper-cased) indicates a DATETIME / TIMESTAMP type.
///
/// Must be checked **before** [`is_date_type`] because "DATETIME" starts with
/// "DATE" and "TIMESTAMP" starts with "TIME".
#[inline]
fn is_datetime_type(dt: &str) -> bool {
    dt.starts_with("DATETIME") || dt.starts_with("TIMESTAMP")
}

/// True when `dt` (already upper-cased) indicates a DATE-only type.
///
/// Checked only after ruling out DATETIME.
#[inline]
fn is_date_type(dt: &str) -> bool {
    dt.starts_with("DATE")
}

/// True when `dt` (already upper-cased) indicates a TIME-of-day type.
///
/// Checked only after ruling out TIMESTAMP / DATETIME.
#[inline]
fn is_time_type(dt: &str) -> bool {
    dt.starts_with("TIME")
}

/// True when `dt` (already upper-cased) indicates a UUID type.
#[inline]
fn is_uuid_type(dt: &str) -> bool {
    dt.starts_with("UUID")
}

// ── Text parsing helpers ──────────────────────────────────────────────────────

/// Parse an ISO-8601 datetime string into microseconds since Unix epoch.
///
/// Accepts `"YYYY-MM-DDTHH:MM:SS"`, `"YYYY-MM-DD HH:MM:SS"`, and variants
/// with optional sub-second fractions.  Returns `None` on parse failure.
fn parse_text_as_timestamp(s: &str) -> Option<i64> {
    // Try the two common separator styles (T and space).
    let fmt_t = "%Y-%m-%dT%H:%M:%S%.f";
    let fmt_sp = "%Y-%m-%d %H:%M:%S%.f";
    let fmt_t_no_frac = "%Y-%m-%dT%H:%M:%S";
    let fmt_sp_no_frac = "%Y-%m-%d %H:%M:%S";

    let dt: Option<NaiveDateTime> = NaiveDateTime::parse_from_str(s, fmt_t)
        .or_else(|_| NaiveDateTime::parse_from_str(s, fmt_sp))
        .or_else(|_| NaiveDateTime::parse_from_str(s, fmt_t_no_frac))
        .or_else(|_| NaiveDateTime::parse_from_str(s, fmt_sp_no_frac))
        .ok();

    dt.map(|d| {
        let epoch = NaiveDate::from_ymd_opt(1970, 1, 1)
            .and_then(|d| d.and_hms_opt(0, 0, 0))
            .expect("epoch datetime is valid");
        let dur = d.signed_duration_since(epoch);
        dur.num_microseconds()
            .unwrap_or(dur.num_milliseconds() * 1_000)
    })
}

/// Parse an ISO-8601 date string `"YYYY-MM-DD"` into days since Unix epoch.
///
/// Returns `None` on parse failure.
fn parse_text_as_date(s: &str) -> Option<i32> {
    let d = NaiveDate::parse_from_str(s, "%Y-%m-%d").ok()?;
    let epoch = UNIX_EPOCH_DATE();
    // `signed_duration_since` is always in whole days here because both are
    // date-only values.
    let days = d.signed_duration_since(epoch).num_days();
    i32::try_from(days).ok()
}

/// Parse a time-of-day string into microseconds since midnight.
///
/// Accepts `"HH:MM:SS"` and `"HH:MM:SS.ffffff"`.  Returns `None` on parse
/// failure.
fn parse_text_as_time(s: &str) -> Option<i64> {
    let t: Option<NaiveTime> = NaiveTime::parse_from_str(s, "%H:%M:%S%.f")
        .or_else(|_| NaiveTime::parse_from_str(s, "%H:%M:%S"))
        .ok();
    t.map(|t| {
        let midnight = NaiveTime::from_hms_opt(0, 0, 0).expect("midnight is valid");
        let dur = t.signed_duration_since(midnight);
        dur.num_microseconds()
            .unwrap_or(dur.num_milliseconds() * 1_000)
    })
}

/// Parse a hyphenated UUID string `"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"` into
/// a `u128`.  Returns `None` on parse failure.
fn parse_text_as_uuid(s: &str) -> Option<u128> {
    // Expect exactly 36 bytes: 8-4-4-4-12 hex with dashes.
    if s.len() != 36 {
        return None;
    }
    let parts: Vec<&str> = s.split('-').collect();
    if parts.len() != 5 {
        return None;
    }
    let expected_lens = [8usize, 4, 4, 4, 12];
    for (part, &expected) in parts.iter().zip(expected_lens.iter()) {
        if part.len() != expected {
            return None;
        }
    }

    // Concatenate all hex digits and parse as u128.
    let hex: String = parts.concat();
    u128::from_str_radix(&hex, 16).ok()
}

/// Convert an `oxisql_core::Value` into a `limbo::Value`.
///
/// Rich OxiSQL types are coerced to the closest SQLite storage class:
/// - `Bool`      → `Integer` (0 / 1)
/// - `Timestamp` → `Integer` (microseconds since epoch)
/// - `Date`      → `Integer` (days since epoch)
/// - `Time`      → `Integer` (microseconds since midnight)
/// - `Uuid`      → `Text`    (hyphenated UUID string)
/// - `Decimal`   → `Text`    (decimal string)
/// - `Json`      → `Text`    (JSON string)
/// - `Array`     → `Text`    (debug representation — not round-trippable)
///
/// # Errors
///
/// Returns [`SqliteCompatError::TypeMap`] when a `Uuid` value cannot be
/// formatted (should never occur in practice).
pub fn core_to_limbo(val: &CoreValue) -> Result<LimboValue, SqliteCompatError> {
    let v = match val {
        CoreValue::Null => LimboValue::Null,
        CoreValue::Bool(b) => LimboValue::Integer(i64::from(*b)),
        CoreValue::I64(n) => LimboValue::Integer(*n),
        CoreValue::F64(f) => LimboValue::Real(*f),
        CoreValue::Text(s) => LimboValue::Text(s.clone()),
        CoreValue::Blob(b) => LimboValue::Blob(b.clone()),
        CoreValue::Timestamp(us) => LimboValue::Integer(*us),
        CoreValue::Date(days) => LimboValue::Integer(i64::from(*days)),
        CoreValue::Time(us) => LimboValue::Integer(*us),
        CoreValue::Uuid(u) => {
            // Format as hyphenated UUID string (16 bytes / u128).
            let hi = (u >> 64) as u64;
            let lo = *u as u64;
            let raw: [u8; 16] = {
                let mut buf = [0u8; 16];
                buf[..8].copy_from_slice(&hi.to_be_bytes());
                buf[8..].copy_from_slice(&lo.to_be_bytes());
                buf
            };
            let s = format!(
                "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
                u32::from_be_bytes(
                    raw[0..4]
                        .try_into()
                        .map_err(|_| SqliteCompatError::TypeMap("uuid slice error".into()))?
                ),
                u16::from_be_bytes(
                    raw[4..6]
                        .try_into()
                        .map_err(|_| SqliteCompatError::TypeMap("uuid slice error".into()))?
                ),
                u16::from_be_bytes(
                    raw[6..8]
                        .try_into()
                        .map_err(|_| SqliteCompatError::TypeMap("uuid slice error".into()))?
                ),
                u16::from_be_bytes(
                    raw[8..10]
                        .try_into()
                        .map_err(|_| SqliteCompatError::TypeMap("uuid slice error".into()))?
                ),
                {
                    let b = &raw[10..16];
                    ((b[0] as u64) << 40)
                        | ((b[1] as u64) << 32)
                        | ((b[2] as u64) << 24)
                        | ((b[3] as u64) << 16)
                        | ((b[4] as u64) << 8)
                        | (b[5] as u64)
                }
            );
            LimboValue::Text(s)
        }
        CoreValue::Decimal(s) | CoreValue::Json(s) => LimboValue::Text(s.clone()),
        CoreValue::Array(arr) => LimboValue::Text(format!("{arr:?}")),
        CoreValue::TypedArray { values: arr, .. } => LimboValue::Text(format!("{arr:?}")),
    };
    Ok(v)
}

/// Split a SQL string containing multiple statements separated by `;` into
/// individual statement slices.
///
/// The splitter is token-aware: semicolons that appear inside single-quoted
/// string literals (`'...'`), double-quoted identifiers (`"..."`),
/// backtick-quoted identifiers (`` `...` ``), block comments (`/* ... */`),
/// or line comments (`-- ...`) are **not** treated as statement boundaries.
///
/// # Behaviour
///
/// - SQL-standard `''` escape sequences inside single-quoted strings are
///   recognised, so `'it''s ok; really'` is treated as one token.
/// - Unterminated strings or comments at end-of-input are passed through
///   without error; the SQL engine will surface a syntax error if needed.
/// - Empty statements (e.g. `;;`) are silently dropped.
/// - The returned slices borrow from `sql` and are already trimmed of
///   leading/trailing whitespace.
pub(crate) fn split_statements(sql: &str) -> Vec<&str> {
    let mut stmts = Vec::new();
    let bytes = sql.as_bytes();
    let len = bytes.len();
    let mut i = 0usize;
    let mut stmt_start = 0usize;

    while i < len {
        match bytes[i] {
            b'\'' => {
                // Single-quoted string: advance past the closing `'`, handling
                // `''` escape sequences.
                i += 1;
                while i < len {
                    if bytes[i] == b'\'' {
                        if i + 1 < len && bytes[i + 1] == b'\'' {
                            i += 2; // escaped ''
                        } else {
                            i += 1; // closing quote
                            break;
                        }
                    } else {
                        i += 1;
                    }
                }
            }
            b'"' => {
                // Double-quoted identifier — advance to the matching `"`.
                i += 1;
                while i < len && bytes[i] != b'"' {
                    i += 1;
                }
                if i < len {
                    i += 1; // consume closing "
                }
            }
            b'`' => {
                // Backtick-quoted identifier (MySQL-style; SQLite accepts it).
                i += 1;
                while i < len && bytes[i] != b'`' {
                    i += 1;
                }
                if i < len {
                    i += 1; // consume closing `
                }
            }
            b'-' if i + 1 < len && bytes[i + 1] == b'-' => {
                // Line comment: skip to the end of the line.
                while i < len && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if i + 1 < len && bytes[i + 1] == b'*' => {
                // Block comment: skip to the closing `*/`.
                i += 2;
                while i + 1 < len {
                    if bytes[i] == b'*' && bytes[i + 1] == b'/' {
                        i += 2;
                        break;
                    }
                    i += 1;
                }
            }
            b';' => {
                let stmt = sql[stmt_start..i].trim();
                if !stmt.is_empty() {
                    stmts.push(stmt);
                }
                i += 1;
                stmt_start = i;
            }
            _ => {
                i += 1;
            }
        }
    }

    // Handle a trailing statement that has no terminating `;`.
    let tail = sql[stmt_start..].trim();
    if !tail.is_empty() {
        stmts.push(tail);
    }

    stmts
}

/// Rewrite OxiSQL-style `$N` positional placeholders to SQLite `?` placeholders,
/// returning the reordered parameter list.
///
/// # Behaviour
///
/// - `$1`, `$2`, … are replaced left-to-right with `?`.
/// - Parameters inside single-quoted string literals (`'...'`) are preserved.
/// - Double-quoted identifiers (`"..."`) are similarly skipped.
/// - The returned `params` vec is ordered by `$N` index (1-based), so `$2, $1`
///   in the SQL results in `[params[1], params[0]]` in the output.
///
/// # Errors
///
/// Returns [`SqliteCompatError::TypeMap`] if a placeholder references a parameter
/// index that is out of range for the supplied `params` slice.
pub fn rewrite_params(
    sql: &str,
    params: &[&dyn oxisql_core::ToSqlValue],
) -> Result<(String, Vec<LimboValue>), SqliteCompatError> {
    let mut out = String::with_capacity(sql.len());
    let mut ordered: Vec<LimboValue> = Vec::new();
    let chars: Vec<char> = sql.chars().collect();
    let n = chars.len();
    let mut i = 0;

    while i < n {
        match chars[i] {
            // Single-quoted string literal — copy verbatim.
            '\'' => {
                out.push('\'');
                i += 1;
                while i < n {
                    let c = chars[i];
                    out.push(c);
                    i += 1;
                    if c == '\'' {
                        // Escaped quote ''
                        if i < n && chars[i] == '\'' {
                            out.push('\'');
                            i += 1;
                        } else {
                            break;
                        }
                    }
                }
            }
            // Double-quoted identifier — copy verbatim.
            '"' => {
                out.push('"');
                i += 1;
                while i < n && chars[i] != '"' {
                    out.push(chars[i]);
                    i += 1;
                }
                if i < n {
                    out.push('"');
                    i += 1;
                }
            }
            // Potential positional parameter $N.
            '$' => {
                i += 1;
                // Collect digits.
                let start = i;
                while i < n && chars[i].is_ascii_digit() {
                    i += 1;
                }
                if i > start {
                    let idx_str: String = chars[start..i].iter().collect();
                    let idx: usize = idx_str.parse::<usize>().map_err(|_| {
                        SqliteCompatError::TypeMap(format!(
                            "invalid parameter placeholder: ${idx_str}"
                        ))
                    })?;
                    if idx == 0 || idx > params.len() {
                        return Err(SqliteCompatError::TypeMap(format!(
                            "parameter ${idx} is out of range (have {} params)",
                            params.len()
                        )));
                    }
                    let limbo_val = core_to_limbo(&params[idx - 1].to_value())?;
                    ordered.push(limbo_val);
                    out.push('?');
                } else {
                    // Bare `$` with no digits — pass through unchanged.
                    out.push('$');
                }
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }

    Ok((out, ordered))
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── split_statements ──────────────────────────────────────────────────────

    #[test]
    fn test_split_basic() {
        let stmts = split_statements("SELECT 1; SELECT 2");
        assert_eq!(stmts, vec!["SELECT 1", "SELECT 2"]);
    }

    #[test]
    fn test_split_trailing_semicolon() {
        let stmts = split_statements("SELECT 1; SELECT 2;");
        assert_eq!(stmts, vec!["SELECT 1", "SELECT 2"]);
    }

    #[test]
    fn test_split_single_statement_no_semicolon() {
        let stmts = split_statements("SELECT 1");
        assert_eq!(stmts, vec!["SELECT 1"]);
    }

    #[test]
    fn test_split_empty_statements() {
        let stmts = split_statements(";;;");
        assert!(stmts.is_empty(), "expected 0 stmts, got {stmts:?}");
    }

    #[test]
    fn test_split_whitespace_only() {
        let stmts = split_statements("   \n  ");
        assert!(stmts.is_empty());
    }

    #[test]
    fn test_split_semicolon_in_single_quoted_string() {
        let stmts = split_statements("INSERT INTO t VALUES ('a;b')");
        assert_eq!(stmts, vec!["INSERT INTO t VALUES ('a;b')"]);
    }

    #[test]
    fn test_split_escaped_single_quotes() {
        // 'it''s ok;really' contains a '' escape and a ; — neither should split.
        let stmts = split_statements("INSERT INTO t VALUES ('it''s ok;really')");
        assert_eq!(stmts, vec!["INSERT INTO t VALUES ('it''s ok;really')"]);
    }

    #[test]
    fn test_split_double_quoted_identifier() {
        let stmts = split_statements(r#"SELECT "col;name" FROM t"#);
        assert_eq!(stmts, vec![r#"SELECT "col;name" FROM t"#]);
    }

    #[test]
    fn test_split_backtick_quoted_identifier() {
        let stmts = split_statements("SELECT `col;name` FROM t");
        assert_eq!(stmts, vec!["SELECT `col;name` FROM t"]);
    }

    #[test]
    fn test_split_line_comment() {
        // The ; after -- must not be a statement boundary.
        let stmts = split_statements("SELECT 1 -- ; this is a comment\n");
        assert_eq!(stmts, vec!["SELECT 1 -- ; this is a comment"]);
    }

    #[test]
    fn test_split_line_comment_between_stmts() {
        let sql = "SELECT 1; -- comment with ; semicolon\nSELECT 2";
        let stmts = split_statements(sql);
        assert_eq!(stmts.len(), 2, "got {stmts:?}");
        assert_eq!(stmts[0], "SELECT 1");
        assert_eq!(stmts[1], "-- comment with ; semicolon\nSELECT 2");
    }

    #[test]
    fn test_split_block_comment() {
        let stmts = split_statements("SELECT /* ; */ 1");
        assert_eq!(stmts, vec!["SELECT /* ; */ 1"]);
    }

    #[test]
    fn test_split_block_comment_spanning_stmts() {
        let sql = "SELECT 1; /* comment; with semicolons */ SELECT 2";
        let stmts = split_statements(sql);
        assert_eq!(stmts.len(), 2, "got {stmts:?}");
        assert_eq!(stmts[0], "SELECT 1");
        assert_eq!(stmts[1], "/* comment; with semicolons */ SELECT 2");
    }

    #[test]
    fn test_split_multiple_with_trailing_no_semicolon() {
        let sql = "CREATE TABLE t (id INT);\nINSERT INTO t VALUES (1)";
        let stmts = split_statements(sql);
        assert_eq!(stmts.len(), 2, "got {stmts:?}");
        assert_eq!(stmts[0], "CREATE TABLE t (id INT)");
        assert_eq!(stmts[1], "INSERT INTO t VALUES (1)");
    }

    #[test]
    fn test_split_trims_whitespace() {
        let stmts = split_statements("  SELECT 1  ;  SELECT 2  ");
        assert_eq!(stmts, vec!["SELECT 1", "SELECT 2"]);
    }

    // ── limbo_to_core ─────────────────────────────────────────────────────────

    #[test]
    fn test_limbo_to_core_all_types() {
        assert_eq!(limbo_to_core(LimboValue::Null).unwrap(), CoreValue::Null);
        assert_eq!(
            limbo_to_core(LimboValue::Integer(42)).unwrap(),
            CoreValue::I64(42)
        );
        assert_eq!(
            limbo_to_core(LimboValue::Real(1.5)).unwrap(),
            CoreValue::F64(1.5)
        );
        assert_eq!(
            limbo_to_core(LimboValue::Text("hello".into())).unwrap(),
            CoreValue::Text("hello".into())
        );
        assert_eq!(
            limbo_to_core(LimboValue::Blob(vec![1, 2, 3])).unwrap(),
            CoreValue::Blob(vec![1, 2, 3])
        );
    }

    #[test]
    fn test_core_to_limbo_basic() {
        assert_eq!(core_to_limbo(&CoreValue::Null).unwrap(), LimboValue::Null);
        assert_eq!(
            core_to_limbo(&CoreValue::I64(7)).unwrap(),
            LimboValue::Integer(7)
        );
        assert_eq!(
            core_to_limbo(&CoreValue::F64(1.5)).unwrap(),
            LimboValue::Real(1.5)
        );
        assert_eq!(
            core_to_limbo(&CoreValue::Bool(true)).unwrap(),
            LimboValue::Integer(1)
        );
    }

    #[test]
    fn test_rewrite_params_basic() {
        let params: Vec<&dyn oxisql_core::ToSqlValue> = vec![&42i64, &"hello"];
        let (sql, vals) = rewrite_params("SELECT $1, $2", &params).unwrap();
        assert_eq!(sql, "SELECT ?, ?");
        assert_eq!(vals.len(), 2);
        assert_eq!(vals[0], LimboValue::Integer(42));
        assert_eq!(vals[1], LimboValue::Text("hello".into()));
    }

    #[test]
    fn test_rewrite_params_skips_string_literals() {
        let params: Vec<&dyn oxisql_core::ToSqlValue> = vec![&99i64];
        let (sql, vals) = rewrite_params("SELECT '$1' WHERE id = $1", &params).unwrap();
        assert_eq!(sql, "SELECT '$1' WHERE id = ?");
        assert_eq!(vals.len(), 1);
        assert_eq!(vals[0], LimboValue::Integer(99));
    }

    #[test]
    fn test_rewrite_params_out_of_range() {
        let params: Vec<&dyn oxisql_core::ToSqlValue> = vec![&1i64];
        assert!(rewrite_params("SELECT $2", &params).is_err());
    }

    #[test]
    fn test_rewrite_params_no_params() {
        let params: &[&dyn oxisql_core::ToSqlValue] = &[];
        let (sql, vals) = rewrite_params("SELECT 1", params).unwrap();
        assert_eq!(sql, "SELECT 1");
        assert!(vals.is_empty());
    }
}