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
use linkrs_core::types::expr::analysis_utils::collect_variables_from_contextual;
use linkrs_core::types::expr::contextual::ContextualExpression;
use linkrs_core::types::Span;

use super::PatternUtils;

use super::{CreateTarget, DeleteTarget, FetchTarget, UpdateTarget};
use super::{OrderByClause, ReturnClause, ReturnItem, Stmt, YieldClause};
use crate::parser::ast::types::{LimitClause, SkipClause};

#[derive(Debug, Clone, PartialEq)]
pub struct UseStmt {
    pub span: Span,
    pub space: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ShowStmt {
    pub span: Span,
    pub target: ShowTarget,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ShowTarget {
    Spaces,
    Tags,
    Edges,
    Indexes,
    Index(String),
    Stats,
    Functions,
    Graphs,
    Macros,
    AttachedDatabases,
    Extensions,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub enum ExplainFormat {
    #[default]
    Table,
    Dot,
}

#[derive(Debug, Clone)]
pub struct ExplainStmt {
    pub span: Span,
    pub statement: Box<Stmt>,
    pub format: ExplainFormat,
    /// Whether the statement is executed and actual operator statistics
    /// (rows / time) are overlaid on the plan output.
    pub analyze: bool,
}

impl PartialEq for ExplainStmt {
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span && self.format == other.format && self.analyze == other.analyze
    }
}

#[derive(Debug, Clone)]
pub struct ProfileStmt {
    pub span: Span,
    pub statement: Box<Stmt>,
    pub format: ExplainFormat,
}

/// ANALYZE statement: collect statistics for a space.
#[derive(Debug, Clone, PartialEq)]
pub struct AnalyzeStmt {
    pub span: Span,
    /// None = current/default space.
    pub space: Option<String>,
}

impl PartialEq for ProfileStmt {
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span && self.format == other.format
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum GroupingType {
    Standard,
    Rollup(Vec<ContextualExpression>),
    Cube(Vec<ContextualExpression>),
    GroupingSets(Vec<Vec<ContextualExpression>>),
}

#[derive(Debug, Clone, PartialEq)]
pub struct GroupByStmt {
    pub span: Span,
    pub group_items: Vec<ContextualExpression>,
    pub grouping_type: GroupingType,
    pub yield_clause: YieldClause,
    pub having_clause: Option<ContextualExpression>,
}

#[derive(Debug, Clone)]
pub struct PipeStmt {
    pub span: Span,
    pub left: Box<Stmt>,
    pub right: Box<Stmt>,
}

impl PartialEq for PipeStmt {
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct UnwindStmt {
    pub span: Span,
    pub expression: ContextualExpression,
    pub variable: String,
    pub return_clause: Option<ReturnClause>,
    pub order_by: Option<OrderByClause>,
    pub limit: Option<LimitClause>,
    pub skip: Option<SkipClause>,
}

#[derive(Debug, Clone)]
pub struct WithStmt {
    pub span: Span,
    pub items: Vec<ReturnItem>,
    pub where_clause: Option<ContextualExpression>,
    pub distinct: bool,
    pub order_by: Option<OrderByClause>,
    pub skip: Option<SkipClause>,
    pub limit: Option<LimitClause>,
    pub recursive: bool,
    pub ctes: Vec<CteDef>,
}

/// A common table expression defined in a WITH clause.
///
/// `name AS (<body>)` where the body is a single query, or — under
/// `WITH RECURSIVE` — `anchor UNION ALL step`. V1 supports exactly one CTE
/// per WITH and single-column anchors; the planner reports wider shapes
/// with a precise error.
#[derive(Debug, Clone)]
pub struct CteDef {
    pub span: Span,
    pub name: String,
    pub body: Box<Stmt>,
}

/// A standalone WHERE stage used as a pipe suffix (e.g. `GO ... | WHERE age > 25`).
#[derive(Debug, Clone, PartialEq)]
pub struct FilterStmt {
    pub span: Span,
    pub expression: ContextualExpression,
}

/// A standalone COLLECT stage used as a pipe suffix (e.g. `| COLLECT LIST(name) AS names`).
#[derive(Debug, Clone, PartialEq)]
pub struct CollectStmt {
    pub span: Span,
    pub items: Vec<super::YieldItem>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ShowSessionsStmt {
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ShowQueriesStmt {
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub struct KillQueryStmt {
    pub span: Span,
    pub session_id: i64,
    pub plan_id: i64,
}

/// Target schema of a [`PurgeExpiredStmt`]: a single tag or edge type.
/// `None` (when the whole field is `None`) means "every TTL-configured
/// schema in the space".
#[derive(Debug, Clone, PartialEq)]
pub enum PurgeTarget {
    Tag(String),
    Edge(String),
}

/// `PURGE EXPIRED [TAG <tag> | EDGE <edge>] IN <space>` statement.
///
/// Physically deletes TTL-expired rows. Without a target it scans every
/// TTL-configured tag and edge type in the space; a target restricts the
/// scan to one schema.
#[derive(Debug, Clone, PartialEq)]
pub struct PurgeExpiredStmt {
    pub span: Span,
    pub space_name: String,
    pub target: Option<PurgeTarget>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ShowConfigsStmt {
    pub span: Span,
    pub module: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct UpdateConfigsStmt {
    pub span: Span,
    pub module: Option<String>,
    pub config_name: String,
    pub config_value: ContextualExpression,
}

#[derive(Debug, Clone)]
pub struct AssignmentStmt {
    pub span: Span,
    pub variable: String,
    pub statement: Box<Stmt>,
}

impl PartialEq for AssignmentStmt {
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span && self.variable == other.variable
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum SetOperationType {
    Union,
    UnionAll,
    Intersect,
    Minus,
}

#[derive(Debug, Clone)]
pub struct SetOperationStmt {
    pub span: Span,
    pub op_type: SetOperationType,
    pub left: Box<Stmt>,
    pub right: Box<Stmt>,
}

impl PartialEq for SetOperationStmt {
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span && self.op_type == other.op_type
    }
}

/// `EXPORT DATABASE '<path>' [WITH OPTIONS (...)]` statement.
#[derive(Debug, Clone, PartialEq)]
pub struct ExportDatabaseStmt {
    pub span: Span,
    pub path: String,
    pub options: Vec<ExportOption>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ExportOption {
    pub key: String,
    pub value: String,
}

/// `IMPORT DATABASE '<path>'` statement.
#[derive(Debug, Clone, PartialEq)]
pub struct ImportDatabaseStmt {
    pub span: Span,
    pub path: String,
}

/// Extension management action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtensionAction {
    /// `LOAD EXTENSION '<path>'`: load a UDF dynamic library.
    Load,
    /// `INSTALL EXTENSION <name> FROM '<source>'`: install from a local file source.
    Install,
    /// `UNINSTALL EXTENSION <name>`: unload a previously loaded UDF.
    Uninstall,
    /// `UPDATE EXTENSION <name>`: reload a previously loaded UDF from its
    /// original library path.
    Update,
}

/// `ATTACH '<path>' AS <alias> [(DBTYPE <type>)]` statement.
///
/// Registers an external data source in the attached-database catalog so it
/// can be observed via `SHOW ATTACHED DATABASES`. Cross-source federation is
/// not implemented; only the catalog entry is produced.
#[derive(Debug, Clone, PartialEq)]
pub struct AttachDatabaseStmt {
    pub span: Span,
    /// Source path/URL as written in the statement.
    pub path: String,
    /// Alias used to reference the source after attachment.
    pub alias: String,
    /// Optional declared source type (`DBTYPE <name>` or `DATABASE_TYPE = ...`).
    pub db_type: Option<String>,
    /// Additional key/value options from the parenthesized list.
    pub options: Vec<(String, String)>,
}

/// `DETACH <alias>` statement.
///
/// Removes a previously registered attachment from the catalog. Distinct from
/// `DETACH DELETE`, which is parsed as part of the DELETE statement.
#[derive(Debug, Clone, PartialEq)]
pub struct DetachDatabaseStmt {
    pub span: Span,
    pub alias: String,
}

/// `LOAD EXTENSION` / `INSTALL EXTENSION` / `UNINSTALL EXTENSION` /
/// `UPDATE EXTENSION` statement.
///
/// Extension statements are executed directly by the session layer against
/// the function registry; they never reach the planner.
#[derive(Debug, Clone, PartialEq)]
pub struct ExtensionStmt {
    pub span: Span,
    pub action: ExtensionAction,
    /// Function name (install/uninstall) or library path (load).
    pub name: String,
    /// Install source path (`INSTALL ... FROM`). `None` for load/uninstall.
    pub source: Option<String>,
}

pub struct StmtUtils;

impl StmtUtils {
    pub fn find_variables(stmt: &Stmt) -> Vec<String> {
        let mut variables = Vec::new();
        Self::find_variables_recursive(stmt, &mut variables);
        variables
    }

    fn find_variables_recursive(stmt: &Stmt, variables: &mut Vec<String>) {
        match stmt {
            Stmt::Match(s) => {
                for pattern in &s.patterns {
                    variables.extend(PatternUtils::find_variables(pattern));
                }
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            Stmt::Create(s) => match &s.target {
                CreateTarget::Node {
                    properties: Some(props),
                    ..
                } => {
                    variables.extend(collect_variables_from_contextual(props));
                }
                CreateTarget::Edge {
                    src,
                    dst,
                    properties: Some(props),
                    ..
                } => {
                    variables.extend(collect_variables_from_contextual(src));
                    variables.extend(collect_variables_from_contextual(dst));
                    variables.extend(collect_variables_from_contextual(props));
                }
                _ => {}
            },
            Stmt::Delete(s) => match &s.target {
                DeleteTarget::Vertices { vids, .. } => {
                    for vertex in vids {
                        variables.extend(collect_variables_from_contextual(vertex));
                    }
                }
                DeleteTarget::Edges { edges, .. } => {
                    for (src, dst, rank) in edges {
                        variables.extend(collect_variables_from_contextual(src));
                        variables.extend(collect_variables_from_contextual(dst));
                        if let Some(ref rank) = rank {
                            variables.extend(collect_variables_from_contextual(rank));
                        }
                    }
                }
                _ => {}
            },
            Stmt::Update(s) => {
                match &s.target {
                    UpdateTarget::Vertex(vertex) => {
                        variables.extend(collect_variables_from_contextual(vertex));
                    }
                    UpdateTarget::Edge { src, dst, rank, .. } => {
                        variables.extend(collect_variables_from_contextual(src));
                        variables.extend(collect_variables_from_contextual(dst));
                        if let Some(ref rank) = rank {
                            variables.extend(collect_variables_from_contextual(rank));
                        }
                    }
                    _ => {}
                }
                for assignment in &s.set_clause.assignments {
                    variables.extend(collect_variables_from_contextual(&assignment.value));
                }
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            Stmt::Go(s) => {
                for vertex in &s.from.vertices {
                    variables.extend(collect_variables_from_contextual(vertex));
                }
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            Stmt::Fetch(s) => match &s.target {
                FetchTarget::Vertices { ids, .. } => {
                    for id in ids {
                        variables.extend(collect_variables_from_contextual(id));
                    }
                }
                FetchTarget::Edges { src, dst, rank, .. } => {
                    variables.extend(collect_variables_from_contextual(src));
                    variables.extend(collect_variables_from_contextual(dst));
                    if let Some(ref rank) = rank {
                        variables.extend(collect_variables_from_contextual(rank));
                    }
                }
            },
            Stmt::Lookup(s) => {
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            Stmt::Subgraph(s) => {
                for vertex in &s.from.vertices {
                    variables.extend(collect_variables_from_contextual(vertex));
                }
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            Stmt::FindPath(s) => {
                for vertex in &s.from.vertices {
                    variables.extend(collect_variables_from_contextual(vertex));
                }
                variables.extend(collect_variables_from_contextual(&s.to));
                if let Some(ref where_clause) = s.where_clause {
                    variables.extend(collect_variables_from_contextual(where_clause));
                }
            }
            _ => {}
        }
    }
}