sqawk 0.8.2

An SQL-based command-line tool for processing delimiter-separated files (CSV, TSV, etc.), inspired by awk
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
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
//! Unit tests for the VM engine
//!
//! These tests verify that the VM's two-phase execution approach works correctly:
//! 1. Compilation of SQL to bytecode
//! 2. Execution of bytecode by the VM engine

use crate::database::Database;
use crate::error::SqawkResult;
use crate::table::{Table, Value};
use crate::vm::bytecode::{Instruction, OpCode, Program};
use crate::vm::engine::VmEngine;

/// Bytecode testing module
mod bytecode_tests {
    use super::*;

    /// Helper function to create a program with given instructions and execute it
    pub fn execute_bytecode_program(
        instructions: Vec<Instruction>,
        database: &Database,
    ) -> SqawkResult<Option<Table>> {
        // Create a program from the instructions
        let mut program = Program::new();
        for instruction in instructions {
            program.add_instruction(instruction);
        }

        // Execute the program
        let mut engine = VmEngine::new(database, false);
        engine.init(program);
        engine.execute()?;

        // Return the result table
        engine.create_result_table()
    }

    /// Create an instruction with the given opcode and parameters
    pub fn create_instruction(
        opcode: OpCode,
        p1: i64,
        p2: i64,
        p3: i64,
        p4: Option<String>,
        comment: Option<String>,
    ) -> Instruction {
        Instruction::new(opcode, p1, p2, p3, p4, 0, comment)
    }

