stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
// 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.

//! JSON SQL Tests
//!
//! Tests JSON data type support in SQL statements

use stoolap::Database;

/// Test creating tables with JSON columns
#[test]
fn test_json_create_table() {
    let db = Database::open("memory://json_create").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON,
            required_json JSON NOT NULL
        )",
        (),
    )
    .expect("Failed to create table with JSON columns");
}

/// Test inserting JSON data
#[test]
fn test_json_insert() {
    let db = Database::open("memory://json_insert").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON,
            required_json JSON NOT NULL
        )",
        (),
    )
    .expect("Failed to create table");

    // Insert simple object
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (?, ?, ?)",
        (1, r#"{"name":"John","age":30}"#, r#"{"type":"required"}"#),
    )
    .expect("Failed to insert simple object");

    // Insert array
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (?, ?, ?)",
        (2, "[1,2,3,4]", r#"{"type":"array"}"#),
    )
    .expect("Failed to insert array");

    // Insert nested object
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (?, ?, ?)",
        (
            3,
            r#"{"user":{"name":"Jane","age":25,"roles":["admin","user"]}}"#,
            r#"{"type":"nested"}"#,
        ),
    )
    .expect("Failed to insert nested object");

    // Insert NULL value
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (4, NULL, '{\"type\":\"null_test\"}')", ())
    .expect("Failed to insert NULL value");

    // Insert empty object
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (?, ?, ?)",
        (5, "{}", r#"{"type":"empty"}"#),
    )
    .expect("Failed to insert empty object");

    // Insert empty array
    db.execute(
        "INSERT INTO json_test (id, data, required_json) VALUES (?, ?, ?)",
        (6, "[]", r#"{"type":"empty_array"}"#),
    )
    .expect("Failed to insert empty array");

    // Verify count
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM json_test", ())
        .expect("Failed to count");
    assert_eq!(count, 6, "Expected 6 rows inserted");
}

/// Test selecting JSON data
#[test]
fn test_json_select() {
    let db = Database::open("memory://json_select").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (1, '{"name":"John","age":30}')"#,
        (),
    )
    .expect("Failed to insert");

    // Query by ID
    let result = db
        .query("SELECT id, data FROM json_test WHERE id = 1", ())
        .expect("Failed to query");

    let mut found = false;
    for row in result {
        let row = row.expect("Failed to get row");
        let id: i64 = row.get(0).unwrap();
        let data: String = row.get(1).unwrap();

        assert_eq!(id, 1);
        assert!(data.contains("John"), "Expected data to contain 'John'");
        found = true;
    }
    assert!(found, "Expected to find row with id=1");
}

/// Test updating JSON data
#[test]
fn test_json_update() {
    let db = Database::open("memory://json_update").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (1, '{"name":"John","age":30}')"#,
        (),
    )
    .expect("Failed to insert");

    // Update the JSON
    db.execute(
        "UPDATE json_test SET data = ? WHERE id = ?",
        (r#"{"updated":true,"name":"UpdatedValue"}"#, 1),
    )
    .expect("Failed to update");

    // Verify update
    let result = db
        .query("SELECT data FROM json_test WHERE id = 1", ())
        .expect("Failed to query");

    for row in result {
        let row = row.expect("Failed to get row");
        let data: String = row.get(0).unwrap();
        assert!(
            data.contains("updated") || data.contains("Updated"),
            "Expected updated data, got: {}",
            data
        );
    }
}

/// Test JSON literal in INSERT
#[test]
fn test_json_literal_insert() {
    let db = Database::open("memory://json_literal").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    // Insert with JSON literal
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (100, '{"literal":true}')"#,
        (),
    )
    .expect("Failed to insert with literal");

    // Verify
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM json_test WHERE id = 100", ())
        .expect("Failed to count");
    assert_eq!(count, 1, "Expected 1 row with id=100");
}

