linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
//! Planner registration mechanism
//! Implement static registration using type-safe enumerations to completely eliminate dynamic distribution.
//!
//! # Explanation of the reconstruction process
//!
//! This module has been completely restructured, and the old mechanism for matching SentenceKind strings has been removed.
//! Now, use the direct enumeration mode to match the planner created from the Stmt.

use std::sync::Arc;

use crate::binder::BoundStatement;
use crate::parser::ast::Stmt;
use crate::planning::context::PlanContext;
use crate::planning::plan::SubPlan;
use crate::QueryContext;

// Re-exported for planner implementations that still reference it.
pub use crate::binder::validation::ValidatedStatement;

use crate::planning::fulltext_planner::FulltextSearchPlanner;
use crate::planning::statements::ddl::maintain_planner::MaintainPlanner;
use crate::planning::statements::ddl::use_planner::UsePlanner;
use crate::planning::statements::ddl::user_management_planner::UserManagementPlanner;
use crate::planning::statements::dml::assignment_planner::AssignmentPlanner;
use crate::planning::statements::dml::copy_planner::CopyPlanner;
use crate::planning::statements::dml::delete_planner::DeletePlanner;
use crate::planning::statements::dml::insert_planner::InsertPlanner;
use crate::planning::statements::dml::merge_planner::MergePlanner;
use crate::planning::statements::dml::remove_planner::RemovePlanner;
use crate::planning::statements::dml::set_planner::SetPlanner;
use crate::planning::statements::dml::update_planner::UpdatePlanner;
use crate::planning::statements::dql::assign_variable_planner::AssignVariablePlanner;
use crate::planning::statements::dql::collect_planner::CollectPlanner;
use crate::planning::statements::dql::explain_planner::ExplainPlanner;
use crate::planning::statements::dql::fetch_edges_planner::FetchEdgesPlanner;
use crate::planning::statements::dql::fetch_vertices_planner::FetchVerticesPlanner;
use crate::planning::statements::dql::filter_planner::FilterPlanner;
use crate::planning::statements::dql::go_planner::GoPlanner;
use crate::planning::statements::dql::group_by_planner::GroupByPlanner;
use crate::planning::statements::dql::lookup_planner::LookupPlanner;
use crate::planning::statements::dql::path_planner::PathPlanner;
use crate::planning::statements::dql::pipe_planner::PipePlanner;
use crate::planning::statements::dql::return_planner::ReturnPlanner;
use crate::planning::statements::dql::set_operation_planner::SetOperationPlanner;
use crate::planning::statements::dql::subgraph_planner::SubgraphPlanner;
use crate::planning::statements::dql::unwind_planner::UnwindPlanner;
use crate::planning::statements::dql::with_planner::WithPlanner;
use crate::planning::statements::dql::yield_planner::YieldPlanner;
use crate::planning::statements::match_statement_planner::MatchStatementPlanner;
#[cfg(feature = "vector")]
use crate::planning::vector_planner::VectorSearchPlanner;

///  Planner Configuration
#[derive(Debug, Clone)]
pub struct PlannerConfig {
    pub max_plan_depth: usize,
    pub enable_parallel_planning: bool,
    pub enable_rewrite: bool,
}

impl Default for PlannerConfig {
    fn default() -> Self {
        Self {
            max_plan_depth: 100,
            enable_parallel_planning: false,
            enable_rewrite: true,
        }
    }
}

/// Match function type
pub type MatchFunc = fn(&Stmt) -> bool;

///  Planner Features
///
/// # Design Principles
/// The `transform` method accepts an `Arc<QueryContext>` and a `&ValidatedStatement`.
/// The `match_planner` method receives an `&Stmt` object, which is used for matching and making judgments.
pub trait Planner: std::fmt::Debug {
    /// Translate the verified statement into a sub-plan.
    ///
    /// # Parameters
    /// `validated`: A verified statement that contains ValidationInfo and Ast.
    /// `qctx`: Query context
    fn transform(
        &mut self,
        validated: &ValidatedStatement,
        qctx: Arc<QueryContext>,
    ) -> Result<SubPlan, PlannerError>;