    /// Test Init, Integer, ResultRow, and Halt opcodes
    #[test]
    fn test_basic_flow_opcodes() {
        // This test verifies that the basic program flow opcodes work together:
        // - Init: Initialize VM
        // - Integer: Load an integer value
        // - ResultRow: Return a result row
        // - Halt: Stop execution

        let database = Database::new();

        // Create a program that loads integer 42 into register 1 and returns it
        let instructions = vec![
            // Initialize VM and jump to instruction 1
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load integer 42 into register 1
            create_instruction(
                OpCode::Integer,
                42,
                1,
                0,
                None,
                Some("Load value 42".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        let rows = table.rows();
        let first_row = &rows[0];

        match &first_row[0] {
            Value::Integer(val) => assert_eq!(*val, 42, "Expected value 42, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }
    }

    /// Test String opcode
    #[test]
    fn test_string_opcode() {
        // This test verifies that the String opcode works correctly

        let database = Database::new();

        // Create a program that loads a string into register 1 and returns it
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load string "test" into register 1
            create_instruction(
                OpCode::String,
                0,
                1,
                0,
                Some("test".to_string()),
                Some("Load string value".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        let rows = table.rows();
        let first_row = &rows[0];

        match &first_row[0] {
            Value::String(val) => assert_eq!(val, "test", "Expected value 'test', got '{}'", val),
            other => panic!("Expected String type, got {:?}", other),
        }
    }

    /// Test Null opcode
    #[test]
    fn test_null_opcode() {
        // This test verifies that the Null opcode works correctly

        let database = Database::new();

        // Create a program that loads NULL into register 1 and returns it
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load NULL into register 1
            create_instruction(
                OpCode::Null,
                0,
                1,
                0,
                None,
                Some("Load NULL value".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        let rows = table.rows();
        let first_row = &rows[0];

        match &first_row[0] {
            Value::Null => {} // Success
            other => panic!("Expected Null type, got {:?}", other),
        }
    }

    /// Test ResultRow with multiple registers
    #[test]
    fn test_result_row_with_multiple_registers() {
        // This test verifies that ResultRow correctly handles multiple registers

        let database = Database::new();

        // Create a program that loads values into registers 1, 2, 3 and returns them
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load integer 42 into register 1
            create_instruction(
                OpCode::Integer,
                42,
                1,
                0,
                None,
                Some("Load value 42".to_string()),
            ),
            // Load string "test" into register 2
            create_instruction(
                OpCode::String,
                0,
                2,
                0,
                Some("test".to_string()),
                Some("Load string value".to_string()),
            ),
            // Load NULL into register 3
            create_instruction(
                OpCode::Null,
                0,
                3,
                0,
                None,
                Some("Load NULL value".to_string()),
            ),
            // Return result row with registers 1, 2, 3
            create_instruction(
                OpCode::ResultRow,
                1,
                3,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 3, "Expected 3 columns");

        let rows = table.rows();
        let first_row = &rows[0];

        // Check first column (register 1)
        match &first_row[0] {
            Value::Integer(val) => assert_eq!(*val, 42, "Expected value 42, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }

        // Check second column (register 2)
        match &first_row[1] {
            Value::String(val) => assert_eq!(val, "test", "Expected value 'test', got '{}'", val),
            other => panic!("Expected String type, got {:?}", other),
        }

        // Check third column (register 3)
        match &first_row[2] {
            Value::Null => {} // Success
            other => panic!("Expected Null type, got {:?}", other),
        }
    }

    /// Test table operations: OpenRead, Rewind, Column, Next, and Close
    #[test]
    fn test_table_operations() {
        // This test verifies that table operation opcodes work correctly:
        // - OpenRead: Open a table for reading
        // - Rewind: Move cursor to first row
        // - Column: Read column value into register
        // - Next: Move cursor to next row
        // - Close: Close a cursor

        // Create a database with a test table
        let mut database = Database::new();

        // Create a simple table with test data
        let mut table = Table::new("test_table", vec![], None);
        table.add_column("id".to_string(), "INT".to_string());
        table.add_column("name".to_string(), "TEXT".to_string());

        // Add some test rows
        table
            .add_row(vec![
                Value::Integer(1),
                Value::String("Alice".to_string().into()),
            ])
            .expect("Failed to add row");

        table
            .add_row(vec![
                Value::Integer(2),
                Value::String("Bob".to_string().into()),
            ])
            .expect("Failed to add row");

        // Add the table to the database
        let _ = database.add_table("test_table".to_string(), table);

        // Create a program that reads from the table and returns both rows
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Open test_table with cursor 1
            create_instruction(
                OpCode::OpenRead,
                1,
                0,
                0,
                Some("test_table".to_string()),
                Some("Open table".to_string()),
            ),
            // Rewind cursor 1, jump to end (instruction 7) if empty
            create_instruction(
                OpCode::Rewind,
                1,
                7,
                0,
                None,
                Some("Move to first row".to_string()),
            ),
            // Loop start:
            // Read column 0 (id) into register 1
            create_instruction(
                OpCode::Column,
                1,
                0,
                1,
                None,
                Some("Read ID column".to_string()),
            ),
            // Read column 1 (name) into register 2
            create_instruction(
                OpCode::Column,
                1,
                1,
                2,
                None,
                Some("Read name column".to_string()),
            ),
            // Return result row with registers 1-2
            create_instruction(
                OpCode::ResultRow,
                1,
                2,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Next row for cursor 1, jump to loop start (instruction 3) if more rows
            create_instruction(
                OpCode::Next,
                1,
                3,
                0,
                None,
                Some("Move to next row".to_string()),
            ),
            // Close cursor 1
            create_instruction(
                OpCode::Close,
                1,
                0,
                0,
                None,
                Some("Close cursor".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 2, "Expected 2 rows");
        assert_eq!(table.column_count(), 2, "Expected 2 columns");

        let rows = table.rows();

        // Check first row
        assert_eq!(
            rows[0][0],
            Value::Integer(1),
            "First row, first column should be 1"
        );
        assert_eq!(
            rows[0][1],
            Value::String("Alice".to_string().into()),
            "First row, second column should be 'Alice'"
        );

        // Check second row
        assert_eq!(
            rows[1][0],
            Value::Integer(2),
            "Second row, first column should be 2"
        );
        assert_eq!(
            rows[1][1],
            Value::String("Bob".to_string().into()),
            "Second row, second column should be 'Bob'"
        );
    }

    /// Test the Goto operation
    #[test]
    fn test_goto_opcode() {
        // This test verifies that the Goto opcode works correctly for program flow control

        let database = Database::new();

        // Create a program with a jump in the middle
        let instructions = vec![
            // Initialize VM, jump to instruction 1
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load integer 10 into register 1
            create_instruction(
                OpCode::Integer,
                10,
                1,
                0,
                None,
                Some("Load value 10".to_string()),
            ),
            // Jump unconditionally to instruction 4, skipping the next instruction
            create_instruction(
                OpCode::Goto,
                0,
                4,
                0,
                None,
                Some("Jump to instruction 4".to_string()),
            ),
            // Load integer 20 into register 1 (should be skipped)
            create_instruction(
                OpCode::Integer,
                20,
                1,
                0,
                None,
                Some("Load value 20 (should be skipped)".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        let rows = table.rows();
        let first_row = &rows[0];

        match &first_row[0] {
            Value::Integer(val) => assert_eq!(*val, 10, "Expected value 10 (not 20), got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }
    }

    /// Test multiple result rows
    #[test]
    fn test_multiple_result_rows() {
        // This test verifies that the VM can produce multiple result rows

        let database = Database::new();

        // Create a program that generates multiple result rows
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Load integer 1 into register 1
            create_instruction(
                OpCode::Integer,
                1,
                1,
                0,
                None,
                Some("Load value 1".to_string()),
            ),
            // Return first result row
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return first result".to_string()),
            ),
            // Load integer 2 into register 1
            create_instruction(
                OpCode::Integer,
                2,
                1,
                0,
                None,
                Some("Load value 2".to_string()),
            ),
            // Return second result row
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return second result".to_string()),
            ),
            // Load integer 3 into register 1
            create_instruction(
                OpCode::Integer,
                3,
                1,
                0,
                None,
                Some("Load value 3".to_string()),
            ),
            // Return third result row
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return third result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result =
            execute_bytecode_program(instructions, &database).expect("Failed to execute program");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");

        let table = result.unwrap();
        assert_eq!(table.row_count(), 3, "Expected 3 rows");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        let rows = table.rows();

        // Check first row
        match &rows[0][0] {
            Value::Integer(val) => assert_eq!(*val, 1, "Expected value 1, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }

        // Check second row
        match &rows[1][0] {
            Value::Integer(val) => assert_eq!(*val, 2, "Expected value 2, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }

        // Check third row
        match &rows[2][0] {
            Value::Integer(val) => assert_eq!(*val, 3, "Expected value 3, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }
    }

    /// Test transaction opcodes (Begin, Commit, Rollback)
    #[test]
    fn test_transaction_opcodes() {
        // This test verifies that the transaction opcodes work correctly
        let database = Database::new();

        // Create a program that uses transaction opcodes
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Begin transaction
            create_instruction(
                OpCode::Begin,
                0,
                0,
                0,
                None,
                Some("Begin transaction".to_string()),
            ),
            // Load integer 42 into register 1
            create_instruction(
                OpCode::Integer,
                42,
                1,
                0,
                None,
                Some("Load value 42".to_string()),
            ),
            // Commit transaction
            create_instruction(
                OpCode::Commit,
                0,
                0,
                0,
                None,
                Some("Commit transaction".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result = execute_bytecode_program(instructions, &database)
            .expect("Failed to execute program with Begin/Commit");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");
        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        // Check the value
        let rows = table.rows();
        let first_row = &rows[0];
        match &first_row[0] {
            Value::Integer(val) => assert_eq!(*val, 42, "Expected value 42, got {}", val),
            other => panic!("Expected Integer type, got {:?}", other),
        }

        // Test rollback
        let instructions = vec![
            // Initialize VM
            create_instruction(
                OpCode::Init,
                0,
                1,
                0,
                None,
                Some("Initialize VM".to_string()),
            ),
            // Begin transaction
            create_instruction(
                OpCode::Begin,
                0,
                0,
                0,
                None,
                Some("Begin transaction".to_string()),
            ),
            // Load integer 42 into register 1
            create_instruction(
                OpCode::Integer,
                42,
                1,
                0,
                None,
                Some("Load value in transaction".to_string()),
            ),
            // Rollback transaction
            create_instruction(
                OpCode::Rollback,
                0,
                0,
                0,
                None,
                Some("Rollback transaction".to_string()),
            ),
            // Load integer 99 into register 1 (after rollback)
            create_instruction(
                OpCode::Integer,
                99,
                1,
                0,
                None,
                Some("Load value after rollback".to_string()),
            ),
            // Return result row with register 1
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Return result".to_string()),
            ),
            // Halt execution
            create_instruction(
                OpCode::Halt,
                0,
                0,
                0,
                None,
                Some("Stop execution".to_string()),
            ),
        ];

        // Execute the program
        let result = execute_bytecode_program(instructions, &database)
            .expect("Failed to execute program with Begin/Rollback");

        // Verify the result
        assert!(result.is_some(), "Expected a result table");
        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");
        assert_eq!(table.column_count(), 1, "Expected 1 column");

        // Check that we got the post-rollback value
        let rows = table.rows();
        let first_row = &rows[0];
        match &first_row[0] {
            Value::Integer(val) => {
                assert_eq!(*val, 99, "Expected value 99 (after rollback), got {}", val)
            }
            other => panic!("Expected Integer type, got {:?}", other),
        }
    }
}

// The compiler tests and other VM tests have been removed to simplify
// our implementation and focus on the transaction tests.

/// Test comparison opcodes and conditional jumps
mod comparison_tests {
    use super::*;
    use crate::vm::tests::bytecode_tests::{create_instruction, execute_bytecode_program};

    /// Test the Lt (Less Than) comparison opcode
    #[test]
    fn test_lt_opcode() {
        let database = Database::new();

        // Test cases: [(first_value, second_value, expected_result)]
        let test_cases = vec![
            (10, 20, 1), // 10 < 20 = true (1)
            (20, 10, 0), // 20 < 10 = false (0)
            (10, 10, 0), // 10 < 10 = false (0)
        ];

        for (val1, val2, expected) in test_cases {
            let instructions = vec![
                // Initialize VM
                create_instruction(
                    OpCode::Init,
                    0,
                    1,
                    0,
                    None,
                    Some("Initialize VM".to_string()),
                ),
                // Load first value into register 1
                create_instruction(
                    OpCode::Integer,
                    val1,
                    1,
                    0,
                    None,
                    Some(format!("Load first value: {}", val1)),
                ),
                // Load second value into register 2
                create_instruction(
                    OpCode::Integer,
                    val2,
                    2,
                    0,
                    None,
                    Some(format!("Load second value: {}", val2)),
                ),
                // Compare r1 < r2, result in r3
                create_instruction(
                    OpCode::Lt,
                    1,
                    2,
                    3,
                    None,
                    Some(format!("Compare {} < {}", val1, val2)),
                ),
                // Return the comparison result
                create_instruction(
                    OpCode::ResultRow,
                    3,
                    1,
                    0,
                    None,
                    Some("Return result".to_string()),
                ),
                // Halt VM
                create_instruction(
                    OpCode::Halt,
                    0,
                    0,
                    0,
                    None,
                    Some("Stop execution".to_string()),
                ),
            ];

            // Execute the program
            let result = execute_bytecode_program(instructions, &database)
                .expect("Failed to execute program with Lt opcode");

            // Verify the result
            assert!(result.is_some(), "Expected a result table");
            let table = result.unwrap();
            assert_eq!(table.row_count(), 1, "Expected 1 row");

            // Check the result value
            match &table.rows()[0][0] {
                Value::Integer(val) => assert_eq!(
                    *val, expected as i64,
                    "Expected {} < {} to be {}, got {}",
                    val1, val2, expected, val
                ),
                other => panic!("Expected Integer type, got {:?}", other),
            }
        }
    }

    /// Test the Le (Less Than or Equal) comparison opcode
    #[test]
    fn test_le_opcode() {
        let database = Database::new();

        // Test cases: [(first_value, second_value, expected_result)]
        let test_cases = vec![
            (10, 20, 1), // 10 <= 20 = true (1)
            (20, 10, 0), // 20 <= 10 = false (0)
            (10, 10, 1), // 10 <= 10 = true (1)
        ];

        for (val1, val2, expected) in test_cases {
            let instructions = vec![
                // Initialize VM
                create_instruction(
                    OpCode::Init,
                    0,
                    1,
                    0,
                    None,
                    Some("Initialize VM".to_string()),
                ),
                // Load first value into register 1
                create_instruction(
                    OpCode::Integer,
                    val1,
                    1,
                    0,
                    None,
                    Some(format!("Load first value: {}", val1)),
                ),
                // Load second value into register 2
                create_instruction(
                    OpCode::Integer,
                    val2,
                    2,
                    0,
                    None,
                    Some(format!("Load second value: {}", val2)),
                ),
                // Compare r1 <= r2, result in r3
                create_instruction(
                    OpCode::Le,
                    1,
                    2,
                    3,
                    None,
                    Some(format!("Compare {} <= {}", val1, val2)),
                ),
                // Return the comparison result
                create_instruction(
                    OpCode::ResultRow,
                    3,
                    1,
                    0,
                    None,
                    Some("Return result".to_string()),
                ),
                // Halt VM
                create_instruction(
                    OpCode::Halt,
                    0,
                    0,
                    0,
                    None,
                    Some("Stop execution".to_string()),
                ),
            ];

            // Execute the program
            let result = execute_bytecode_program(instructions, &database)
                .expect("Failed to execute program with Le opcode");

            // Verify the result
            assert!(result.is_some(), "Expected a result table");
            let table = result.unwrap();
            assert_eq!(table.row_count(), 1, "Expected 1 row");

            // Check the result value
            match &table.rows()[0][0] {
                Value::Integer(val) => assert_eq!(
                    *val, expected as i64,
                    "Expected {} <= {} to be {}, got {}",
                    val1, val2, expected, val
                ),
                other => panic!("Expected Integer type, got {:?}", other),
            }
        }
    }

    /// Test conditional jump using SQLite-style jump mechanism
    #[test]
    fn test_conditional_jump() {
        let database = Database::new();

        // Test cases for conditional jumps
        // (first_value, second_value, expected_result_after_jump)
        let test_cases = vec![
            (10, 20, 555), // 10 < 20 = true, result = 1, so NOT Jump (555)
            (20, 10, 999), // 20 < 10 = false, result = 0, so Jump (999)
        ];

        for (val1, val2, expected) in test_cases {
            let instructions = vec![
                // Initialize VM
                create_instruction(
                    OpCode::Init,
                    0,
                    1,
                    0,
                    None,
                    Some("Initialize VM".to_string()),
                ),
                // Load first value into register 1
                create_instruction(
                    OpCode::Integer,
                    val1,
                    1,
                    0,
                    None,
                    Some(format!("Load value {}", val1)),
                ),
                // Load second value into register 2
                create_instruction(
                    OpCode::Integer,
                    val2,
                    2,
                    0,
                    None,
                    Some(format!("Load value {}", val2)),
                ),
                // Compare register 1 < register 2, result in register 3
                create_instruction(
                    OpCode::Lt,
                    1,
                    2,
                    3,
                    None,
                    Some(format!("Compare {} < {}", val1, val2)),
                ),
                // Jump to instruction 7 if reg3 contains 0 (SQLite-style jump if zero)
                create_instruction(
                    OpCode::IfZ,
                    3,
                    7,
                    0,
                    None,
                    Some("Jump to instruction 7 if result is 0 (false)".to_string()),
                ),
                // True path (Not jumped) - load 555 into register 4
                create_instruction(
                    OpCode::Integer,
                    555,
                    4,
                    0,
                    None,
                    Some("Load true path value (555)".to_string()),
                ),
                // Jump to instruction 8 (end)
                create_instruction(OpCode::Goto, 0, 8, 0, None, Some("Jump to end".to_string())),
                // False path (Jumped) - load 999 into register 4
                create_instruction(
                    OpCode::Integer,
                    999,
                    4,
                    0,
                    None,
                    Some("Load false path value (999)".to_string()),
                ),
                // Return result from register 4
                create_instruction(
                    OpCode::ResultRow,
                    4,
                    1,
                    0,
                    None,
                    Some("Return result".to_string()),
                ),
                // Halt execution
                create_instruction(
                    OpCode::Halt,
                    0,
                    0,
                    0,
                    None,
                    Some("Stop execution".to_string()),
                ),
            ];

            // Execute the program
            let result = execute_bytecode_program(instructions, &database)
                .expect("Failed to execute program with conditional jump");

            // Verify the result
            assert!(result.is_some(), "Expected a result table");
            let table = result.unwrap();
            assert_eq!(table.row_count(), 1, "Expected 1 row");

            // Check the conditional jump outcome
            match &table.rows()[0][0] {
                Value::Integer(val) => assert_eq!(
                    *val, expected as i64,
                    "Expected {} for comparison {} < {}, got {}",
                    expected, val1, val2, val
                ),
                other => panic!("Expected Integer type, got {:?}", other),
            }
        }
    }

    /// Test the IfPos conditional jump opcode
    #[test]
    fn test_if_pos_opcode() {
        let database = Database::new();

        // Test cases: [(register_value, expected_result_after_jump)]
        let test_cases = vec![
            (5, 777),  // 5 > 0 = true, should jump to 777
            (0, 888),  // 0 = 0, should NOT jump, continue to 888
            (-3, 888), // -3 < 0, should NOT jump, continue to 888
        ];

        for (reg_value, expected) in test_cases {
            let instructions = vec![
                // Initialize VM
                create_instruction(
                    OpCode::Init,
                    0,
                    1,
                    0,
                    None,
                    Some("Initialize VM".to_string()),
                ),
                // Load test value into register 1
                create_instruction(
                    OpCode::Integer,
                    reg_value,
                    1,
                    0,
                    None,
                    Some(format!("Load test value {}", reg_value)),
                ),
                // Jump to instruction 5 if reg1 is positive (> 0)
                create_instruction(
                    OpCode::IfPos,
                    1,
                    5,
                    0,
                    None,
                    Some("Jump if positive".to_string()),
                ),
                // Not jumped path - load 888 into register 2
                create_instruction(
                    OpCode::Integer,
                    888,
                    2,
                    0,
                    None,
                    Some("Load not-jumped value (888)".to_string()),
                ),
                // Jump to end
                create_instruction(OpCode::Goto, 0, 6, 0, None, Some("Jump to end".to_string())),
                // Jumped path - load 777 into register 2
                create_instruction(
                    OpCode::Integer,
                    777,
                    2,
                    0,
                    None,
                    Some("Load jumped value (777)".to_string()),
                ),
                // Return result from register 2
                create_instruction(
                    OpCode::ResultRow,
                    2,
                    1,
                    0,
                    None,
                    Some("Return result".to_string()),
                ),
                // Halt execution
                create_instruction(
                    OpCode::Halt,
                    0,
                    0,
                    0,
                    None,
                    Some("Stop execution".to_string()),
                ),
            ];

            // Execute the program
            let result = execute_bytecode_program(instructions, &database)
                .expect("Failed to execute program with IfPos");

            // Verify the result
            assert!(result.is_some(), "Expected a result table");
            let table = result.unwrap();
            assert_eq!(table.row_count(), 1, "Expected 1 row");

            // Check the conditional jump outcome
            match &table.rows()[0][0] {
                Value::Integer(val) => assert_eq!(
                    *val, expected as i64,
                    "Expected {} for IfPos test with value {}, got {}",
                    expected, reg_value, val
                ),
                other => panic!("Expected Integer type, got {:?}", other),
            }
        }
    }

    /// Test the IfNeg conditional jump opcode
    #[test]
    fn test_if_neg_opcode() {
        let database = Database::new();

        // Test cases: [(register_value, expected_result_after_jump)]
        let test_cases = vec![
            (-5, 333), // -5 < 0 = true, should jump to 333
            (0, 444),  // 0 = 0, should NOT jump, continue to 444
            (3, 444),  // 3 > 0, should NOT jump, continue to 444
        ];

        for (reg_value, expected) in test_cases {
            let instructions = vec![
                // Initialize VM
                create_instruction(
                    OpCode::Init,
                    0,
                    1,
                    0,
                    None,
                    Some("Initialize VM".to_string()),
                ),
                // Load test value into register 1
                create_instruction(
                    OpCode::Integer,
                    reg_value,
                    1,
                    0,
                    None,
                    Some(format!("Load test value {}", reg_value)),
                ),
                // Jump to instruction 5 if reg1 is negative (< 0)
                create_instruction(
                    OpCode::IfNeg,
                    1,
                    5,
                    0,
                    None,
                    Some("Jump if negative".to_string()),
                ),
                // Not jumped path - load 444 into register 2
                create_instruction(
                    OpCode::Integer,
                    444,
                    2,
                    0,
                    None,
                    Some("Load not-jumped value (444)".to_string()),
                ),
                // Jump to end
                create_instruction(OpCode::Goto, 0, 6, 0, None, Some("Jump to end".to_string())),
                // Jumped path - load 333 into register 2
                create_instruction(
                    OpCode::Integer,
                    333,
                    2,
                    0,
                    None,
                    Some("Load jumped value (333)".to_string()),
                ),
                // Return result from register 2
                create_instruction(
                    OpCode::ResultRow,
                    2,
                    1,
                    0,
                    None,
                    Some("Return result".to_string()),
                ),
                // Halt execution
                create_instruction(
                    OpCode::Halt,
                    0,
                    0,
                    0,
                    None,
                    Some("Stop execution".to_string()),
                ),
            ];

            // Execute the program
            let result = execute_bytecode_program(instructions, &database)
                .expect("Failed to execute program with IfNeg");

            // Verify the result
            assert!(result.is_some(), "Expected a result table");
            let table = result.unwrap();
            assert_eq!(table.row_count(), 1, "Expected 1 row");

            // Check the conditional jump outcome
            match &table.rows()[0][0] {
                Value::Integer(val) => assert_eq!(
                    *val, expected as i64,
                    "Expected {} for IfNeg test with value {}, got {}",
                    expected, reg_value, val
                ),
                other => panic!("Expected Integer type, got {:?}", other),
            }
        }
    }

    /// Test Column opcode with simple cursor operations
    #[test]
    fn test_column_opcode_basic() {
        use crate::database::Database;
        use crate::table::Table;

        // Create a simple test database
        let mut database = Database::new();
        let mut test_table = Table::new("simple_test", vec![], None);

        // Add columns: id, value
        test_table.add_column("id".to_string(), "INTEGER".to_string());
        test_table.add_column("value".to_string(), "INTEGER".to_string());

        // Add one test row
        test_table
            .add_row(vec![
                crate::table::Value::Integer(1),
                crate::table::Value::Integer(42),
            ])
            .expect("Failed to add test row");

        database
            .add_table("simple_test".to_string(), test_table)
            .expect("Failed to add table");

        // Simple test: Read the value column (index 1)
        let instructions = vec![
            create_instruction(OpCode::Init, 0, 1, 0, None, Some("Initialize".to_string())),
            create_instruction(
                OpCode::OpenRead,
                0,
                0,
                0,
                Some("simple_test".to_string()),
                Some("Open table".to_string()),
            ),
            create_instruction(OpCode::Rewind, 0, 5, 0, None, Some("Rewind".to_string())),
            create_instruction(
                OpCode::Column,
                0,
                1,
                1,
                None,
                Some("Read value column".to_string()),
            ),
            create_instruction(
                OpCode::ResultRow,
                1,
                1,
                0,
                None,
                Some("Output value".to_string()),
            ),
            create_instruction(OpCode::Halt, 0, 0, 0, None, Some("Stop".to_string())),
        ];

        let result = execute_bytecode_program(instructions, &database)
            .expect("Failed to execute column test");

        // Verify we got the expected value
        assert!(result.is_some(), "Expected a result table");
        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 row");

        match &table.rows()[0][0] {
            crate::table::Value::Integer(value) => {
                assert_eq!(*value, 42, "Expected value 42, got {}", value);
            }
            other => panic!("Expected Integer value, got {:?}", other),
        }
    }

    /// Test comparison operations with Column data
    #[test]
    fn test_column_with_comparison() {
        use crate::database::Database;
        use crate::table::Table;

        // Create test database with two values: one matches, one doesn't
        let mut database = Database::new();
        let mut test_table = Table::new("comparison_test", vec![], None);

        test_table.add_column("id".to_string(), "INTEGER".to_string());
        test_table.add_column("score".to_string(), "INTEGER".to_string());

        // Add two rows: score 25 (should not match > 30), score 35 (should match > 30)
        test_table
            .add_row(vec![
                crate::table::Value::Integer(1),
                crate::table::Value::Integer(25),
            ])
            .expect("Failed to add test row");

        test_table
            .add_row(vec![
                crate::table::Value::Integer(2),
                crate::table::Value::Integer(35),
            ])
            .expect("Failed to add test row");

        database
            .add_table("comparison_test".to_string(), test_table)
            .expect("Failed to add table");

        // Test first row (score = 25, should fail > 30 test)
        let instructions_row1 = vec![
            create_instruction(OpCode::Init, 0, 1, 0, None, Some("Initialize".to_string())),
            create_instruction(
                OpCode::OpenRead,
                0,
                0,
                0,
                Some("comparison_test".to_string()),
                Some("Open table".to_string()),
            ),
            create_instruction(OpCode::Rewind, 0, 7, 0, None, Some("Rewind".to_string())),
            create_instruction(
                OpCode::Column,
                0,
                1,
                1,
                None,
                Some("Read score".to_string()),
            ),
            create_instruction(OpCode::Integer, 30, 2, 0, None, Some("Load 30".to_string())),
            create_instruction(
                OpCode::Gt,
                1,
                2,
                3,
                None,
                Some("Test score > 30".to_string()),
            ),
            create_instruction(
                OpCode::ResultRow,
                3,
                1,
                0,
                None,
                Some("Output comparison result".to_string()),
            ),
            create_instruction(OpCode::Halt, 0, 0, 0, None, Some("Stop".to_string())),
        ];

        let result = execute_bytecode_program(instructions_row1, &database)
            .expect("Failed to execute comparison test");

        assert!(result.is_some(), "Expected a result");
        let table = result.unwrap();
        assert_eq!(table.row_count(), 1, "Expected 1 result row");

        // Should be 0 (false) since 25 > 30 is false
        match &table.rows()[0][0] {
            crate::table::Value::Integer(result_val) => {
                assert_eq!(
                    *result_val, 0,
                    "Expected comparison result 0 (false), got {}",
                    result_val
                );
            }
            other => panic!("Expected Integer comparison result, got {:?}", other),
        }
    }
}

/// Tests for the Not / Compare / Jump opcodes.
///
/// These exist to support the compiler unification: `Not` makes `NOT <expr>`
/// expressible and replaces several hand-rolled inversions, while
/// `Compare`/`Jump` make multi-column key comparison two instructions
/// regardless of key width -- which is what GROUP BY needs in order to detect
/// a group change across ALL key columns instead of only the first.
mod compare_jump_not_tests {
    use super::bytecode_tests::{create_instruction, execute_bytecode_program};
    use super::*;

    /// Run a program and return the single result row.
    fn run_row(instructions: Vec<Instruction>) -> Vec<Value> {
        let database = Database::new();
        let table = execute_bytecode_program(instructions, &database)
            .expect("program failed")
            .expect("expected a result table");
        assert_eq!(table.row_count(), 1, "expected exactly one result row");
        table.rows()[0].clone()
    }

    fn init() -> Instruction {
        create_instruction(OpCode::Init, 0, 1, 0, None, None)
    }

    fn halt() -> Instruction {
        create_instruction(OpCode::Halt, 0, 0, 0, None, None)
    }

    #[test]
    fn not_inverts_truthy_and_falsy() {
        // r1 = 5 -> NOT r1 = 0 ; r3 = 0 -> NOT r3 = 1
        let row = run_row(vec![
            init(),
            create_instruction(OpCode::Integer, 5, 1, 0, None, None),
            create_instruction(OpCode::Not, 1, 2, 0, None, None),
            create_instruction(OpCode::Integer, 0, 3, 0, None, None),
            create_instruction(OpCode::Not, 3, 4, 0, None, None),
            // Emit r2, r4 as a two-column row (registers must be contiguous).
            create_instruction(OpCode::Copy, 2, 10, 0, None, None),
            create_instruction(OpCode::Copy, 4, 11, 0, None, None),
            create_instruction(OpCode::ResultRow, 10, 2, 0, None, None),
            halt(),
        ]);
        assert_eq!(row[0], Value::Integer(0), "NOT 5 should be 0");
        assert_eq!(row[1], Value::Integer(1), "NOT 0 should be 1");
    }

    #[test]
    fn not_propagates_null() {
        // NOT NULL must be NULL (SQL UNKNOWN), not true.
        let row = run_row(vec![
            init(),
            create_instruction(OpCode::Null, 0, 1, 0, None, None),
            create_instruction(OpCode::Not, 1, 2, 0, None, None),
            create_instruction(OpCode::ResultRow, 2, 1, 0, None, None),
            halt(),
        ]);
        assert_eq!(
            row[0],
            Value::Null,
            "NOT NULL must stay NULL, not become true"
        );
    }

    /// Build a program that compares two 2-register vectors and reports which
    /// branch Jump takes: 1 = Less, 2 = Equal, 3 = Greater.
    fn compare_branch(lhs: [i64; 2], rhs: [i64; 2]) -> Value {
        let row = run_row(vec![
            init(),
            // lhs in r1,r2 ; rhs in r3,r4
            create_instruction(OpCode::Integer, lhs[0], 1, 0, None, None),
            create_instruction(OpCode::Integer, lhs[1], 2, 0, None, None),
            create_instruction(OpCode::Integer, rhs[0], 3, 0, None, None),
            create_instruction(OpCode::Integer, rhs[1], 4, 0, None, None),
            // Compare r1..r2 against r3..r4 (2 columns)
            create_instruction(OpCode::Compare, 1, 3, 2, None, None),
            // Jump: less -> 7, equal -> 9, greater -> 11
            create_instruction(OpCode::Jump, 7, 9, 11, None, None),
            // 7: less
            create_instruction(OpCode::Integer, 1, 5, 0, None, None),
            create_instruction(OpCode::Goto, 0, 13, 0, None, None),
            // 9: equal
            create_instruction(OpCode::Integer, 2, 5, 0, None, None),
            create_instruction(OpCode::Goto, 0, 13, 0, None, None),
            // 11: greater
            create_instruction(OpCode::Integer, 3, 5, 0, None, None),
            create_instruction(OpCode::Goto, 0, 13, 0, None, None),
            // 13: emit
            create_instruction(OpCode::ResultRow, 5, 1, 0, None, None),
            halt(),
        ]);
        row[0].clone()
    }

    #[test]
    fn compare_jump_branches_three_ways() {
        assert_eq!(compare_branch([1, 1], [1, 1]), Value::Integer(2), "equal");
        assert_eq!(compare_branch([1, 1], [1, 2]), Value::Integer(1), "less");
        assert_eq!(compare_branch([1, 2], [1, 1]), Value::Integer(3), "greater");
    }

    #[test]
    fn compare_uses_all_key_columns() {
        // The whole point: a difference in the SECOND column must be detected.
        // The old single-Ne group-change check compared only the first, which
        // is why multi-column GROUP BY collapsed to one key.
        assert_ne!(
            compare_branch([7, 1], [7, 2]),
            Value::Integer(2),
            "vectors differing only in the second column must not compare equal"
        );
    }

    #[test]
    fn compare_treats_nulls_as_equal() {
        // Internal ordering, not SQL `=`: two NULL group keys must group
        // together. SQL equality must yield UNKNOWN for NULL, which is exactly
        // why Compare is a separate opcode from Eq.
        let row = run_row(vec![
            init(),
            create_instruction(OpCode::Null, 0, 1, 0, None, None),
            create_instruction(OpCode::Null, 0, 2, 0, None, None),
            create_instruction(OpCode::Compare, 1, 2, 1, None, None),
            create_instruction(OpCode::Jump, 5, 7, 9, None, None),
            // 5: less
            create_instruction(OpCode::Integer, 1, 3, 0, None, None),
            create_instruction(OpCode::Goto, 0, 11, 0, None, None),
            // 7: equal
            create_instruction(OpCode::Integer, 2, 3, 0, None, None),
            create_instruction(OpCode::Goto, 0, 11, 0, None, None),
            // 9: greater
            create_instruction(OpCode::Integer, 3, 3, 0, None, None),
            create_instruction(OpCode::Goto, 0, 11, 0, None, None),
            // 11: emit
            create_instruction(OpCode::ResultRow, 3, 1, 0, None, None),
            halt(),
        ]);
        assert_eq!(
            row[0],
            Value::Integer(2),
            "NULL should compare equal to NULL"
        );
    }
}