cypherlite-query 1.2.2

Cypher query engine with parser, planner, and executor for CypherLite
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
// Public API: CypherLite, QueryResult, Row, Transaction, Params, Value
//
// Phase 3 (v0.3.0) additions:
// - WITH clause (scope barrier + projection)
// - UNWIND clause (list expansion)
// - OPTIONAL MATCH (left join semantics)
// - MERGE with ON MATCH SET / ON CREATE SET
// - CREATE INDEX / DROP INDEX DDL
// - Variable-length paths [*N..M] with cycle detection
// - Query optimizer: IndexScan, LIMIT pushdown, constant folding, projection pruning

use crate::executor::{Params, Record, Value};
use cypherlite_core::{CypherLiteError, DatabaseConfig};
use cypherlite_storage::StorageEngine;
use std::collections::HashMap;

/// Result of executing a Cypher query.
#[derive(Debug)]
pub struct QueryResult {
    /// Column names in order.
    pub columns: Vec<String>,
    /// Rows of data.
    pub rows: Vec<Row>,
}

/// A single row in a query result.
#[derive(Debug)]
pub struct Row {
    values: HashMap<String, Value>,
    columns: Vec<String>,
}

impl Row {
    /// Create a new row from a map of column name -> value and an ordered column list.
    pub fn new(values: HashMap<String, Value>, columns: Vec<String>) -> Self {
        Self { values, columns }
    }

    /// Get a value by column name.
    pub fn get(&self, column: &str) -> Option<&Value> {
        self.values.get(column)
    }

    /// Get a typed value by column name.
    pub fn get_as<T: FromValue>(&self, column: &str) -> Option<T> {
        self.values.get(column).and_then(T::from_value)
    }

    /// Get all column names.
    pub fn columns(&self) -> &[String] {
        &self.columns
    }
}

/// Trait for converting Value to concrete Rust types.
pub trait FromValue: Sized {
    /// Attempt to extract a typed value from a `Value` reference.
    fn from_value(value: &Value) -> Option<Self>;
}

impl FromValue for i64 {
    fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::Int64(i) => Some(*i),
            _ => None,
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::Float64(f) => Some(*f),
            _ => None,
        }
    }
}

impl FromValue for String {
    fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::String(s) => Some(s.clone()),
            _ => None,
        }
    }
}

impl FromValue for bool {
    fn from_value(value: &Value) -> Option<Self> {
        match value {
            Value::Bool(b) => Some(*b),
            _ => None,
        }
    }
}

// @MX:ANCHOR: Main CypherLite database interface -- primary public API entry point
// @MX:REASON: fan_in >= 3 (integration tests, user code, transaction wrapper)
/// The main CypherLite database interface.
pub struct CypherLite {
    engine: StorageEngine,
    #[cfg(feature = "plugin")]
    scalar_functions:
        cypherlite_core::plugin::PluginRegistry<dyn cypherlite_core::plugin::ScalarFunction>,
    #[cfg(feature = "plugin")]
    index_plugins:
        cypherlite_core::plugin::PluginRegistry<dyn cypherlite_core::plugin::IndexPlugin>,
    #[cfg(feature = "plugin")]
    serializers: cypherlite_core::plugin::PluginRegistry<dyn cypherlite_core::plugin::Serializer>,
    #[cfg(feature = "plugin")]
    triggers: cypherlite_core::plugin::PluginRegistry<dyn cypherlite_core::plugin::Trigger>,
}

impl CypherLite {
    /// Open or create a CypherLite database.
    pub fn open(config: DatabaseConfig) -> Result<Self, CypherLiteError> {
        let engine = StorageEngine::open(config)?;
        Ok(Self {
            engine,
            #[cfg(feature = "plugin")]
            scalar_functions: cypherlite_core::plugin::PluginRegistry::new(),
            #[cfg(feature = "plugin")]
            index_plugins: cypherlite_core::plugin::PluginRegistry::new(),
            #[cfg(feature = "plugin")]
            serializers: cypherlite_core::plugin::PluginRegistry::new(),
            #[cfg(feature = "plugin")]
            triggers: cypherlite_core::plugin::PluginRegistry::new(),
        })
    }

