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
//! Experimental query-pipeline extension points.
//!
//! Unstable API: trait signatures are intentionally small (single method
//! with a default `None`) and may evolve without the usual compatibility
//! guarantees while the pipeline integration matures.
//!
//! Mirrors the ladybug four-piece set (`TransformerExtension` /
//! `BinderExtension` / `PlannerExtension` / `MapperExtension`) with this
//! project's own types. All hooks are opt-in: an empty registry leaves the
//! builtin pipeline untouched.
//!
//! Semantics match ladybug: extensions are tried in registration order, the
//! first `Some` wins, `None` falls through to the builtin logic. A panicking
//! extension is isolated with `catch_unwind`, logged, and treated as `None`
//! so a broken extension can never break queries.
//!
//! This module is experimental: trait signatures are intentionally small
//! (single method + default `None`) and may evolve.

use std::sync::Arc;

use linkrs_core::error::DBResult;
use parking_lot::RwLock;

use crate::binder::BoundStatement;
use crate::parser::ast::stmt::Ast;
use crate::planning::plan::ExecutionPlan;
use crate::planning::plan::SubPlan;

/// Input context for [`BinderExtension::bind`].
#[derive(Debug, Clone, Default)]
pub struct BinderExtensionContext {
    pub space_name: Option<String>,
    pub space_id: u64,
}

/// Rewrite the raw query text before parsing.
///
/// Return `None` to decline (builtin parsing proceeds).
pub trait ParserExtension: Send + Sync + std::fmt::Debug {
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    fn transform(&self, _query_text: &str) -> Option<DBResult<String>> {
        None
    }
}

/// Bind a parsed AST into a [`BoundStatement`], bypassing the builtin binder.
///
/// Return `None` to decline (builtin binding proceeds).
pub trait BinderExtension: Send + Sync + std::fmt::Debug {
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    fn bind(
        &self,
        _ast: &Arc<Ast>,
        _ctx: &BinderExtensionContext,
    ) -> Option<DBResult<BoundStatement>> {
        None
    }
}

/// Plan a bound statement into a [`SubPlan`], bypassing builtin planners.
///
/// Return `None` to decline (builtin planning proceeds).
pub trait PlannerExtension: Send + Sync + std::fmt::Debug {
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    fn plan(&self, _bound: &BoundStatement) -> Option<DBResult<SubPlan>> {
        None
    }
}

/// Inspect or rewrite an optimized [`ExecutionPlan`] at the mapper boundary
/// (after logical optimization, before physical plan building).
///
/// Return `None` to decline (builtin plan is used as-is).
pub trait MapperExtension: Send + Sync + std::fmt::Debug {
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    fn map(&self, _plan: &ExecutionPlan) -> Option<DBResult<ExecutionPlan>> {
        None
    }
}

/// Ordered registry for pipeline extensions.
///
/// `Arc`-shared so the pipeline manager and tests can hold the same instance.
#[derive(Debug, Default)]
pub struct ExtensionRegistry {
    parsers: RwLock<Vec<Arc<dyn ParserExtension>>>,
    binders: RwLock<Vec<Arc<dyn BinderExtension>>>,
    planners: RwLock<Vec<Arc<dyn PlannerExtension>>>,
    mappers: RwLock<Vec<Arc<dyn MapperExtension>>>,
}