/// Test parameterized nested JSON
#[test]
fn test_json_nested_param() {
    let db = Database::open("memory://json_nested").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    db.execute(
        "INSERT INTO json_test (id, data) VALUES (?, ?)",
        (101, r#"{"deep":{"nested":{"value":42}}}"#),
    )
    .expect("Failed to insert nested");

    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM json_test WHERE id = 101", ())
        .expect("Failed to count");
    assert_eq!(count, 1, "Expected 1 row with id=101");
}

/// Test JSON with various data types in values
#[test]
fn test_json_various_types() {
    let db = Database::open("memory://json_types").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    // Boolean values
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (1, '{"active":true,"deleted":false}')"#,
        (),
    )
    .expect("Failed to insert boolean");

    // Numeric values
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (2, '{"integer":42,"float":3.14,"negative":-100}')"#, ())
    .expect("Failed to insert numeric");

    // Null value in JSON
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (3, '{"value":null}')"#,
        (),
    )
    .expect("Failed to insert null value");

    // String with special characters (escaped quotes in JSON)
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (4, '{"text":"Hello \"World\""}')"#,
        (),
    )
    .expect("Failed to insert special chars");

    // Verify all inserted
    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM json_test", ())
        .expect("Failed to count");
    assert_eq!(count, 4, "Expected 4 rows");
}

/// Test JSON array operations
#[test]
fn test_json_arrays() {
    let db = Database::open("memory://json_arrays").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_test (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    // Empty array
    db.execute("INSERT INTO json_test (id, data) VALUES (1, '[]')", ())
        .expect("Failed to insert empty array");

    // Number array
    db.execute(
        "INSERT INTO json_test (id, data) VALUES (2, '[1,2,3,4,5]')",
        (),
    )
    .expect("Failed to insert number array");

    // String array
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (3, '["a","b","c"]')"#,
        (),
    )
    .expect("Failed to insert string array");

    // Mixed array
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (4, '[1,"two",true,null]')"#,
        (),
    )
    .expect("Failed to insert mixed array");

    // Nested arrays
    db.execute(
        "INSERT INTO json_test (id, data) VALUES (5, '[[1,2],[3,4]]')",
        (),
    )
    .expect("Failed to insert nested arrays");

    // Array of objects
    db.execute(
        r#"INSERT INTO json_test (id, data) VALUES (6, '[{"name":"John"},{"name":"Jane"}]')"#,
        (),
    )
    .expect("Failed to insert array of objects");

    let count: i64 = db
        .query_one("SELECT COUNT(*) FROM json_test", ())
        .expect("Failed to count");
    assert_eq!(count, 6, "Expected 6 rows");
}

/// Test JSON_TYPE function
#[test]
fn test_json_type_function() {
    let db = Database::open("memory://json_type").expect("Failed to create database");

    // Test with string literal
    let result: String = db
        .query_one("SELECT JSON_TYPE('\"hello\"')", ())
        .expect("Failed to get JSON_TYPE for string");
    assert_eq!(result, "string");

    // Test with number
    let result: String = db
        .query_one("SELECT JSON_TYPE('123')", ())
        .expect("Failed to get JSON_TYPE for number");
    assert_eq!(result, "number");

    // Test with float
    let result: String = db
        .query_one("SELECT JSON_TYPE('3.14')", ())
        .expect("Failed to get JSON_TYPE for float");
    assert_eq!(result, "number");

    // Test with boolean true
    let result: String = db
        .query_one("SELECT JSON_TYPE('true')", ())
        .expect("Failed to get JSON_TYPE for boolean");
    assert_eq!(result, "boolean");

    // Test with boolean false
    let result: String = db
        .query_one("SELECT JSON_TYPE('false')", ())
        .expect("Failed to get JSON_TYPE for boolean false");
    assert_eq!(result, "boolean");

    // Test with null
    let result: String = db
        .query_one("SELECT JSON_TYPE('null')", ())
        .expect("Failed to get JSON_TYPE for null");
    assert_eq!(result, "null");

    // Test with object
    let result: String = db
        .query_one("SELECT JSON_TYPE('{\"a\":1}')", ())
        .expect("Failed to get JSON_TYPE for object");
    assert_eq!(result, "object");

    // Test with array
    let result: String = db
        .query_one("SELECT JSON_TYPE('[1,2,3]')", ())
        .expect("Failed to get JSON_TYPE for array");
    assert_eq!(result, "array");

    // Test with empty object
    let result: String = db
        .query_one("SELECT JSON_TYPE('{}')", ())
        .expect("Failed to get JSON_TYPE for empty object");
    assert_eq!(result, "object");

    // Test with empty array
    let result: String = db
        .query_one("SELECT JSON_TYPE('[]')", ())
        .expect("Failed to get JSON_TYPE for empty array");
    assert_eq!(result, "array");
}