    /// Execute a Cypher query string.
    pub fn execute(&mut self, query: &str) -> Result<QueryResult, CypherLiteError> {
        self.execute_with_params(query, Params::new())
    }

    /// Execute a Cypher query with parameters.
    pub fn execute_with_params(
        &mut self,
        query: &str,
        params: Params,
    ) -> Result<QueryResult, CypherLiteError> {
        // 1. Parse
        let ast = crate::parser::parse_query(query).map_err(|e| CypherLiteError::ParseError {
            line: e.line,
            column: e.column,
            message: e.message,
        })?;

        // 2. Semantic analysis
        let mut analyzer = crate::semantic::SemanticAnalyzer::new(self.engine.catalog_mut());
        analyzer
            .analyze(&ast)
            .map_err(|e| CypherLiteError::SemanticError(e.message))?;

        // 3. Plan
        let plan = crate::planner::LogicalPlanner::new(self.engine.catalog_mut())
            .plan(&ast)
            .map_err(|e| CypherLiteError::ExecutionError(e.message))?;

        // 4. Optimize (index scan, limit pushdown, constant folding, projection pruning)
        let plan = crate::planner::optimize::optimize(plan);

        // 4.5. Inject query start time for now() function
        let mut params = params;
        if !params.contains_key("__query_start_ms__") {
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as i64)
                .unwrap_or(0);
            params.insert("__query_start_ms__".to_string(), Value::Int64(now_ms));
        }

        // 5. Execute
        #[cfg(feature = "plugin")]
        let scalar_fns: &dyn crate::executor::ScalarFnLookup = &self.scalar_functions;
        #[cfg(not(feature = "plugin"))]
        let scalar_fns: &dyn crate::executor::ScalarFnLookup = &();
        #[cfg(feature = "plugin")]
        let trigger_fns: &dyn crate::executor::TriggerLookup = &self.triggers;
        #[cfg(not(feature = "plugin"))]
        let trigger_fns: &dyn crate::executor::TriggerLookup = &();
        let records =
            crate::executor::execute(&plan, &mut self.engine, &params, scalar_fns, trigger_fns)
                .map_err(|e| CypherLiteError::ExecutionError(e.message))?;

        // 6. Convert to QueryResult
        let columns = extract_columns(&records);
        let rows = records
            .into_iter()
            .map(|r| Row::new(r, columns.clone()))
            .collect();

