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
//! Tool Statement Parsing Module
//!
//! Responsible for parsing statements related to tool functions, including USE, SHOW, EXPLAIN, FETCH, LOOKUP, UNWIND, RETURN, WITH, YIELD, SET, REMOVE, etc.

use crate::parser::ast::stmt::*;
use crate::parser::ast::types::OrderDirection;
use crate::parser::core::error::{ParseError, ParseErrorKind};
use crate::parser::parsing::clause_parser::ClauseParser;
use crate::parser::parsing::expr_parser::parse_expression_with_context;
use crate::parser::parsing::parse_context::ParseContext;
use crate::parser::TokenKind;
use linkrs_core::types::expr::contextual::ContextualExpression;

/// Tool Syntax Parser
pub struct UtilStmtParser;

impl UtilStmtParser {
    pub fn new() -> Self {
        Self
    }

    /// Analysis of the USE statement
    pub fn parse_use_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Use)?;

        // `USE GRAPH <name>` is a namespace alias for `USE <name>`.
        // `SPACE` is intentionally not consumed here: it stays a legal
        // space name in USE position, unlike CREATE/DROP where SPACE is
        // the object keyword (see ddl_parser::consume_space_or_graph).
        // A lone `USE graph` names the space `graph`: GRAPH only acts as
        // the alias keyword when another identifier follows it.
        if ctx.check_keyword("GRAPH") {
            let graph_word = ctx.current_token().lexeme.clone();
            ctx.consume_keyword("GRAPH")?;
            match ctx.expect_identifier() {
                Ok(space) => {
                    return Ok(Stmt::Use(UseStmt {
                        span: start_span,
                        space,
                    }));
                }
                Err(_) => {
                    return Ok(Stmt::Use(UseStmt {
                        span: start_span,
                        space: graph_word,
                    }));
                }
            }
        }

        let space = ctx.expect_identifier()?;

        Ok(Stmt::Use(UseStmt {
            span: start_span,
            space,
        }))
    }

    /// Analyzing the internal methods of the SHOW CREATE statement
    pub fn parse_show_create_internal(
        &mut self,
        ctx: &mut ParseContext,
        start_span: crate::parser::ast::types::Span,
    ) -> Result<Stmt, ParseError> {
        ctx.expect_token(TokenKind::Create)?;

        let target = if ctx.match_token(TokenKind::Space) {
            ShowCreateTarget::Space(ctx.expect_identifier()?)
        } else if ctx.match_token(TokenKind::Tag) {
            ShowCreateTarget::Tag(ctx.expect_identifier()?)
        } else if ctx.match_token(TokenKind::Edge) {
            ShowCreateTarget::Edge(ctx.expect_identifier()?)
        } else if ctx.match_token(TokenKind::Index) {
            ShowCreateTarget::Index(ctx.expect_identifier()?)
        } else {
            return Err(ParseError::new(
                ParseErrorKind::UnexpectedToken,
                "Expected SPACE, TAG, EDGE, or INDEX after SHOW CREATE".to_string(),
                ctx.current_position(),
            ));
        };

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::ShowCreate(ShowCreateStmt { span, target }))
    }

    /// Analysis of the internal methods of the SHOW ROLES command
    pub fn parse_show_roles_internal(
        &mut self,
        ctx: &mut ParseContext,
        start_span: crate::parser::ast::types::Span,
    ) -> Result<Stmt, ParseError> {
        ctx.expect_token(TokenKind::Roles)?;

        // Optional IN <space_name> clause; space names accept the same
        // hyphenated/quoted forms as other DCL object names.
        let space_name = if ctx.match_token(TokenKind::In) {
            Some(ctx.expect_dcl_name()?)
        } else {
            None
        };

        let span = ctx.span_since(start_span.start);

        Ok(Stmt::ShowRoles(ShowRolesStmt { span, space_name }))
    }

    /// Analyzing the EXPLAIN statement
    pub fn parse_explain_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let _start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Explain)?;

        // After “EXPLAIN”, a substatement needs to be parsed.
        // Here, we need to invoke the main parser, but due to circular dependency issues, we are returning a placeholder.
        // The actual parsing will be handled within the StmtParser.
        Err(ParseError::new(
            ParseErrorKind::SyntaxError,
            "EXPLAIN should be handled by main parser".to_string(),
            ctx.current_position(),
        ))
    }

    /// Analysis of the FETCH statement
    pub fn parse_fetch_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Fetch)?;

        // The FETCH PROP ON <tag> <ids> syntax is supported.
        let _with_props = ctx.match_token(TokenKind::Prop);

        // `->` is an edge arrow inside FETCH, not the JSON access operator
        // (`expr -> 'key'` postfix JSON get), so expression parsing must not
        // consume `src -> dst` as a JSON get.
        let target = ctx.with_edge_syntax_mode(|ctx| {
            if ctx.match_token(TokenKind::On) {
                // Check for * (all tags)
                let tag_name = if ctx.match_token(TokenKind::Star) {
                    None // None means all tags
                } else {
                    Some(ctx.expect_identifier()?)
                };

                let first_expr = self.parse_expression(ctx)?;
                if ctx.check_token(TokenKind::Arrow) {
                    ctx.expect_token(TokenKind::Arrow)?;
                    let dst = self.parse_expression(ctx)?;
                    let rank = if ctx.match_token(TokenKind::At) {
                        Some(self.parse_expression(ctx)?)
                    } else {
                        None
                    };
                    let edge_type = tag_name.ok_or_else(|| {
                        ParseError::new(
                            ParseErrorKind::SyntaxError,
                            "FETCH edge form requires an edge type; '*' is only valid for vertices"
                                .to_string(),
                            ctx.current_position(),
                        )
                    })?;
                    Ok(FetchTarget::Edges {
                        src: first_expr,
                        dst,
                        edge_type,
                        rank,
                        properties: None,
                    })
                } else {
                    let mut ids = vec![first_expr];
                    while ctx.match_token(TokenKind::Comma) {
                        ids.push(self.parse_expression(ctx)?);
                    }
                    Ok(FetchTarget::Vertices {
                        tag_name,
                        ids,
                        properties: None,
                    })
                }
            } else if ctx.match_token(TokenKind::Tag) {
                let tag_name = Some(ctx.expect_identifier()?);
                let ids = self.parse_expression_list(ctx)?;
                Ok(FetchTarget::Vertices {
                    tag_name,
                    ids,
                    properties: None,
                })
            } else if ctx.match_token(TokenKind::Edge) {
                let edge_type = ctx.expect_identifier()?;
                let src = self.parse_expression(ctx)?;
                ctx.expect_token(TokenKind::Arrow)?;
                let dst = self.parse_expression(ctx)?;
                let rank = if ctx.match_token(TokenKind::At) {
                    Some(self.parse_expression(ctx)?)
                } else {
                    None
                };
                Ok(FetchTarget::Edges {
                    src,
                    dst,
                    edge_type,
                    rank,
                    properties: None,
                })
            } else {
                let ids = self.parse_expression_list(ctx)?;
                Ok(FetchTarget::Vertices {
                    tag_name: None,
                    ids,
                    properties: None,
                })
            }
        })?;

        let yield_clause = if ctx.match_token(TokenKind::Yield) {
            Some(ClauseParser::new().parse_yield_clause(ctx)?)
        } else {
            None
        };

        Ok(Stmt::Fetch(FetchStmt {
            span: start_span,
            target,
            yield_clause,
        }))
    }

    /// Analysis of the LOOKUP statement
    pub fn parse_lookup_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Lookup)?;

        let target = if ctx.match_token(TokenKind::On) {
            // Check if it's an EDGE or TAG keyword followed by identifier
            if ctx.current_token().kind == TokenKind::Edge {
                // LOOKUP ON EDGE <name>
                ctx.next_token(); // consume EDGE
                let name = ctx.expect_identifier()?;
                LookupTarget::Edge(name)
            } else if ctx.current_token().kind == TokenKind::Tag {
                // LOOKUP ON TAG <name>
                ctx.next_token(); // consume TAG
                let name = ctx.expect_identifier()?;
                LookupTarget::Tag(name)
            } else {
                // LOOKUP ON <name> - type will be resolved during validation
                let name = ctx.expect_identifier()?;
                LookupTarget::Unspecified(name)
            }
        } else {
            LookupTarget::Unspecified(String::new())
        };

        let where_clause = if ctx.match_token(TokenKind::Where) {
            ctx.recover_clause(|_| Ok(None), |c| self.parse_expression(c).map(Some))?
        } else {
            None
        };

        let yield_clause = if ctx.match_token(TokenKind::Yield) {
            Some(ClauseParser::new().parse_yield_clause(ctx)?)
        } else {
            None
        };

        Ok(Stmt::Lookup(LookupStmt {
            span: start_span,
            target,
            where_clause,
            yield_clause,
        }))
    }

    /// Analysis of the UNWIND statement
    pub fn parse_unwind_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Unwind)?;

        let expression = self.parse_expression(ctx)?;

        ctx.match_token(TokenKind::As);

        let variable = ctx.expect_identifier()?;

        let return_clause = if ctx.match_token(TokenKind::Return) {
            Some(ClauseParser::new().parse_return_clause(ctx)?)
        } else {
            None
        };

        let order_by = None;
        let limit = None;
        let skip = None;

        Ok(Stmt::Unwind(UnwindStmt {
            span: start_span,
            expression,
            variable,
            return_clause,
            order_by,
            limit,
            skip,
        }))
    }

    /// Analysis of the RETURN statement
    pub fn parse_return_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Return)?;

        let return_clause = ClauseParser::new().parse_return_clause(ctx)?;

        Ok(Stmt::Return(ReturnStmt {
            span: start_span,
            items: return_clause.items,
            distinct: return_clause.distinct,
            order_by: return_clause.order_by,
            skip: return_clause.skip,
            limit: return_clause.limit,
        }))
    }

    /// Analysis of the WITH statement
    pub fn parse_with_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::With)?;

        let recursive = ctx.match_token(TokenKind::Recursive);

        // Common table expressions: `name AS (<query>) [, ...]`.
        // A `IDENT AS (` sequence can never start a plain WITH item (an
        // alias after AS must be an identifier), so detection is unambiguous.
        let mut ctes = Vec::new();
        while let Some(cte) = Self::try_parse_cte_def(ctx)? {
            ctes.push(cte);
            if !ctx.match_token(TokenKind::Comma) {
                break;
            }
        }

        let mut items = Vec::new();
        let distinct = ctx.match_token(TokenKind::Distinct);

        loop {
            let expr = self.parse_expression(ctx)?;
            let alias = if ctx.match_token(TokenKind::As) {
                Some(ctx.expect_identifier()?)
            } else {
                None
            };
            items.push(ReturnItem::Expression {
                expression: expr,
                alias,
            });
            if !ctx.match_token(TokenKind::Comma) {
                break;
            }
        }

        let where_clause = if ctx.match_token(TokenKind::Where) {
            ctx.recover_clause(|_| Ok(None), |c| self.parse_expression(c).map(Some))?
        } else {
            None
        };

        // Explanation of `ORDER BY`
        let order_by = if ctx.match_token(TokenKind::Order) {
            ctx.recover_clause(
                |_| Ok(None),
                |c| {
                    c.expect_token(TokenKind::By)?;
                    self.parse_order_by_clause(c).map(Some)
                },
            )?
        } else {
            None
        };

        // Analysis of SKIP
        let skip = if ctx.match_token(TokenKind::Skip) {
            ctx.recover_clause(
                |_| Ok(None),
                |c| {
                    let count = c.expect_integer_literal()? as usize;
                    Ok(Some(crate::parser::ast::types::SkipClause {
                        span: c.current_span(),
                        count,
                    }))
                },
            )?
        } else {
            None
        };

        // Analysis of the LIMIT clause
        let limit = if ctx.match_token(TokenKind::Limit) {
            ctx.recover_clause(
                |_| Ok(None),
                |c| {
                    let count = c.expect_integer_literal()? as usize;
                    Ok(Some(crate::parser::ast::types::LimitClause {
                        span: c.current_span(),
                        count,
                    }))
                },
            )?
        } else {
            None
        };

        Ok(Stmt::With(WithStmt {
            span: start_span,
            items,
            where_clause,
            distinct,
            order_by,
            skip,
            limit,
            recursive,
            ctes,
        }))
    }

    /// Try to parse one `name AS (<query>)` CTE definition.
    ///
    /// Returns `Ok(None)` (without consuming input) when the upcoming tokens
    /// do not form a CTE header.
    fn try_parse_cte_def(ctx: &mut ParseContext) -> Result<Option<CteDef>, ParseError> {
        let ckpt = ctx.checkpoint();
        let name = match ctx.expect_identifier() {
            Ok(name) => name,
            Err(_) => {
                ctx.restore(ckpt);
                return Ok(None);
            }
        };
        // A CTE definition is always `name AS (`; `name (` starts a function
        // call item instead (e.g. `WITH count(*) AS total`), so back off and
        // let the expression parser handle it.
        if ctx.check_token(TokenKind::LParen) {
            ctx.restore(ckpt);
            return Ok(None);
        }
        if !ctx.check_keyword("AS") {
            ctx.restore(ckpt);
            return Ok(None);
        }
        ctx.consume_keyword("AS")?;
        if !ctx.check_token(TokenKind::LParen) {
            ctx.restore(ckpt);
            return Ok(None);
        }
        let cte_span = ctx.current_span();
        ctx.expect_token(TokenKind::LParen)?;
        let body = crate::parser::parsing::StmtParser::parse_statement(ctx).map_err(|e| {
            ParseError::new(
                ParseErrorKind::SyntaxError,
                format!("Invalid CTE body for '{}': {}", name, e),
                ctx.current_position(),
            )
        })?;
        ctx.expect_token(TokenKind::RParen)?;
        Ok(Some(CteDef {
            span: cte_span,
            name,
            body: Box::new(body),
        }))
    }

    /// Analysis of the YIELD statement
    pub fn parse_yield_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Yield)?;

        let yield_clause = ClauseParser::new().parse_yield_clause(ctx)?;

        Ok(Stmt::Yield(YieldStmt {
            span: start_span,
            items: yield_clause.items,
            where_clause: yield_clause.where_clause,
            distinct: yield_clause.distinct,
            order_by: yield_clause.order_by,
            skip: yield_clause.skip,
            limit: yield_clause.limit,
            sample: yield_clause.sample,
        }))
    }

    /// Analyzing the SET statement
    pub fn parse_set_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Set)?;

        let set_clause = ClauseParser::new().parse_set_clause(ctx)?;

        Ok(Stmt::Set(SetStmt {
            span: start_span,
            assignments: set_clause.assignments,
        }))
    }

    /// Analysis of the REMOVE statement
    pub fn parse_remove_statement(&mut self, ctx: &mut ParseContext) -> Result<Stmt, ParseError> {
        let start_span = ctx.current_span();
        ctx.expect_token(TokenKind::Remove)?;

        let mut items = Vec::new();
        loop {
            items.push(self.parse_expression(ctx)?);
            if !ctx.match_token(TokenKind::Comma) {
                break;
            }
        }

        Ok(Stmt::Remove(RemoveStmt {
            span: start_span,
            items,
        }))
    }

    /// Parse the list of expressions
    fn parse_expression_list(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<Vec<ContextualExpression>, ParseError> {
        let mut expressions = Vec::new();

        loop {
            expressions.push(self.parse_expression(ctx)?);
            if !ctx.match_token(TokenKind::Comma) {
                break;
            }
        }

        Ok(expressions)
    }

    /// Analyzing the expression
    fn parse_expression(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<ContextualExpression, ParseError> {
        parse_expression_with_context(ctx, ctx.expression_context_clone())
    }

    /// Analysis of the ORDER BY clause
    fn parse_order_by_clause(
        &mut self,
        ctx: &mut ParseContext,
    ) -> Result<OrderByClause, ParseError> {
        let span = ctx.current_span();
        let mut items = Vec::new();

        loop {
            let expr = self.parse_expression(ctx)?;
            let direction = if ctx.match_token(TokenKind::Asc) {
                OrderDirection::Asc
            } else if ctx.match_token(TokenKind::Desc) {
                OrderDirection::Desc
            } else {
                OrderDirection::Asc
            };
            items.push(OrderByItem {
                expression: expr,
                direction,
            });
            if !ctx.match_token(TokenKind::Comma) {
                break;
            }
        }

        Ok(OrderByClause { span, items })
    }
}

impl Default for UtilStmtParser {
    fn default() -> Self {
        Self::new()
    }
}