/// Test JSON_TYPEOF function (alias for JSON_TYPE)
#[test]
fn test_json_typeof_function() {
    let db = Database::open("memory://json_typeof").expect("Failed to create database");

    // Test that JSON_TYPEOF returns same results as JSON_TYPE
    let result: String = db
        .query_one("SELECT JSON_TYPEOF('{\"key\":\"value\"}')", ())
        .expect("Failed to get JSON_TYPEOF for object");
    assert_eq!(result, "object");

    let result: String = db
        .query_one("SELECT JSON_TYPEOF('[1,2,3]')", ())
        .expect("Failed to get JSON_TYPEOF for array");
    assert_eq!(result, "array");

    let result: String = db
        .query_one("SELECT JSON_TYPEOF('\"string\"')", ())
        .expect("Failed to get JSON_TYPEOF for string");
    assert_eq!(result, "string");

    let result: String = db
        .query_one("SELECT JSON_TYPEOF('42')", ())
        .expect("Failed to get JSON_TYPEOF for number");
    assert_eq!(result, "number");
}

/// Test JSON_VALID function
#[test]
fn test_json_valid_function() {
    let db = Database::open("memory://json_valid").expect("Failed to create database");

    // Test valid JSON object
    let result: i64 = db
        .query_one("SELECT JSON_VALID('{\"a\":1}')", ())
        .expect("Failed to get JSON_VALID for valid object");
    assert_eq!(result, 1);

    // Test valid JSON array
    let result: i64 = db
        .query_one("SELECT JSON_VALID('[1,2,3]')", ())
        .expect("Failed to get JSON_VALID for valid array");
    assert_eq!(result, 1);

    // Test valid JSON string
    let result: i64 = db
        .query_one("SELECT JSON_VALID('\"hello\"')", ())
        .expect("Failed to get JSON_VALID for valid string");
    assert_eq!(result, 1);

    // Test valid JSON number
    let result: i64 = db
        .query_one("SELECT JSON_VALID('123')", ())
        .expect("Failed to get JSON_VALID for valid number");
    assert_eq!(result, 1);

    // Test valid JSON boolean
    let result: i64 = db
        .query_one("SELECT JSON_VALID('true')", ())
        .expect("Failed to get JSON_VALID for valid boolean");
    assert_eq!(result, 1);

    // Test valid JSON null
    let result: i64 = db
        .query_one("SELECT JSON_VALID('null')", ())
        .expect("Failed to get JSON_VALID for valid null");
    assert_eq!(result, 1);

    // Test invalid JSON - missing quotes
    let result: i64 = db
        .query_one("SELECT JSON_VALID('invalid')", ())
        .expect("Failed to get JSON_VALID for invalid");
    assert_eq!(result, 0);

    // Test invalid JSON - incomplete object
    let result: i64 = db
        .query_one("SELECT JSON_VALID('{incomplete')", ())
        .expect("Failed to get JSON_VALID for incomplete object");
    assert_eq!(result, 0);

    // Test invalid JSON - trailing comma
    let result: i64 = db
        .query_one("SELECT JSON_VALID('[1,2,3,]')", ())
        .expect("Failed to get JSON_VALID for trailing comma");
    assert_eq!(result, 0);

    // Test invalid JSON - single quotes (JSON requires double quotes)
    let result: i64 = db
        .query_one("SELECT JSON_VALID('{''key'':''value''}')", ())
        .expect("Failed to get JSON_VALID for single quotes");
    assert_eq!(result, 0);

    // Test empty string (not valid JSON)
    let result: i64 = db
        .query_one("SELECT JSON_VALID('')", ())
        .expect("Failed to get JSON_VALID for empty string");
    assert_eq!(result, 0);
}