        Ok(QueryResult { columns, rows })
    }

    /// Get a reference to the underlying storage engine.
    pub fn engine(&self) -> &StorageEngine {
        &self.engine
    }

    /// Get a mutable reference to the underlying storage engine.
    pub fn engine_mut(&mut self) -> &mut StorageEngine {
        &mut self.engine
    }

    /// Register a user-defined scalar function (plugin feature).
    ///
    /// Returns an error if a function with the same name is already registered.
    #[cfg(feature = "plugin")]
    pub fn register_scalar_function(
        &mut self,
        func: Box<dyn cypherlite_core::plugin::ScalarFunction>,
    ) -> Result<(), CypherLiteError> {
        self.scalar_functions
            .register(func)
            .map_err(|e| CypherLiteError::PluginError(e.to_string()))
    }

    /// List all registered scalar functions as `(name, version)` pairs.
    #[cfg(feature = "plugin")]
    pub fn list_scalar_functions(&self) -> Vec<(&str, &str)> {
        self.scalar_functions
            .list()
            .filter_map(|name| self.scalar_functions.get(name).map(|f| (name, f.version())))
            .collect()
    }

    /// Register a custom index plugin.
    ///
    /// Returns an error if an index plugin with the same name is already registered.
    #[cfg(feature = "plugin")]
    pub fn register_index_plugin(
        &mut self,
        plugin: Box<dyn cypherlite_core::plugin::IndexPlugin>,
    ) -> Result<(), CypherLiteError> {
        self.index_plugins
            .register(plugin)
            .map_err(|e| CypherLiteError::PluginError(e.to_string()))
    }

    /// List all registered index plugins as `(name, version, index_type)` tuples.
    #[cfg(feature = "plugin")]
    pub fn list_index_plugins(&self) -> Vec<(&str, &str, &str)> {
        self.index_plugins
            .list()
            .filter_map(|name| {
                self.index_plugins
                    .get(name)
                    .map(|p| (name, p.version(), p.index_type()))
            })
            .collect()
    }

    /// Get an immutable reference to a registered index plugin by name.
    #[cfg(feature = "plugin")]
    pub fn get_index_plugin(
        &self,
        name: &str,
    ) -> Option<&dyn cypherlite_core::plugin::IndexPlugin> {
        self.index_plugins.get(name)
    }

    /// Get a mutable reference to a registered index plugin by name.
    ///
    /// Useful for calling `insert()` and `remove()` which require `&mut self`.
    #[cfg(feature = "plugin")]
    pub fn get_index_plugin_mut(
        &mut self,
        name: &str,
    ) -> Option<&mut (dyn cypherlite_core::plugin::IndexPlugin + 'static)> {
        self.index_plugins.get_mut(name)
    }

    /// Register a custom serializer plugin.
    ///
    /// Returns an error if a serializer with the same name is already registered.
    #[cfg(feature = "plugin")]
    pub fn register_serializer(
        &mut self,
        serializer: Box<dyn cypherlite_core::plugin::Serializer>,
    ) -> Result<(), CypherLiteError> {
        self.serializers
            .register(serializer)
            .map_err(|e| CypherLiteError::PluginError(e.to_string()))
    }

    /// List all registered serializers as `(name, version)` pairs.
    #[cfg(feature = "plugin")]
    pub fn list_serializers(&self) -> Vec<(&str, &str)> {
        self.serializers
            .list()
            .filter_map(|name| self.serializers.get(name).map(|s| (name, s.version())))
            .collect()
    }

    /// Export query results through a registered serializer.
    ///
    /// Executes the given query, converts the resulting rows to
    /// `Vec<HashMap<String, PropertyValue>>`, then delegates to the
    /// serializer whose `format()` matches the requested format string.
    #[cfg(feature = "plugin")]
    pub fn export_data(&mut self, format: &str, query: &str) -> Result<Vec<u8>, CypherLiteError> {
        // Validate format before executing (avoids running query for bad format).
        if !self.has_serializer_format(format) {
            return Err(CypherLiteError::UnsupportedFormat(format.to_string()));
        }

        // Execute the query first (requires &mut self).
        let result = self.execute(query)?;

        // Convert rows to property maps (filter out non-convertible values).
        let data = rows_to_property_maps(&result.rows);

        // Now borrow serializer (only &self needed) and export.
        let serializer = self.find_serializer_by_format(format)?;
        serializer.export(&data)
    }

    /// Import data through a registered serializer.
    ///
    /// Looks up the serializer whose `format()` matches the requested format
    /// string, then delegates to its `import()` method.
    #[cfg(feature = "plugin")]
    pub fn import_data(
        &self,
        format: &str,
        bytes: &[u8],
    ) -> Result<Vec<HashMap<String, cypherlite_core::types::PropertyValue>>, CypherLiteError> {
        let serializer = self.find_serializer_by_format(format)?;
        serializer.import(bytes)
    }

    /// Check whether a serializer with the given format is registered.
    #[cfg(feature = "plugin")]
    fn has_serializer_format(&self, format: &str) -> bool {
        self.serializers.list().any(|name| {
            self.serializers
                .get(name)
                .is_some_and(|s| s.format() == format)
        })
    }

    /// Find a registered serializer by its format identifier.
    #[cfg(feature = "plugin")]
    fn find_serializer_by_format(
        &self,
        format: &str,
    ) -> Result<&dyn cypherlite_core::plugin::Serializer, CypherLiteError> {
        for name in self.serializers.list() {
            if let Some(s) = self.serializers.get(name) {
                if s.format() == format {
                    return Ok(s);
                }
            }
        }
        Err(CypherLiteError::UnsupportedFormat(format.to_string()))
    }

    /// Register a custom trigger plugin.
    ///
    /// Returns an error if a trigger with the same name is already registered.
    #[cfg(feature = "plugin")]
    pub fn register_trigger(
        &mut self,
        trigger: Box<dyn cypherlite_core::plugin::Trigger>,
    ) -> Result<(), CypherLiteError> {
        self.triggers
            .register(trigger)
            .map_err(|e| CypherLiteError::PluginError(e.to_string()))
    }

    /// List all registered triggers as `(name, version)` pairs.
    #[cfg(feature = "plugin")]
    pub fn list_triggers(&self) -> Vec<(&str, &str)> {
        self.triggers
            .list()
            .filter_map(|name| self.triggers.get(name).map(|t| (name, t.version())))
            .collect()
    }

    /// Begin a transaction (simplified - wraps execute calls).
    pub fn begin(&mut self) -> Transaction<'_> {
        Transaction {
            db: self,
            committed: false,
        }
    }
}