    /// Check whether this planner can handle the given sentence.
    fn match_planner(&self, stmt: &Stmt) -> bool;

    /// Translate a bound statement directly into a plan sub-tree.
    ///
    /// The unified [`PlanContext`] bundles all inputs needed during
    /// bound-statement planning (bound statement, query context, metadata,
    /// validated statement). The default implementation returns
    /// `UnsupportedOperation` so that planners which have not yet been
    /// migrated to the bound pipeline continue to work unchanged.
    fn plan_bound(&mut self, _ctx: &PlanContext<'_>) -> Result<SubPlan, PlannerError> {
        Err(PlannerError::UnsupportedOperation(
            "plan_bound not yet implemented for this planner".to_string(),
        ))
    }

    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

// ============================================================================
// Implementation of static registration – complete elimination of dynamic distribution
// ============================================================================

/// Planner Enumeration – Core for Static Distribution
/// Eliminate dynamic distribution completely and use compile-time polymorphism instead.
#[derive(Debug, Clone)]
pub enum PlannerEnum {
    Match(Box<MatchStatementPlanner>),
    Go(GoPlanner),
    Lookup(LookupPlanner),
    Path(PathPlanner),
    Subgraph(SubgraphPlanner),
    FetchVertices(FetchVerticesPlanner),
    FetchEdges(FetchEdgesPlanner),
    Maintain(MaintainPlanner),
    UserManagement(UserManagementPlanner),
    Assignment(AssignmentPlanner),
    Insert(InsertPlanner),
    Copy(CopyPlanner),
    Delete(DeletePlanner),
    Update(UpdatePlanner),
    Remove(RemovePlanner),
    Set(SetPlanner),
    Merge(MergePlanner),
    GroupBy(GroupByPlanner),
    Filter(FilterPlanner),
    Collect(CollectPlanner),
    SetOperation(SetOperationPlanner),
    Use(UsePlanner),
    Unwind(UnwindPlanner),
    With(WithPlanner),
    Return(ReturnPlanner),
    AssignVariable(AssignVariablePlanner),
    Yield(YieldPlanner),
    Pipe(PipePlanner),
    Explain(ExplainPlanner),
    FulltextSearch(FulltextSearchPlanner),
    #[cfg(feature = "vector")]
    VectorSearch(VectorSearchPlanner),
}

impl PlannerEnum {
    /// Create a planner directly from Arc<Stmt> (the recommended method).
    /// Use the enumeration pattern for matching to completely eliminate the need for string matching.
    pub fn from_stmt(stmt: &Arc<Stmt>) -> Option<Self> {
        Self::from_stmt_ref(stmt.as_ref())
    }