/// Test JSON_KEYS function
#[test]
fn test_json_keys_function() {
    let db = Database::open("memory://json_keys").expect("Failed to create database");

    // Test with simple object
    let result: String = db
        .query_one("SELECT JSON_KEYS('{\"name\":\"John\",\"age\":30}')", ())
        .expect("Failed to get JSON_KEYS for object");
    // Keys are returned as JSON array, order may vary
    assert!(result.contains("\"name\""));
    assert!(result.contains("\"age\""));

    // Test with nested object - should only return top-level keys
    let result: String = db
        .query_one(
            "SELECT JSON_KEYS('{\"user\":{\"name\":\"John\"},\"active\":true}')",
            (),
        )
        .expect("Failed to get JSON_KEYS for nested object");
    assert!(result.contains("\"user\""));
    assert!(result.contains("\"active\""));
    assert!(!result.contains("\"name\"")); // name is nested, not top-level

    // Test with empty object
    let result: String = db
        .query_one("SELECT JSON_KEYS('{}')", ())
        .expect("Failed to get JSON_KEYS for empty object");
    assert_eq!(result, "[]");

    // Test with single key
    let result: String = db
        .query_one("SELECT JSON_KEYS('{\"key\":\"value\"}')", ())
        .expect("Failed to get JSON_KEYS for single key");
    assert!(result.contains("\"key\""));
}

/// Test JSON_KEYS returns NULL for non-object types
#[test]
fn test_json_keys_non_object() {
    let db = Database::open("memory://json_keys_null").expect("Failed to create database");

    // Test with array - should return NULL
    let result = db
        .query("SELECT JSON_KEYS('[1,2,3]')", ())
        .expect("Failed to query JSON_KEYS for array");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_KEYS on array should return NULL");

    // Test with string - should return NULL
    let result = db
        .query("SELECT JSON_KEYS('\"hello\"')", ())
        .expect("Failed to query JSON_KEYS for string");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_KEYS on string should return NULL");

    // Test with number - should return NULL
    let result = db
        .query("SELECT JSON_KEYS('123')", ())
        .expect("Failed to query JSON_KEYS for number");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_KEYS on number should return NULL");
}

/// Test JSON functions with NULL input
#[test]
fn test_json_functions_with_null() {
    let db = Database::open("memory://json_null_input").expect("Failed to create database");

    // JSON_TYPE with NULL should return NULL
    let result = db
        .query("SELECT JSON_TYPE(NULL)", ())
        .expect("Failed to query JSON_TYPE with NULL");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_TYPE(NULL) should return NULL");

    // JSON_VALID with NULL should return NULL
    let result = db
        .query("SELECT JSON_VALID(NULL)", ())
        .expect("Failed to query JSON_VALID with NULL");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_VALID(NULL) should return NULL");

    // JSON_KEYS with NULL should return NULL
    let result = db
        .query("SELECT JSON_KEYS(NULL)", ())
        .expect("Failed to query JSON_KEYS with NULL");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(row.is_null(0), "JSON_KEYS(NULL) should return NULL");
}

/// Test JSON functions with table data
#[test]
fn test_json_functions_with_table() {
    let db = Database::open("memory://json_func_table").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_data (
            id INTEGER NOT NULL,
            data JSON
        )",
        (),
    )
    .expect("Failed to create table");

    // Insert various JSON types
    db.execute(
        "INSERT INTO json_data (id, data) VALUES (1, '{\"name\":\"John\",\"age\":30}')",
        (),
    )
    .expect("Failed to insert object");
    db.execute("INSERT INTO json_data (id, data) VALUES (2, '[1,2,3]')", ())
        .expect("Failed to insert array");
    db.execute(
        "INSERT INTO json_data (id, data) VALUES (3, '\"string\"')",
        (),
    )
    .expect("Failed to insert string");
    db.execute("INSERT INTO json_data (id, data) VALUES (4, '42')", ())
        .expect("Failed to insert number");
    db.execute("INSERT INTO json_data (id, data) VALUES (5, NULL)", ())
        .expect("Failed to insert null");

    // Query JSON_TYPE for each row
    let result = db
        .query(
            "SELECT id, JSON_TYPE(data) as type FROM json_data ORDER BY id",
            (),
        )
        .expect("Failed to query");

    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 5);

    // Check each type
    let row = rows[0].as_ref().expect("Failed to get row 1");
    let id: i64 = row.get(0).unwrap();
    let json_type: String = row.get(1).unwrap();
    assert_eq!(id, 1);
    assert_eq!(json_type, "object");

    let row = rows[1].as_ref().expect("Failed to get row 2");
    let id: i64 = row.get(0).unwrap();
    let json_type: String = row.get(1).unwrap();
    assert_eq!(id, 2);
    assert_eq!(json_type, "array");

    let row = rows[2].as_ref().expect("Failed to get row 3");
    let id: i64 = row.get(0).unwrap();
    let json_type: String = row.get(1).unwrap();
    assert_eq!(id, 3);
    assert_eq!(json_type, "string");

    let row = rows[3].as_ref().expect("Failed to get row 4");
    let id: i64 = row.get(0).unwrap();
    let json_type: String = row.get(1).unwrap();
    assert_eq!(id, 4);
    assert_eq!(json_type, "number");

    let row = rows[4].as_ref().expect("Failed to get row 5");
    let id: i64 = row.get(0).unwrap();
    assert_eq!(id, 5);
    assert!(row.is_null(1), "JSON_TYPE of NULL should be NULL");
}