/// Convert query rows to property maps, filtering out non-convertible values
/// (e.g., Node, Edge references that have no PropertyValue representation).
#[cfg(feature = "plugin")]
fn rows_to_property_maps(
    rows: &[Row],
) -> Vec<HashMap<String, cypherlite_core::types::PropertyValue>> {
    use cypherlite_core::types::PropertyValue;

    rows.iter()
        .map(|row| {
            row.columns()
                .iter()
                .filter_map(|col| {
                    row.get(col).and_then(|v| {
                        PropertyValue::try_from(v.clone())
                            .ok()
                            .map(|pv| (col.clone(), pv))
                    })
                })
                .collect()
        })
        .collect()
}

/// Extract column names from the first record.
fn extract_columns(records: &[Record]) -> Vec<String> {
    if records.is_empty() {
        return vec![];
    }
    let mut cols: Vec<String> = records[0].keys().cloned().collect();
    cols.sort(); // deterministic column order
    cols
}

/// A transaction wrapping CypherLite execute calls.
///
/// Phase 2: simplified transaction without WAL integration.
/// Full rollback requires WAL integration (Phase 3).
pub struct Transaction<'a> {
    db: &'a mut CypherLite,
    committed: bool,
}

impl<'a> Transaction<'a> {
    /// Execute a query within this transaction.
    pub fn execute(&mut self, query: &str) -> Result<QueryResult, CypherLiteError> {
        self.db.execute(query)
    }

    /// Execute a query with parameters within this transaction.
    pub fn execute_with_params(
        &mut self,
        query: &str,
        params: Params,
    ) -> Result<QueryResult, CypherLiteError> {
        self.db.execute_with_params(query, params)
    }

    /// Commit the transaction.
    pub fn commit(mut self) -> Result<(), CypherLiteError> {
        self.committed = true;
        Ok(())
    }

    /// Rollback the transaction (discard changes).
    /// For Phase 2, this is a no-op since we don't have WAL integration yet.
    pub fn rollback(mut self) -> Result<(), CypherLiteError> {
        self.committed = true; // prevent double-rollback
                               // Phase 2: no actual rollback - in-memory changes remain
                               // Full rollback requires WAL integration (Phase 3)
        Ok(())
    }
}