impl ExtensionRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_parser_extension(&self, extension: Arc<dyn ParserExtension>) {
        self.parsers.write().push(extension);
    }

    pub fn add_binder_extension(&self, extension: Arc<dyn BinderExtension>) {
        self.binders.write().push(extension);
    }

    pub fn add_planner_extension(&self, extension: Arc<dyn PlannerExtension>) {
        self.planners.write().push(extension);
    }

    pub fn add_mapper_extension(&self, extension: Arc<dyn MapperExtension>) {
        self.mappers.write().push(extension);
    }

    pub fn parser_extension_count(&self) -> usize {
        self.parsers.read().len()
    }

    pub fn binder_extension_count(&self) -> usize {
        self.binders.read().len()
    }

    pub fn planner_extension_count(&self) -> usize {
        self.planners.read().len()
    }

    pub fn mapper_extension_count(&self) -> usize {
        self.mappers.read().len()
    }

    fn snapshot_parsers(&self) -> Vec<Arc<dyn ParserExtension>> {
        let guard = self.parsers.read();
        if guard.is_empty() {
            return Vec::new();
        }
        guard.clone()
    }

    fn snapshot_binders(&self) -> Vec<Arc<dyn BinderExtension>> {
        let guard = self.binders.read();
        if guard.is_empty() {
            return Vec::new();
        }
        guard.clone()
    }

    fn snapshot_planners(&self) -> Vec<Arc<dyn PlannerExtension>> {
        let guard = self.planners.read();
        if guard.is_empty() {
            return Vec::new();
        }
        guard.clone()
    }

    fn snapshot_mappers(&self) -> Vec<Arc<dyn MapperExtension>> {
        let guard = self.mappers.read();
        if guard.is_empty() {
            return Vec::new();
        }
        guard.clone()
    }

    /// First `Some` wins; panics are isolated to `None`.
    pub fn try_parse_transform(&self, query_text: &str) -> Option<DBResult<String>> {
        for extension in self.snapshot_parsers() {
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                extension.transform(query_text)
            }));
            match outcome {
                Ok(Some(result)) => return Some(result),
                Ok(None) => continue,
                Err(_) => {
                    log::error!(
                        "parser extension {} panicked; falling back to builtin",
                        extension.name()
                    );
                }
            }
        }
        None
    }

    /// First `Some` wins; panics are isolated to `None`.
    pub fn try_bind(
        &self,
        ast: &Arc<Ast>,
        ctx: &BinderExtensionContext,
    ) -> Option<DBResult<BoundStatement>> {
        for extension in self.snapshot_binders() {
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| extension.bind(ast, ctx)));
            match outcome {
                Ok(Some(result)) => return Some(result),
                Ok(None) => continue,
                Err(_) => {
                    log::error!(
                        "binder extension {} panicked; falling back to builtin",
                        extension.name()
                    );
                }
            }
        }
        None
    }

    /// First `Some` wins; panics are isolated to `None`.
    pub fn try_plan(&self, bound: &BoundStatement) -> Option<DBResult<SubPlan>> {
        for extension in self.snapshot_planners() {
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| extension.plan(bound)));
            match outcome {
                Ok(Some(result)) => return Some(result),
                Ok(None) => continue,
                Err(_) => {
                    log::error!(
                        "planner extension {} panicked; falling back to builtin",
                        extension.name()
                    );
                }
            }
        }
        None
    }

    /// First `Some` wins; panics are isolated to `None`.
    pub fn try_map(&self, plan: &ExecutionPlan) -> Option<DBResult<ExecutionPlan>> {
        for extension in self.snapshot_mappers() {
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| extension.map(plan)));
            match outcome {
                Ok(Some(result)) => return Some(result),
                Ok(None) => continue,
                Err(_) => {
                    log::error!(
                        "mapper extension {} panicked; falling back to builtin",
                        extension.name()
                    );
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::Parser;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn parse_ast(query: &str) -> Arc<Ast> {
        let mut parser = Parser::new(query);
        let result = parser.parse().expect("test query parses");
        assert!(!parser.has_errors());
        result.ast
    }

    #[derive(Debug)]
    struct ShowInterceptor {
        hits: Arc<AtomicUsize>,
    }

    impl BinderExtension for ShowInterceptor {
        fn bind(
            &self,
            ast: &Arc<Ast>,
            _ctx: &BinderExtensionContext,
        ) -> Option<DBResult<BoundStatement>> {
            if matches!(ast.stmt(), crate::parser::ast::Stmt::Show(_)) {
                self.hits.fetch_add(1, Ordering::SeqCst);
                // Rewrite: collapse any SHOW into a synthetic SHOW SPACES form
                // by reusing the parsed statement as opaque payload.
                return Some(Ok(BoundStatement::Other(Box::new(ast.stmt().clone()))));
            }
            None
        }
    }

    #[derive(Debug)]
    struct PanickingBinder;

    impl BinderExtension for PanickingBinder {
        fn bind(
            &self,
            _ast: &Arc<Ast>,
            _ctx: &BinderExtensionContext,
        ) -> Option<DBResult<BoundStatement>> {
            panic!("extension boom");
        }
    }

    #[derive(Debug)]
    struct PanickingPlanner;

    impl PlannerExtension for PanickingPlanner {
        fn plan(&self, _bound: &BoundStatement) -> Option<DBResult<SubPlan>> {
            panic!("planner boom");
        }
    }

    #[derive(Debug)]
    struct OtherClaimingPlanner {
        hits: Arc<AtomicUsize>,
    }

    impl PlannerExtension for OtherClaimingPlanner {
        fn plan(&self, bound: &BoundStatement) -> Option<DBResult<SubPlan>> {
            if matches!(bound, BoundStatement::Other(_)) {
                self.hits.fetch_add(1, Ordering::SeqCst);
                return Some(Ok(SubPlan::new(None, None)));
            }
            None
        }
    }

    #[derive(Debug)]
    struct IdentityMapper {
        hits: Arc<AtomicUsize>,
    }

    impl MapperExtension for IdentityMapper {
        fn map(&self, plan: &ExecutionPlan) -> Option<DBResult<ExecutionPlan>> {
            self.hits.fetch_add(1, Ordering::SeqCst);
            Some(Ok(plan.clone()))
        }
    }

    #[derive(Debug)]
    struct PrefixParser;

    impl ParserExtension for PrefixParser {
        fn transform(&self, query_text: &str) -> Option<DBResult<String>> {
            if query_text.starts_with("/* ext */") {
                return Some(Ok(query_text.trim_start_matches("/* ext */").to_string()));
            }
            None
        }
    }

    #[test]
    fn binder_extension_intercepts_and_rewrites() {
        let registry = ExtensionRegistry::new();
        let hits = Arc::new(AtomicUsize::new(0));
        registry.add_binder_extension(Arc::new(ShowInterceptor {
            hits: Arc::clone(&hits),
        }));

        let ast = parse_ast("SHOW SPACES");
        let rewritten = registry
            .try_bind(&ast, &BinderExtensionContext::default())
            .expect("interceptor claims SHOW");
        assert!(rewritten.is_ok());
        assert_eq!(hits.load(Ordering::SeqCst), 1);

        // Non-matching statements fall through to builtin (None).
        let other = parse_ast("MATCH (n) RETURN n");
        assert!(registry
            .try_bind(&other, &BinderExtensionContext::default())
            .is_none());
    }

    #[test]
    fn panicking_extensions_fall_back_to_builtin() {
        let registry = ExtensionRegistry::new();
        registry.add_binder_extension(Arc::new(PanickingBinder));
        registry.add_planner_extension(Arc::new(PanickingPlanner));

        let ast = parse_ast("MATCH (n) RETURN n");
        assert!(registry
            .try_bind(&ast, &BinderExtensionContext::default())
            .is_none());

        let bound = BoundStatement::Other(Box::new(ast.stmt().clone()));
        assert!(registry.try_plan(&bound).is_none());
    }

    #[test]
    fn planner_extension_intercepts_matching_bound_statement() {
        let registry = ExtensionRegistry::new();
        let hits = Arc::new(AtomicUsize::new(0));
        registry.add_planner_extension(Arc::new(OtherClaimingPlanner {
            hits: Arc::clone(&hits),
        }));

        let ast = parse_ast("SHOW SPACES");
        let bound = BoundStatement::Other(Box::new(ast.stmt().clone()));
        let planned = registry
            .try_plan(&bound)
            .expect("other-claiming planner handles Other");
        assert!(planned.is_ok());
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn parser_and_mapper_stubs_register_and_invoke() {
        let registry = ExtensionRegistry::new();
        registry.add_parser_extension(Arc::new(PrefixParser));
        assert_eq!(registry.parser_extension_count(), 1);

        let rewritten = registry
            .try_parse_transform("/* ext */MATCH (n) RETURN n")
            .expect("prefix parser claims marked queries");
        assert_eq!(rewritten.unwrap(), "MATCH (n) RETURN n");
        assert!(registry.try_parse_transform("MATCH (n) RETURN n").is_none());

        // Mapper stub proves the registration/callable contract; an empty
        // optimized plan round-trips through the identity mapper.
        let hits = Arc::new(AtomicUsize::new(0));
        registry.add_mapper_extension(Arc::new(IdentityMapper {
            hits: Arc::clone(&hits),
        }));
        let plan = ExecutionPlan::new(None);
        let mapped = registry
            .try_map(&plan)
            .expect("identity mapper claims everything");
        assert!(mapped.is_ok());
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }
}