/// Test JSON_VALID filtering in WHERE clause
#[test]
fn test_json_valid_in_where() {
    let db = Database::open("memory://json_valid_where").expect("Failed to create database");

    db.execute(
        "CREATE TABLE json_strings (
            id INTEGER NOT NULL,
            content TEXT
        )",
        (),
    )
    .expect("Failed to create table");

    // Insert valid and invalid JSON strings
    db.execute(
        "INSERT INTO json_strings (id, content) VALUES (1, '{\"valid\":true}')",
        (),
    )
    .expect("Failed to insert valid JSON");
    db.execute(
        "INSERT INTO json_strings (id, content) VALUES (2, 'invalid json')",
        (),
    )
    .expect("Failed to insert invalid JSON");
    db.execute(
        "INSERT INTO json_strings (id, content) VALUES (3, '[1,2,3]')",
        (),
    )
    .expect("Failed to insert valid array");
    db.execute(
        "INSERT INTO json_strings (id, content) VALUES (4, '{broken')",
        (),
    )
    .expect("Failed to insert broken JSON");

    // Select only valid JSON using JSON_VALID
    let count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM json_strings WHERE JSON_VALID(content) = 1",
            (),
        )
        .expect("Failed to count valid JSON");
    assert_eq!(count, 2, "Expected 2 valid JSON rows");

    // Select only invalid JSON
    let count: i64 = db
        .query_one(
            "SELECT COUNT(*) FROM json_strings WHERE JSON_VALID(content) = 0",
            (),
        )
        .expect("Failed to count invalid JSON");
    assert_eq!(count, 2, "Expected 2 invalid JSON rows");
}

/// Test JSON_TYPE with two arguments (path extraction)
#[test]
fn test_json_type_with_path() {
    let db = Database::open("memory://json_type_path").expect("Failed to create database");

    // Test extracting type at path - number
    let result: String = db
        .query_one(
            "SELECT JSON_TYPE('{\"name\":\"John\",\"age\":30}', '$.age')",
            (),
        )
        .expect("Failed to get JSON_TYPE with path for number");
    assert_eq!(result, "number");

    // Test extracting type at path - string
    let result: String = db
        .query_one(
            "SELECT JSON_TYPE('{\"name\":\"John\",\"age\":30}', '$.name')",
            (),
        )
        .expect("Failed to get JSON_TYPE with path for string");
    assert_eq!(result, "string");

    // Test extracting type at path - object
    let result: String = db
        .query_one("SELECT JSON_TYPE('{\"user\":{\"id\":1}}', '$.user')", ())
        .expect("Failed to get JSON_TYPE with path for object");
    assert_eq!(result, "object");

    // Test extracting type at path - array
    let result: String = db
        .query_one("SELECT JSON_TYPE('{\"tags\":[\"a\",\"b\"]}', '$.tags')", ())
        .expect("Failed to get JSON_TYPE with path for array");
    assert_eq!(result, "array");

    // Test extracting type at path - boolean
    let result: String = db
        .query_one("SELECT JSON_TYPE('{\"active\":true}', '$.active')", ())
        .expect("Failed to get JSON_TYPE with path for boolean");
    assert_eq!(result, "boolean");

    // Test extracting type at path - null value in JSON
    let result: String = db
        .query_one("SELECT JSON_TYPE('{\"value\":null}', '$.value')", ())
        .expect("Failed to get JSON_TYPE with path for null");
    assert_eq!(result, "null");

    // Test non-existent path returns NULL
    let result = db
        .query("SELECT JSON_TYPE('{\"a\":1}', '$.nonexistent')", ())
        .expect("Failed to query JSON_TYPE with non-existent path");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(
        row.is_null(0),
        "JSON_TYPE with non-existent path should return NULL"
    );

    // Test nested path
    let result: String = db
        .query_one(
            "SELECT JSON_TYPE('{\"user\":{\"profile\":{\"age\":25}}}', '$.user.profile.age')",
            (),
        )
        .expect("Failed to get JSON_TYPE with nested path");
    assert_eq!(result, "number");
}