impl<'a> Drop for Transaction<'a> {
    fn drop(&mut self) {
        if !self.committed {
            // Auto-rollback on drop (no-op for Phase 2)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cypherlite_core::SyncMode;
    use tempfile::tempdir;

    fn test_config(dir: &std::path::Path) -> DatabaseConfig {
        DatabaseConfig {
            path: dir.join("test.cyl"),
            wal_sync_mode: SyncMode::Normal,
            ..Default::default()
        }
    }

    // ======================================================================
    // TASK-054: QueryResult, Row, FromValue tests
    // ======================================================================

    #[test]
    fn test_row_get_existing_column() {
        let mut values = HashMap::new();
        values.insert("name".to_string(), Value::String("Alice".into()));
        let row = Row::new(values, vec!["name".to_string()]);
        assert_eq!(row.get("name"), Some(&Value::String("Alice".into())));
    }

    #[test]
    fn test_row_get_missing_column() {
        let row = Row::new(HashMap::new(), vec![]);
        assert_eq!(row.get("missing"), None);
    }

    #[test]
    fn test_row_get_as_i64() {
        let mut values = HashMap::new();
        values.insert("age".to_string(), Value::Int64(30));
        let row = Row::new(values, vec!["age".to_string()]);
        assert_eq!(row.get_as::<i64>("age"), Some(30));
    }

    #[test]
    fn test_row_get_as_f64() {
        let mut values = HashMap::new();
        values.insert("score".to_string(), Value::Float64(3.15));
        let row = Row::new(values, vec!["score".to_string()]);
        assert_eq!(row.get_as::<f64>("score"), Some(3.15));
    }

    #[test]
    fn test_row_get_as_string() {
        let mut values = HashMap::new();
        values.insert("name".to_string(), Value::String("Bob".into()));
        let row = Row::new(values, vec!["name".to_string()]);
        assert_eq!(row.get_as::<String>("name"), Some("Bob".to_string()));
    }

    #[test]
    fn test_row_get_as_bool() {
        let mut values = HashMap::new();
        values.insert("active".to_string(), Value::Bool(true));
        let row = Row::new(values, vec!["active".to_string()]);
        assert_eq!(row.get_as::<bool>("active"), Some(true));
    }

    #[test]
    fn test_row_get_as_wrong_type() {
        let mut values = HashMap::new();
        values.insert("age".to_string(), Value::String("thirty".into()));
        let row = Row::new(values, vec!["age".to_string()]);
        assert_eq!(row.get_as::<i64>("age"), None);
    }

    #[test]
    fn test_row_columns() {
        let row = Row::new(HashMap::new(), vec!["a".to_string(), "b".to_string()]);
        assert_eq!(row.columns(), &["a".to_string(), "b".to_string()]);
    }

    #[test]
    fn test_query_result_empty() {
        let result = QueryResult {
            columns: vec![],
            rows: vec![],
        };
        assert!(result.rows.is_empty());
        assert!(result.columns.is_empty());
    }

    #[test]
    fn test_from_value_null_returns_none() {
        assert_eq!(i64::from_value(&Value::Null), None);
        assert_eq!(f64::from_value(&Value::Null), None);
        assert_eq!(String::from_value(&Value::Null), None);
        assert_eq!(bool::from_value(&Value::Null), None);
    }

    #[test]
    fn test_extract_columns_empty_records() {
        let records: Vec<Record> = vec![];
        assert!(extract_columns(&records).is_empty());
    }

    #[test]
    fn test_extract_columns_deterministic_order() {
        let mut r = Record::new();
        r.insert("b".to_string(), Value::Int64(1));
        r.insert("a".to_string(), Value::Int64(2));
        let cols = extract_columns(&[r]);
        assert_eq!(cols, vec!["a".to_string(), "b".to_string()]);
    }

    // ======================================================================
    // TASK-055: CypherLite::open(), execute() tests
    // ======================================================================

    #[test]
    fn test_cypherlite_open() {
        let dir = tempdir().expect("tempdir");
        let db = CypherLite::open(test_config(dir.path()));
        assert!(db.is_ok());
    }

    #[test]
    fn test_cypherlite_engine_accessors() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");
        assert_eq!(db.engine().node_count(), 0);
        assert_eq!(db.engine_mut().edge_count(), 0);
    }

    // ======================================================================
    // TASK-056: Transaction tests
    // ======================================================================

    #[test]
    fn test_transaction_commit() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");
        let tx = db.begin();
        assert!(tx.commit().is_ok());
    }