    /// Create a planner directly from a statement reference.
    /// This avoids cloning the whole statement tree when only dispatching.
    pub fn from_stmt_ref(stmt: &Stmt) -> Option<Self> {
        match stmt {
            Stmt::Match(_) => Some(PlannerEnum::Match(Box::default())),
            Stmt::Go(_) => Some(PlannerEnum::Go(GoPlanner::new())),
            Stmt::Lookup(_) => Some(PlannerEnum::Lookup(LookupPlanner::new())),
            Stmt::FindPath(_) => Some(PlannerEnum::Path(PathPlanner::new())),
            Stmt::Subgraph(_) => Some(PlannerEnum::Subgraph(SubgraphPlanner::new())),
            Stmt::Fetch(fetch_stmt) => match &fetch_stmt.target {
                crate::parser::ast::FetchTarget::Vertices { .. } => {
                    Some(PlannerEnum::FetchVertices(FetchVerticesPlanner::new()))
                }
                crate::parser::ast::FetchTarget::Edges { .. } => {
                    Some(PlannerEnum::FetchEdges(FetchEdgesPlanner::new()))
                }
            },
            Stmt::Insert(_) => Some(PlannerEnum::Insert(InsertPlanner::new())),
            Stmt::Copy(_) => Some(PlannerEnum::Copy(CopyPlanner::new())),
            Stmt::Delete(_) => Some(PlannerEnum::Delete(DeletePlanner::new())),
            Stmt::Update(_) => Some(PlannerEnum::Update(UpdatePlanner::new())),
            Stmt::Remove(_) => Some(PlannerEnum::Remove(RemovePlanner::new())),
            Stmt::Set(_) => Some(PlannerEnum::Set(SetPlanner::new())),
            Stmt::Merge(_) => Some(PlannerEnum::Merge(MergePlanner::new())),
            Stmt::Assignment(_) => Some(PlannerEnum::Assignment(AssignmentPlanner::new())),
            Stmt::GroupBy(_) => Some(PlannerEnum::GroupBy(GroupByPlanner::new())),
            Stmt::Filter(_) => Some(PlannerEnum::Filter(FilterPlanner::new())),
            Stmt::Collect(_) => Some(PlannerEnum::Collect(CollectPlanner::new())),
            Stmt::SetOperation(_) => Some(PlannerEnum::SetOperation(SetOperationPlanner::new())),
            Stmt::Use(_) => Some(PlannerEnum::Use(UsePlanner::new())),
            Stmt::Unwind(_) => Some(PlannerEnum::Unwind(UnwindPlanner::new())),
            Stmt::With(_) => Some(PlannerEnum::With(WithPlanner::new())),
            Stmt::Return(_) => Some(PlannerEnum::Return(ReturnPlanner::new())),
            Stmt::AssignVariable(_) => {
                Some(PlannerEnum::AssignVariable(AssignVariablePlanner::new()))
            }
            Stmt::Yield(_) => Some(PlannerEnum::Yield(YieldPlanner::new())),
            Stmt::Pipe(_) => Some(PlannerEnum::Pipe(PipePlanner::new())),
            Stmt::Explain(_) => Some(PlannerEnum::Explain(ExplainPlanner::new())),
            Stmt::Profile(_) => Some(PlannerEnum::Explain(ExplainPlanner::new_profile())),
            // Full-text search statements
            Stmt::CreateFulltextIndex(_)
            | Stmt::DropFulltextIndex(_)
            | Stmt::AlterFulltextIndex(_)
            | Stmt::ShowFulltextIndex(_)
            | Stmt::DescribeFulltextIndex(_)
            | Stmt::Search(_)
            | Stmt::LookupFulltext(_)
            | Stmt::MatchFulltext(_) => {
                Some(PlannerEnum::FulltextSearch(FulltextSearchPlanner::new()))
            }
            #[cfg(feature = "vector")]
            Stmt::CreateVectorIndex(_)
            | Stmt::DropVectorIndex(_)
            | Stmt::SearchVector(_)
            | Stmt::LookupVector(_)
            | Stmt::MatchVector(_) => Some(PlannerEnum::VectorSearch(VectorSearchPlanner::new())),
            Stmt::CreateUser(_)
            | Stmt::DropUser(_)
            | Stmt::AlterUser(_)
            | Stmt::ChangePassword(_)
            | Stmt::Grant(_)
            | Stmt::Revoke(_)
            | Stmt::DescribeUser(_)
            | Stmt::ShowUsers(_)
            | Stmt::ShowRoles(_) => Some(PlannerEnum::UserManagement(UserManagementPlanner::new())),
            Stmt::Create(_)
            | Stmt::Drop(_)
            | Stmt::Show(_)
            | Stmt::Desc(_)
            | Stmt::Alter(_)
            | Stmt::ShowCreate(_)
            | Stmt::ShowSessions(_)
            | Stmt::ShowQueries(_)
            | Stmt::KillQuery(_)
            | Stmt::ShowConfigs(_)
            | Stmt::UpdateConfigs(_)
            | Stmt::ClearSpace(_)
            | Stmt::BeginTransaction(_)
            | Stmt::CommitTransaction(_)
            | Stmt::RollbackTransaction(_)
            | Stmt::Savepoint(_)
            | Stmt::ReleaseSavepoint(_)
            | Stmt::Checkpoint(_)
            | Stmt::PurgeExpired(_)
            | Stmt::ExportDatabase(_)
            | Stmt::ImportDatabase(_)
            | Stmt::AttachDatabase(_)
            | Stmt::DetachDatabase(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            // New reading clause statements — no dedicated planner yet; route
            // through the MaintainPlanner fallback (returns UnsupportedOperation
            // until a proper planner is implemented).
            Stmt::LoadFrom(_) | Stmt::InQueryCall(_) => {
                Some(PlannerEnum::Maintain(MaintainPlanner::new()))
            }
            // Catalog DDL statements are planned by the MaintainPlanner into
            // MacroManage / TypeManage plan nodes.
            Stmt::CreateMacro(_) | Stmt::DropMacro(_) | Stmt::CreateType(_) | Stmt::DropType(_) => {
                Some(PlannerEnum::Maintain(MaintainPlanner::new()))
            }
            // The type of the following sentence does not currently support direct planning.
            _ => None,
        }
    }

    /// Create a planner from Arc<Ast>.
    /// This is the new recommendation method; the context of the expressions is defined within Ast.
    pub fn from_ast(ast: &Arc<crate::parser::ast::stmt::Ast>) -> Option<Self> {
        Self::from_stmt_ref(&ast.stmt)
    }

    /// Convert the verified statement into an execution plan.
    pub fn transform(
        &mut self,
        validated: &ValidatedStatement,
        qctx: Arc<QueryContext>,
    ) -> Result<SubPlan, PlannerError> {
        match self {
            PlannerEnum::Match(planner) => planner.transform(validated, qctx),
            PlannerEnum::Go(planner) => planner.transform(validated, qctx),
            PlannerEnum::Lookup(planner) => planner.transform(validated, qctx),
            PlannerEnum::Path(planner) => planner.transform(validated, qctx),
            PlannerEnum::Subgraph(planner) => planner.transform(validated, qctx),
            PlannerEnum::FetchVertices(planner) => planner.transform(validated, qctx),
            PlannerEnum::FetchEdges(planner) => planner.transform(validated, qctx),
            PlannerEnum::Maintain(planner) => planner.transform(validated, qctx),
            PlannerEnum::UserManagement(planner) => planner.transform(validated, qctx),
            PlannerEnum::Assignment(planner) => planner.transform(validated, qctx),
            PlannerEnum::Insert(planner) => planner.transform(validated, qctx),
            PlannerEnum::Copy(planner) => planner.transform(validated, qctx),
            PlannerEnum::Delete(planner) => planner.transform(validated, qctx),
            PlannerEnum::Update(planner) => planner.transform(validated, qctx),
            PlannerEnum::Remove(planner) => planner.transform(validated, qctx),
            PlannerEnum::Set(planner) => planner.transform(validated, qctx),
            PlannerEnum::Merge(planner) => planner.transform(validated, qctx),
            PlannerEnum::GroupBy(planner) => planner.transform(validated, qctx),
            PlannerEnum::Filter(planner) => planner.transform(validated, qctx),
            PlannerEnum::Collect(planner) => planner.transform(validated, qctx),
            PlannerEnum::SetOperation(planner) => planner.transform(validated, qctx),
            PlannerEnum::Use(planner) => planner.transform(validated, qctx),
            PlannerEnum::Unwind(planner) => planner.transform(validated, qctx),
            PlannerEnum::With(planner) => planner.transform(validated, qctx),
            PlannerEnum::Return(planner) => planner.transform(validated, qctx),
            PlannerEnum::AssignVariable(planner) => planner.transform(validated, qctx),
            PlannerEnum::Yield(planner) => planner.transform(validated, qctx),
            PlannerEnum::Pipe(planner) => planner.transform(validated, qctx),
            PlannerEnum::Explain(planner) => planner.transform(validated, qctx),
            PlannerEnum::FulltextSearch(planner) => planner.transform(validated, qctx),
            #[cfg(feature = "vector")]
            PlannerEnum::VectorSearch(planner) => planner.transform(validated, qctx),
        }
    }

    /// Create a planner from a BoundStatement.
    pub fn from_bound_statement(bound: &BoundStatement) -> Option<Self> {
        match bound {
            BoundStatement::Match(_) => Some(PlannerEnum::Match(Box::default())),
            BoundStatement::Go(_) => Some(PlannerEnum::Go(GoPlanner::new())),
            BoundStatement::Lookup(_) => Some(PlannerEnum::Lookup(LookupPlanner::new())),
            BoundStatement::FetchVertices(_) => {
                Some(PlannerEnum::FetchVertices(FetchVerticesPlanner::new()))
            }
            BoundStatement::FetchEdges(_) => {
                Some(PlannerEnum::FetchEdges(FetchEdgesPlanner::new()))
            }
            BoundStatement::FindPath(_) => Some(PlannerEnum::Path(PathPlanner::new())),
            BoundStatement::Subgraph(_) => Some(PlannerEnum::Subgraph(SubgraphPlanner::new())),
            BoundStatement::Return(_) => Some(PlannerEnum::Return(ReturnPlanner::new())),
            BoundStatement::With(_) => Some(PlannerEnum::With(WithPlanner::new())),
            BoundStatement::Use(_) => Some(PlannerEnum::Use(UsePlanner::new())),
            BoundStatement::Unwind(_) => Some(PlannerEnum::Unwind(UnwindPlanner::new())),
            BoundStatement::Pipe(_) => Some(PlannerEnum::Pipe(PipePlanner::new())),
            BoundStatement::SetOperation(_) => {
                Some(PlannerEnum::SetOperation(SetOperationPlanner::new()))
            }
            BoundStatement::GroupBy(_) => Some(PlannerEnum::GroupBy(GroupByPlanner::new())),
            BoundStatement::Filter(_) => Some(PlannerEnum::Filter(FilterPlanner::new())),
            BoundStatement::Yield(_) => Some(PlannerEnum::Yield(YieldPlanner::new())),
            BoundStatement::Collect(_) => Some(PlannerEnum::Collect(CollectPlanner::new())),
            BoundStatement::AssignVariable(_) => {
                Some(PlannerEnum::AssignVariable(AssignVariablePlanner::new()))
            }
            BoundStatement::Insert(_) => Some(PlannerEnum::Insert(InsertPlanner::new())),
            BoundStatement::Update(_) => Some(PlannerEnum::Update(UpdatePlanner::new())),
            BoundStatement::Delete(_) => Some(PlannerEnum::Delete(DeletePlanner::new())),
            BoundStatement::Merge(_) => Some(PlannerEnum::Merge(MergePlanner::new())),
            BoundStatement::Set(_) => Some(PlannerEnum::Set(SetPlanner::new())),
            BoundStatement::Remove(_) => Some(PlannerEnum::Remove(RemovePlanner::new())),
            BoundStatement::Copy(_) => Some(PlannerEnum::Copy(CopyPlanner::new())),
            BoundStatement::Drop(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::Alter(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::Show(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::ShowCreate(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::Desc(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::ClearSpace(_) => Some(PlannerEnum::Maintain(MaintainPlanner::new())),
            BoundStatement::CreateUser(_)
            | BoundStatement::DropUser(_)
            | BoundStatement::AlterUser(_) => {
                Some(PlannerEnum::UserManagement(UserManagementPlanner::new()))
            }
            BoundStatement::CreateFulltextIndex(_) => {
                Some(PlannerEnum::FulltextSearch(FulltextSearchPlanner::new()))
            }
            BoundStatement::CreateVectorIndex(_) => {
                #[cfg(feature = "vector")]
                {
                    Some(PlannerEnum::VectorSearch(VectorSearchPlanner::new()))
                }
                #[cfg(not(feature = "vector"))]
                {
                    None
                }
            }
            BoundStatement::Explain(_) => Some(PlannerEnum::Explain(ExplainPlanner::new())),
            BoundStatement::Profile(_) => Some(PlannerEnum::Explain(ExplainPlanner::new_profile())),
            BoundStatement::BeginTransaction(_)
            | BoundStatement::Commit(_)
            | BoundStatement::Rollback(_)
            | BoundStatement::Savepoint(_)
            | BoundStatement::ReleaseSavepoint(_) => {
                Some(PlannerEnum::Maintain(MaintainPlanner::new()))
            }
            BoundStatement::Assignment(_) => {
                Some(PlannerEnum::Assignment(AssignmentPlanner::new()))
            }
            BoundStatement::Other(stmt) => Self::from_stmt_ref(stmt.as_ref()),
        }
    }

    /// Obtain the name of the planner.
    pub fn name(&self) -> &'static str {
        match self {
            PlannerEnum::Match(_) => "MatchPlanner",
            PlannerEnum::Go(_) => "GoPlanner",
            PlannerEnum::Lookup(_) => "LookupPlanner",
            PlannerEnum::Path(_) => "PathPlanner",
            PlannerEnum::Subgraph(_) => "SubgraphPlanner",
            PlannerEnum::FetchVertices(_) => "FetchVerticesPlanner",
            PlannerEnum::FetchEdges(_) => "FetchEdgesPlanner",
            PlannerEnum::Maintain(_) => "MaintainPlanner",
            PlannerEnum::UserManagement(_) => "UserManagementPlanner",
            PlannerEnum::Assignment(_) => "AssignmentPlanner",
            PlannerEnum::Insert(_) => "InsertPlanner",
            PlannerEnum::Copy(_) => "CopyPlanner",
            PlannerEnum::Delete(_) => "DeletePlanner",
            PlannerEnum::Update(_) => "UpdatePlanner",
            PlannerEnum::Remove(_) => "RemovePlanner",
            PlannerEnum::Set(_) => "SetPlanner",
            PlannerEnum::Merge(_) => "MergePlanner",
            PlannerEnum::GroupBy(_) => "GroupByPlanner",
            PlannerEnum::Filter(_) => "FilterPlanner",
            PlannerEnum::Collect(_) => "CollectPlanner",
            PlannerEnum::SetOperation(_) => "SetOperationPlanner",
            PlannerEnum::Use(_) => "UsePlanner",
            PlannerEnum::Unwind(_) => "UnwindPlanner",
            PlannerEnum::With(_) => "WithPlanner",
            PlannerEnum::Return(_) => "ReturnPlanner",
            PlannerEnum::AssignVariable(_) => "AssignVariablePlanner",
            PlannerEnum::Yield(_) => "YieldPlanner",
            PlannerEnum::Pipe(_) => "PipePlanner",
            PlannerEnum::Explain(_) => "ExplainPlanner",
            PlannerEnum::FulltextSearch(_) => "FulltextSearchPlanner",
            #[cfg(feature = "vector")]
            PlannerEnum::VectorSearch(_) => "VectorSearchPlanner",
        }
    }

    /// Check whether there is a match.
    pub fn matches(&self, stmt: &Stmt) -> bool {
        match self {
            PlannerEnum::Match(planner) => planner.match_planner(stmt),
            PlannerEnum::Go(planner) => planner.match_planner(stmt),
            PlannerEnum::Lookup(planner) => planner.match_planner(stmt),
            PlannerEnum::Path(planner) => planner.match_planner(stmt),
            PlannerEnum::Subgraph(planner) => planner.match_planner(stmt),
            PlannerEnum::FetchVertices(planner) => planner.match_planner(stmt),
            PlannerEnum::FetchEdges(planner) => planner.match_planner(stmt),
            PlannerEnum::Maintain(planner) => planner.match_planner(stmt),
            PlannerEnum::UserManagement(planner) => planner.match_planner(stmt),
            PlannerEnum::Assignment(planner) => planner.match_planner(stmt),
            PlannerEnum::Insert(planner) => planner.match_planner(stmt),
            PlannerEnum::Copy(planner) => planner.match_planner(stmt),
            PlannerEnum::Delete(planner) => planner.match_planner(stmt),
            PlannerEnum::Update(planner) => planner.match_planner(stmt),
            PlannerEnum::Remove(planner) => planner.match_planner(stmt),
            PlannerEnum::Set(planner) => planner.match_planner(stmt),
            PlannerEnum::Merge(planner) => planner.match_planner(stmt),
            PlannerEnum::GroupBy(planner) => planner.match_planner(stmt),
            PlannerEnum::Filter(planner) => planner.match_planner(stmt),
            PlannerEnum::Collect(planner) => planner.match_planner(stmt),
            PlannerEnum::SetOperation(planner) => planner.match_planner(stmt),
            PlannerEnum::Use(planner) => planner.match_planner(stmt),
            PlannerEnum::Unwind(planner) => planner.match_planner(stmt),
            PlannerEnum::With(planner) => planner.match_planner(stmt),
            PlannerEnum::Return(planner) => planner.match_planner(stmt),
            PlannerEnum::AssignVariable(planner) => planner.match_planner(stmt),
            PlannerEnum::Yield(planner) => planner.match_planner(stmt),
            PlannerEnum::Pipe(planner) => planner.match_planner(stmt),
            PlannerEnum::Explain(planner) => planner.match_planner(stmt),
            PlannerEnum::FulltextSearch(planner) => planner.match_planner(stmt),
            #[cfg(feature = "vector")]
            PlannerEnum::VectorSearch(planner) => planner.match_planner(stmt),
        }
    }

    /// Plan from a BoundStatement, producing a SubPlan (PlanNodeEnum tree).
    pub fn plan_bound(
        &mut self,
        ctx: &crate::planning::context::PlanContext<'_>,
    ) -> Result<SubPlan, PlannerError> {
        match self {
            PlannerEnum::Match(planner) => planner.plan_bound(ctx),
            PlannerEnum::Go(planner) => planner.plan_bound(ctx),
            PlannerEnum::Lookup(planner) => planner.plan_bound(ctx),
            PlannerEnum::Path(planner) => planner.plan_bound(ctx),
            PlannerEnum::Subgraph(planner) => planner.plan_bound(ctx),
            PlannerEnum::FetchVertices(planner) => planner.plan_bound(ctx),
            PlannerEnum::FetchEdges(planner) => planner.plan_bound(ctx),
            PlannerEnum::Maintain(planner) => planner.plan_bound(ctx),
            PlannerEnum::UserManagement(planner) => planner.plan_bound(ctx),
            PlannerEnum::Assignment(planner) => planner.plan_bound(ctx),
            PlannerEnum::Insert(planner) => planner.plan_bound(ctx),
            PlannerEnum::Copy(planner) => planner.plan_bound(ctx),
            PlannerEnum::Delete(planner) => planner.plan_bound(ctx),
            PlannerEnum::Update(planner) => planner.plan_bound(ctx),
            PlannerEnum::Remove(planner) => planner.plan_bound(ctx),
            PlannerEnum::Set(planner) => planner.plan_bound(ctx),
            PlannerEnum::Merge(planner) => planner.plan_bound(ctx),
            PlannerEnum::GroupBy(planner) => planner.plan_bound(ctx),
            PlannerEnum::Filter(planner) => planner.plan_bound(ctx),
            PlannerEnum::Collect(planner) => planner.plan_bound(ctx),
            PlannerEnum::SetOperation(planner) => planner.plan_bound(ctx),
            PlannerEnum::Use(planner) => planner.plan_bound(ctx),
            PlannerEnum::Unwind(planner) => planner.plan_bound(ctx),
            PlannerEnum::With(planner) => planner.plan_bound(ctx),
            PlannerEnum::Return(planner) => planner.plan_bound(ctx),
            PlannerEnum::AssignVariable(planner) => planner.plan_bound(ctx),
            PlannerEnum::Yield(planner) => planner.plan_bound(ctx),
            PlannerEnum::Pipe(planner) => planner.plan_bound(ctx),
            PlannerEnum::Explain(planner) => planner.plan_bound(ctx),
            PlannerEnum::FulltextSearch(planner) => planner.plan_bound(ctx),
            #[cfg(feature = "vector")]
            PlannerEnum::VectorSearch(planner) => planner.plan_bound(ctx),
        }
    }
}

/// Error handling macros
#[macro_export]
macro_rules! ng_return_if_error {
    ($expr:expr) => {
        match $expr {
            Ok(val) => val,
            Err(e) => return Err(e.into()),
        }
    };
}

/// Error handling macro variants
#[macro_export]
macro_rules! ng_ok_or_err {
    ($expr:expr, $msg:expr) => {
        match $expr {
            Ok(val) => val,
            Err(_) => return Err(PlannerError::PlanGenerationFailed($msg.to_string())),
        }
    };
}

/// Planner error type
#[derive(Debug, thiserror::Error)]
pub enum PlannerError {
    #[error("No suitable planner found: {0}")]
    NoSuitablePlanner(String),

    #[error("Unsupported operation: {0}")]
    UnsupportedOperation(String),

    #[error("Plan generation failed: {0}")]
    PlanGenerationFailed(String),

    #[error("Join operation failed: {0}")]
    JoinFailed(String),

    #[error("Invalid AST context: {0}")]
    InvalidAstContext(String),

    #[error("Missing input: {0}")]
    MissingInput(String),

    #[error("Missing variable: {0}")]
    MissingVariable(String),

    #[error("Invalid operation: {0}")]
    InvalidOperation(String),

    #[error("Index not found: {0}")]
    IndexNotFound(String),

    #[error("Unsupported vector filter: {0}")]
    UnsupportedVectorFilter(String),

    #[error("Tag not found: {0}")]
    TagNotFound(String),

    #[error("Edge type not found: {0}")]
    EdgeTypeNotFound(String),

    #[error("Metadata version mismatch: expected {expected}, got {actual}")]
    MetadataVersionMismatch { expected: u64, actual: u64 },

    #[error("Invalid metadata: {0}")]
    InvalidMetadata(String),
}

// Implement the From conversion for the DBError class.
impl From<linkrs_core::error::DBError> for PlannerError {
    fn from(err: linkrs_core::error::DBError) -> Self {
        PlannerError::PlanGenerationFailed(err.to_string())
    }
}

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

    #[test]
    fn test_planner_enum_from_stmt() {
        // Testing the creation of a planner from a Stmt
        let match_stmt = Stmt::Match(crate::parser::ast::MatchStmt {
            span: linkrs_core::types::Span::default(),
            patterns: vec![],
            where_clause: None,
            return_clause: None,
            order_by: None,
            limit: None,
            skip: None,
            join_hint: None,
            optional: false,
            delete_clause: None,
        });

        let planner = PlannerEnum::from_stmt(&Arc::new(match_stmt));
        assert!(planner.is_some());
        assert_eq!(
            planner.expect("Planner should exist").name(),
            "MatchPlanner"
        );
    }

    #[test]
    fn test_planner_enum_matches() {
        let match_stmt = Stmt::Match(crate::parser::ast::MatchStmt {
            span: linkrs_core::types::Span::default(),
            patterns: vec![],
            where_clause: None,
            return_clause: None,
            order_by: None,
            limit: None,
            skip: None,
            join_hint: None,
            optional: false,
            delete_clause: None,
        });

        let planner = PlannerEnum::Match(Box::default());
        assert!(planner.matches(&match_stmt));
    }
}