/// Test JSON_TYPE with path on table data
#[test]
fn test_json_type_path_with_table() {
    let db = Database::open("memory://json_type_path_table").expect("Failed to create database");

    db.execute(
        "CREATE TABLE products (
            id INTEGER PRIMARY KEY,
            name TEXT,
            metadata JSON
        )",
        (),
    )
    .expect("Failed to create table");

    db.execute(
        "INSERT INTO products (id, name, metadata) VALUES (1, 'Laptop', '{\"price\":999.99,\"specs\":{\"cpu\":\"i7\",\"ram\":16},\"tags\":[\"electronics\"]}')",
        (),
    )
    .expect("Failed to insert product");

    // Test JSON_TYPE with path on column
    let result: String = db
        .query_one(
            "SELECT JSON_TYPE(metadata, '$.price') FROM products WHERE id = 1",
            (),
        )
        .expect("Failed to get JSON_TYPE with path on column");
    assert_eq!(result, "number");

    let result: String = db
        .query_one(
            "SELECT JSON_TYPE(metadata, '$.specs') FROM products WHERE id = 1",
            (),
        )
        .expect("Failed to get JSON_TYPE with path on column for object");
    assert_eq!(result, "object");

    let result: String = db
        .query_one(
            "SELECT JSON_TYPE(metadata, '$.tags') FROM products WHERE id = 1",
            (),
        )
        .expect("Failed to get JSON_TYPE with path on column for array");
    assert_eq!(result, "array");

    let result: String = db
        .query_one(
            "SELECT JSON_TYPE(metadata, '$.specs.cpu') FROM products WHERE id = 1",
            (),
        )
        .expect("Failed to get JSON_TYPE with nested path on column");
    assert_eq!(result, "string");
}

/// Test JSON_TYPEOF with two arguments (should behave same as JSON_TYPE)
#[test]
fn test_json_typeof_with_path() {
    let db = Database::open("memory://json_typeof_path").expect("Failed to create database");

    let result: String = db
        .query_one("SELECT JSON_TYPEOF('{\"count\":42}', '$.count')", ())
        .expect("Failed to get JSON_TYPEOF with path");
    assert_eq!(result, "number");

    let result: String = db
        .query_one("SELECT JSON_TYPEOF('{\"items\":[1,2,3]}', '$.items')", ())
        .expect("Failed to get JSON_TYPEOF with path for array");
    assert_eq!(result, "array");
}

/// Test JSON_TYPE with NULL path argument
#[test]
fn test_json_type_null_path() {
    let db = Database::open("memory://json_type_null_path").expect("Failed to create database");

    // NULL path should return NULL
    let result = db
        .query("SELECT JSON_TYPE('{\"a\":1}', NULL)", ())
        .expect("Failed to query JSON_TYPE with NULL path");
    let rows: Vec<_> = result.collect();
    assert_eq!(rows.len(), 1);
    let row = rows[0].as_ref().expect("Failed to get row");
    assert!(
        row.is_null(0),
        "JSON_TYPE with NULL path should return NULL"
    );
}