    #[test]
    fn test_transaction_rollback() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");
        let tx = db.begin();
        assert!(tx.rollback().is_ok());
    }

    #[test]
    fn test_transaction_auto_rollback_on_drop() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");
        {
            let _tx = db.begin();
            // dropped without commit or rollback -- should not panic
        }
    }

    // ======================================================================
    // TASK-057: End-to-end integration tests
    // ======================================================================

    // INT-T001: open -> CREATE -> MATCH
    #[test]
    fn int_t001_create_then_match() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        // Create a node
        db.execute("CREATE (n:Person {name: 'Alice', age: 30})")
            .expect("create");

        // Query the node
        let result = db
            .execute("MATCH (n:Person) RETURN n.name, n.age")
            .expect("match");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("n.name"),
            Some("Alice".to_string())
        );
        assert_eq!(result.rows[0].get_as::<i64>("n.age"), Some(30));
    }

    // INT-T002: Parameter binding $name
    #[test]
    fn int_t002_parameter_binding() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (n:Person {name: 'Alice'})")
            .expect("create");

        let mut params = Params::new();
        params.insert("name".to_string(), Value::String("Alice".into()));

        let result = db
            .execute_with_params(
                "MATCH (n:Person) WHERE n.name = $name RETURN n.name",
                params,
            )
            .expect("match with params");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("n.name"),
            Some("Alice".to_string())
        );
    }

    // INT-T003: Transaction commit
    #[test]
    fn int_t003_transaction_commit() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        {
            let mut tx = db.begin();
            tx.execute("CREATE (n:Person {name: 'Bob'})")
                .expect("create in tx");
            tx.commit().expect("commit");
        }

        // Verify data persists after commit
        let result = db
            .execute("MATCH (n:Person) RETURN n.name")
            .expect("match after commit");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("n.name"),
            Some("Bob".to_string())
        );
    }

    // INT-T004: Invalid Cypher -> ParseError (no panic)
    #[test]
    fn int_t004_invalid_cypher_parse_error() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        let result = db.execute("INVALID QUERY @#$");
        assert!(result.is_err());
        let err = result.expect_err("should fail");
        // Should be a parse error, not a panic
        assert!(
            matches!(err, CypherLiteError::ParseError { .. }),
            "expected ParseError, got: {err}"
        );
    }

    // INT-T005: MATCH non-existent label -> empty result (not error)
    #[test]
    fn int_t005_match_nonexistent_label_empty() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        let result = db
            .execute("MATCH (n:NonExistent) RETURN n")
            .expect("should succeed with empty result");
        assert!(result.rows.is_empty());
    }

    // INT-T006: SET then MATCH to verify change
    #[test]
    fn int_t006_set_then_match() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (n:Person {name: 'Alice', age: 25})")
            .expect("create");

        db.execute("MATCH (n:Person) SET n.age = 30").expect("set");

        let result = db
            .execute("MATCH (n:Person) RETURN n.age")
            .expect("match after set");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(result.rows[0].get_as::<i64>("n.age"), Some(30));
    }

    // INT-T007: DETACH DELETE
    #[test]
    fn int_t007_detach_delete() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (a:Person {name: 'Alice'})-[:KNOWS]->(b:Person {name: 'Bob'})")
            .expect("create");

        // Verify nodes exist
        let result = db
            .execute("MATCH (n:Person) RETURN n.name")
            .expect("match before delete");
        assert_eq!(result.rows.len(), 2);

        // Detach delete all Person nodes
        db.execute("MATCH (n:Person) DETACH DELETE n")
            .expect("detach delete");

        // Verify no nodes remain
        let result = db
            .execute("MATCH (n:Person) RETURN n.name")
            .expect("match after delete");
        assert!(result.rows.is_empty());
    }

    // AC-001: MATCH (n:Person) RETURN n.name with 3 Person nodes
    #[test]
    fn ac_001_match_return_three_persons() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (n:Person {name: 'Alice'})").expect("c1");
        db.execute("CREATE (n:Person {name: 'Bob'})").expect("c2");
        db.execute("CREATE (n:Person {name: 'Charlie'})")
            .expect("c3");

        let result = db.execute("MATCH (n:Person) RETURN n.name").expect("match");
        assert_eq!(result.rows.len(), 3);

        let mut names: Vec<String> = result
            .rows
            .iter()
            .filter_map(|r| r.get_as::<String>("n.name"))
            .collect();
        names.sort();
        assert_eq!(names, vec!["Alice", "Bob", "Charlie"]);
    }

    // AC-002: CREATE (a:Person {name: "Alice"}) then MATCH verify
    #[test]
    fn ac_002_create_then_match_verify() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (a:Person {name: 'Alice'})")
            .expect("create");

        let result = db.execute("MATCH (n:Person) RETURN n.name").expect("match");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("n.name"),
            Some("Alice".to_string())
        );
    }

    // AC-003: CREATE relationship then traverse
    #[test]
    fn ac_003_create_relationship_then_traverse() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (a:Person {name: 'Alice'})-[:KNOWS]->(b:Person {name: 'Bob'})")
            .expect("create relationship");

        let result = db
            .execute("MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN b.name")
            .expect("traverse");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("b.name"),
            Some("Bob".to_string())
        );
    }

    // AC-004: WHERE n.age > 28 filter
    #[test]
    fn ac_004_where_filter() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (n:Person {name: 'Alice', age: 30})")
            .expect("c1");
        db.execute("CREATE (n:Person {name: 'Bob', age: 25})")
            .expect("c2");
        db.execute("CREATE (n:Person {name: 'Charlie', age: 35})")
            .expect("c3");

        let result = db
            .execute("MATCH (n:Person) WHERE n.age > 28 RETURN n.name")
            .expect("filter");
        assert_eq!(result.rows.len(), 2);

        let mut names: Vec<String> = result
            .rows
            .iter()
            .filter_map(|r| r.get_as::<String>("n.name"))
            .collect();
        names.sort();
        assert_eq!(names, vec!["Alice", "Charlie"]);
    }

    // AC-006: Syntax error detection with position
    #[test]
    fn ac_006_syntax_error_detection() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        let result = db.execute("MATCH (n:Person RETURN n");
        assert!(result.is_err());
        let err = result.expect_err("should fail");
        match err {
            CypherLiteError::ParseError {
                line,
                column,
                message,
            } => {
                assert!(line >= 1, "line should be >= 1, got {line}");
                assert!(column >= 1, "column should be >= 1, got {column}");
                assert!(!message.is_empty(), "error message should not be empty");
            }
            other => panic!("expected ParseError, got: {other}"),
        }
    }

    // AC-007: Type mismatch error (undefined variable as semantic error)
    #[test]
    fn ac_007_semantic_error() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        // Reference undefined variable 'm' instead of 'n'
        let result = db.execute("MATCH (n:Person) RETURN m.name");
        assert!(result.is_err());
        let err = result.expect_err("should fail");
        assert!(
            matches!(err, CypherLiteError::SemanticError(_)),
            "expected SemanticError, got: {err}"
        );
    }

    // AC-010: NULL handling (IS NOT NULL, missing property returns NULL)
    #[test]
    fn ac_010_null_handling() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        // Create nodes: one with email, one without
        db.execute("CREATE (n:Person {name: 'Alice', email: 'alice@example.com'})")
            .expect("c1");
        db.execute("CREATE (n:Person {name: 'Bob'})").expect("c2");

        // Query for a property that may be missing
        let result = db
            .execute("MATCH (n:Person) RETURN n.name, n.email")
            .expect("match");
        assert_eq!(result.rows.len(), 2);

        // One row should have email, one should have Null
        let mut found_null = false;
        let mut found_email = false;
        for row in &result.rows {
            match row.get("n.email") {
                Some(Value::String(s)) if !s.is_empty() => found_email = true,
                Some(Value::Null) | None => found_null = true,
                _ => {}
            }
        }
        assert!(found_email, "should find at least one row with email");
        assert!(found_null, "should find at least one row with null email");
    }

    // Additional: IS NOT NULL filter
    #[test]
    fn ac_010_is_not_null_filter() {
        let dir = tempdir().expect("tempdir");
        let mut db = CypherLite::open(test_config(dir.path())).expect("open");

        db.execute("CREATE (n:Person {name: 'Alice', email: 'alice@example.com'})")
            .expect("c1");
        db.execute("CREATE (n:Person {name: 'Bob'})").expect("c2");

        let result = db
            .execute("MATCH (n:Person) WHERE n.email IS NOT NULL RETURN n.name")
            .expect("filter not null");
        assert_eq!(result.rows.len(), 1);
        assert_eq!(
            result.rows[0].get_as::<String>("n.name"),
            Some("Alice".to_string())
        );
    }
}