/// Test JSON_OBJECT function
#[test]
fn test_json_object_function() {
    let db = Database::open("memory://json_object").expect("Failed to create database");

    // Simple key-value pairs
    let result: String = db
        .query_one("SELECT JSON_OBJECT('name', 'Alice', 'age', 30)", ())
        .expect("Failed to create JSON object");
    assert!(result.contains("\"name\""));
    assert!(result.contains("\"Alice\""));
    assert!(result.contains("\"age\""));
    assert!(result.contains("30"));

    // Empty object
    let result: String = db
        .query_one("SELECT JSON_OBJECT()", ())
        .expect("Failed to create empty JSON object");
    assert_eq!(result, "{}");

    // Single key-value pair
    let result: String = db
        .query_one("SELECT JSON_OBJECT('key', 'value')", ())
        .expect("Failed to create single-pair JSON object");
    assert!(result.contains("\"key\""));
    assert!(result.contains("\"value\""));

    // Mixed types
    let result: String = db
        .query_one(
            "SELECT JSON_OBJECT('str', 'text', 'num', 42, 'bool', true)",
            (),
        )
        .expect("Failed to create mixed-type JSON object");
    assert!(result.contains("\"text\""));
    assert!(result.contains("42"));
    assert!(result.contains("true"));
}

/// Test JSON_ARRAY function
#[test]
fn test_json_array_function() {
    let db = Database::open("memory://json_array").expect("Failed to create database");

    // Number array
    let result: String = db
        .query_one("SELECT JSON_ARRAY(1, 2, 3)", ())
        .expect("Failed to create number array");
    assert_eq!(result, "[1,2,3]");

    // String array
    let result: String = db
        .query_one("SELECT JSON_ARRAY('a', 'b', 'c')", ())
        .expect("Failed to create string array");
    assert!(result.contains("\"a\""));
    assert!(result.contains("\"b\""));
    assert!(result.contains("\"c\""));

    // Empty array
    let result: String = db
        .query_one("SELECT JSON_ARRAY()", ())
        .expect("Failed to create empty array");
    assert_eq!(result, "[]");

    // Mixed types
    let result: String = db
        .query_one("SELECT JSON_ARRAY(1, 'two', true, null)", ())
        .expect("Failed to create mixed array");
    assert!(result.contains("1"));
    assert!(result.contains("\"two\""));
    assert!(result.contains("true"));
    assert!(result.contains("null"));
}

/// Test JSON_ARRAY_LENGTH function
#[test]
fn test_json_array_length_function() {
    let db = Database::open("memory://json_array_length").expect("Failed to create database");

    // Simple array
    let result: i64 = db
        .query_one("SELECT JSON_ARRAY_LENGTH('[1,2,3,4,5]')", ())
        .expect("Failed to get array length");
    assert_eq!(result, 5);

    // Empty array
    let result: i64 = db
        .query_one("SELECT JSON_ARRAY_LENGTH('[]')", ())
        .expect("Failed to get empty array length");
    assert_eq!(result, 0);

    // Single element
    let result: i64 = db
        .query_one("SELECT JSON_ARRAY_LENGTH('[42]')", ())
        .expect("Failed to get single element array length");
    assert_eq!(result, 1);
}

/// Test JSON_ARRAY_LENGTH with path (two arguments)
#[test]
fn test_json_array_length_with_path() {
    let db = Database::open("memory://json_array_length_path").expect("Failed to create database");

    // Array at path
    let result: i64 = db
        .query_one(
            "SELECT JSON_ARRAY_LENGTH('{\"items\":[1,2,3]}', '$.items')",
            (),
        )
        .expect("Failed to get array length at path");
    assert_eq!(result, 3);

    // Nested array
    let result: i64 = db
        .query_one(
            "SELECT JSON_ARRAY_LENGTH('{\"data\":{\"values\":[1,2,3,4]}}', '$.data.values')",
            (),
        )
        .expect("Failed to get nested array length");
    assert_eq!(result, 4);

    // Empty array at path
    let result: i64 = db
        .query_one("SELECT JSON_ARRAY_LENGTH('{\"empty\":[]}', '$.empty')", ())
        .expect("Failed to get empty array length at path");
    assert_eq!(result, 0);
}