selene-db-gql 1.3.0

ISO/IEC 39075:2024 GQL parser, planner, optimizer, and executor for selene-db.
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
//! Bind-pass orchestration.

pub(crate) mod aggregate_rules;
pub(crate) mod call;
pub(crate) mod ddl;
pub(crate) mod element_ref;
pub(crate) mod expr;
pub(crate) mod expr_depth;
pub(crate) mod mutation;
pub(crate) mod parameter_inheritance;
pub(crate) mod parameters;
pub(crate) mod pattern;
pub(crate) mod query;
pub(crate) mod session;
pub(crate) mod transaction;

use selene_core::DbString;

use crate::{
    ProcedureRegistry, SourceSpan, Statement, ValueExpr,
    analyze::{
        ast::AnalyzedStatement,
        binding::{BindingDeclKind, BindingId, BindingUse, BindingUseKind},
        category::{self, StatementCategory},
        error::AnalysisError,
        scope::{BindingScopeTree, ScopeId, ScopeKind},
        types::{AnalyzedType, ExprId, ExprIdLookup, ExprTypeTable},
        write_set::{ElementKind, MutationWriteSet, WriteKind, WriteSetEntry},
    },
};

pub(crate) const ANALYZER_MAX_DEPTH: u32 = 256;

/// Analyze one statement with the binding pass.
pub(crate) fn bind_statement(
    mut stmt: Statement,
    registry: &dyn ProcedureRegistry,
) -> Result<AnalyzedStatement, AnalysisError> {
    parameters::apply_statement_parameter_declarations(&mut stmt)?;
    let mut ctx = BindContext::new(stmt.span(), registry);
    let bind_result = (|| -> Result<(), AnalysisError> {
        match &mut stmt {
            Statement::Query(pipeline) => query::bind_query_pipeline(&mut ctx, pipeline)?,
            Statement::Composite { first, rest, .. } => {
                ctx.with_child_scope(ScopeKind::Projection, first.span, true, |ctx| {
                    query::bind_query_pipeline(ctx, first)
                })?;
                for (_, pipeline) in rest {
                    ctx.with_child_scope(ScopeKind::Projection, pipeline.span, true, |ctx| {
                        query::bind_query_pipeline(ctx, pipeline)
                    })?;
                }
            }
            Statement::Chained { blocks, .. } => {
                // Each NEXT block consumes the prior block's binding table, so
                // we run sequential blocks in scopes chained off the previous
                // block's *terminal* scope (which holds the projection aliases
                // each block published). Boundary stays `false` so post-RETURN
                // bindings flow forward through GA07.
                let root = ctx.current_scope();
                let mut prior_tail = root;
                for block in blocks {
                    let block_root =
                        ctx.scopes
                            .push_scope(prior_tail, ScopeKind::Projection, block.span, false);
                    ctx.set_scope(block_root);
                    query::bind_query_pipeline(&mut ctx, block)?;
                    prior_tail = ctx.current_scope();
                }
                ctx.set_scope(root);
            }
            Statement::Mutate(pipeline) => mutation::bind_mutation_pipeline(&mut ctx, pipeline)?,
            Statement::Ddl(statement) => ddl::bind_ddl_statement(&mut ctx, statement)?,
            Statement::Call(call) => {
                call::bind_procedure_call(&mut ctx, call)?;
            }
            Statement::Explain { inner, .. } => bind_explain_inner(&mut ctx, inner)?,
            Statement::StartTransaction { span }
            | Statement::Commit { span }
            | Statement::Rollback { span } => {
                transaction::bind_transaction_control(&mut ctx, *span)
            }
            Statement::SessionSetValue { span, .. }
            | Statement::SessionSetTimeZone { span, .. }
            | Statement::SessionSetGraph { span, .. }
            | Statement::SessionReset { span, .. }
            | Statement::SessionClose { span } => session::bind_session_command(&mut ctx, *span),
        }
        Ok(())
    })();
    bind_result?;
    let category = category::classify(&stmt, registry);
    let write_set = statement_write_set(&stmt).then(|| ctx.write_set.clone());
    Ok(ctx.finish(stmt, category, write_set))
}

fn bind_explain_inner(
    ctx: &mut BindContext<'_>,
    inner: &mut Statement,
) -> Result<(), AnalysisError> {
    match inner {
        Statement::Query(pipeline) => query::bind_query_pipeline(ctx, pipeline),
        Statement::Composite { first, rest, .. } => {
            ctx.with_child_scope(ScopeKind::Projection, first.span, true, |ctx| {
                query::bind_query_pipeline(ctx, first)
            })?;
            for (_, pipeline) in rest {
                ctx.with_child_scope(ScopeKind::Projection, pipeline.span, true, |ctx| {
                    query::bind_query_pipeline(ctx, pipeline)
                })?;
            }
            Ok(())
        }
        Statement::Chained { blocks, .. } => {
            let root = ctx.current_scope();
            let mut prior_tail = root;
            for block in blocks {
                let block_root =
                    ctx.scopes
                        .push_scope(prior_tail, ScopeKind::Projection, block.span, false);
                ctx.set_scope(block_root);
                query::bind_query_pipeline(ctx, block)?;
                prior_tail = ctx.current_scope();
            }
            ctx.set_scope(root);
            Ok(())
        }
        Statement::Mutate(pipeline) => mutation::bind_mutation_pipeline(ctx, pipeline),
        Statement::Ddl(statement) => ddl::bind_ddl_statement(ctx, statement),
        Statement::Call(call) => call::bind_procedure_call(ctx, call),
        Statement::Explain { span, .. } => Err(AnalysisError::NotImplemented {
            message: "EXPLAIN EXPLAIN is not supported".into(),
            span: *span,
            hint: None,
        }),
        Statement::StartTransaction { span }
        | Statement::Commit { span }
        | Statement::Rollback { span } => {
            transaction::bind_transaction_control(ctx, *span);
            Ok(())
        }
        // The grammar's `explainable_statement` rule excludes session commands,
        // so EXPLAIN never wraps one; reject defensively rather than silently
        // binding a non-explainable statement.
        Statement::SessionSetValue { span, .. }
        | Statement::SessionSetTimeZone { span, .. }
        | Statement::SessionSetGraph { span, .. }
        | Statement::SessionReset { span, .. }
        | Statement::SessionClose { span } => Err(AnalysisError::NotImplemented {
            message: "EXPLAIN of a SESSION command is not supported".into(),
            span: *span,
            hint: None,
        }),
    }
}

fn statement_write_set(statement: &Statement) -> bool {
    match statement {
        Statement::Mutate(_) => true,
        Statement::Explain { inner, .. } => matches!(inner.as_ref(), Statement::Mutate(_)),
        _ => false,
    }
}

pub(crate) struct BindContext<'ctx> {
    scopes: BindingScopeTree,
    current: ScopeId,
    references: Vec<BindingUse>,
    expr_types: ExprTypeTable,
    expr_ids: ExprIdLookup,
    write_set: MutationWriteSet,
    registry: &'ctx dyn ProcedureRegistry,
    expr_depth: u32,
}

impl<'ctx> BindContext<'ctx> {
    fn new(root_span: SourceSpan, registry: &'ctx dyn ProcedureRegistry) -> Self {
        let scopes = BindingScopeTree::new(root_span);
        let current = scopes.root();
        Self {
            scopes,
            current,
            references: Vec::new(),
            expr_types: ExprTypeTable::default(),
            expr_ids: ExprIdLookup::default(),
            write_set: MutationWriteSet::default(),
            registry,
            expr_depth: 0,
        }
    }

    fn finish(
        self,
        stmt: Statement,
        category: StatementCategory,
        write_set: Option<MutationWriteSet>,
    ) -> AnalyzedStatement {
        AnalyzedStatement::new(
            stmt,
            self.scopes,
            self.references,
            self.expr_types,
            self.expr_ids,
            category,
            write_set,
        )
    }

    pub(crate) fn declare_strict_typed(
        &mut self,
        kind: BindingDeclKind,
        name: DbString,
        span: SourceSpan,
        ty: AnalyzedType,
    ) -> Result<BindingId, AnalysisError> {
        self.scopes
            .declare_strict_typed(self.current, kind, name, span, ty)
    }

    pub(crate) fn declare_or_reuse(
        &mut self,
        kind: BindingDeclKind,
        name: DbString,
        span: SourceSpan,
    ) -> Result<BindingId, AnalysisError> {
        self.declare_or_reuse_with_labels(kind, name, span, None)
    }

    pub(crate) fn declare_or_reuse_with_labels(
        &mut self,
        kind: BindingDeclKind,
        name: DbString,
        span: SourceSpan,
        labels: Option<crate::LabelExpr>,
    ) -> Result<BindingId, AnalysisError> {
        self.declare_or_reuse_with_labels_info(kind, name, span, labels)
            .map(|(binding, _)| binding)
    }

    pub(crate) fn declare_or_reuse_with_labels_info(
        &mut self,
        kind: BindingDeclKind,
        name: DbString,
        span: SourceSpan,
        labels: Option<crate::LabelExpr>,
    ) -> Result<(BindingId, bool), AnalysisError> {
        self.declare_or_reuse_with_labels_typed_info(
            kind,
            name,
            span,
            crate::analyze::binding::BindingDecl::default_type(kind),
            labels,
        )
    }

    pub(crate) fn declare_or_reuse_with_labels_typed_info(
        &mut self,
        kind: BindingDeclKind,
        name: DbString,
        span: SourceSpan,
        ty: AnalyzedType,
        labels: Option<crate::LabelExpr>,
    ) -> Result<(BindingId, bool), AnalysisError> {
        let (binding, reused) = self.scopes.declare_or_reuse_with_labels_typed(
            self.current,
            kind,
            name.clone(),
            span,
            ty,
            labels,
        )?;
        if reused {
            self.references.push(BindingUse {
                name,
                binding,
                span,
                kind: BindingUseKind::PatternReuse,
            });
        }
        Ok((binding, reused))
    }

    pub(crate) fn resolve(
        &mut self,
        name: DbString,
        span: SourceSpan,
        kind: BindingUseKind,
    ) -> Result<BindingId, AnalysisError> {
        let Some(binding) = self.scopes.resolve(self.current, name.clone()) else {
            return Err(AnalysisError::undefined_reference(name, span));
        };
        self.references.push(BindingUse {
            name,
            binding,
            span,
            kind,
        });
        Ok(binding)
    }

    pub(crate) fn element_kind(&self, binding: BindingId) -> ElementKind {
        let declaration = self
            .scopes
            .declaration(binding)
            .expect("resolved binding has declaration");
        ElementKind::from_decl_kind(declaration.kind())
    }

    pub(crate) fn record_write(
        &mut self,
        statement_index: usize,
        span: SourceSpan,
        kind: WriteKind,
    ) {
        self.write_set.push(WriteSetEntry {
            statement_index,
            span,
            kind,
        });
    }

    pub(crate) fn with_child_scope<T>(
        &mut self,
        kind: ScopeKind,
        span: SourceSpan,
        boundary: bool,
        f: impl FnOnce(&mut Self) -> Result<T, AnalysisError>,
    ) -> Result<T, AnalysisError> {
        let parent = self.current;
        let child = self.scopes.push_scope(parent, kind, span, boundary);
        self.current = child;
        let result = f(self);
        self.current = parent;
        result
    }

    /// Bind `f` inside a boundary subquery scope that imports ONLY the named
    /// outer bindings (ISO/IEC 39075:2024 ยง15.2 explicit variable scope, GP03).
    ///
    /// Each name is resolved against the current (parent) scope first โ€” an
    /// unknown name is an undefined-reference error โ€” and re-exposed in the
    /// child by id, so a body reference to an import resolves to the outer
    /// binding (and flows through `outer_binding_refs`). The child is a
    /// `boundary`, so any *unnamed* outer variable referenced in the body stops
    /// at the child and resolves to undefined. An empty `imports` slice
    /// (`CALL () { ... }`) yields a fully isolated scope. Duplicate import names
    /// are rejected by [`BindingScopeTree::import_binding`].
    pub(crate) fn with_imported_scope<T>(
        &mut self,
        imports: &[DbString],
        span: SourceSpan,
        f: impl FnOnce(&mut Self) -> Result<T, AnalysisError>,
    ) -> Result<T, AnalysisError> {
        let parent = self.current;
        // Resolve imports against the parent scope before entering the (boundary)
        // child โ€” the child cannot see the parent, so resolution must happen now.
        let mut resolved = Vec::with_capacity(imports.len());
        for name in imports {
            let binding = self
                .scopes
                .resolve(parent, name.clone())
                .ok_or_else(|| AnalysisError::undefined_reference(name.clone(), span))?;
            resolved.push((name.clone(), binding));
        }
        let child = self
            .scopes
            .push_scope(parent, ScopeKind::Subquery, span, true);
        for (name, binding) in resolved {
            self.scopes.import_binding(child, binding, name, span)?;
        }
        self.current = child;
        let result = f(self);
        self.current = parent;
        result
    }

    pub(crate) fn allocate_expr(&mut self, expr: &ValueExpr, ty: AnalyzedType) -> ExprId {
        let id = self.expr_types.push(ty);
        self.expr_ids.insert(expr, id);
        id
    }

    pub(crate) fn expr_type(&self, id: ExprId) -> &AnalyzedType {
        self.expr_types.get(id)
    }

    pub(crate) fn expr_id(&self, expr: &ValueExpr) -> Option<ExprId> {
        self.expr_ids.get(expr)
    }

    pub(crate) fn binding_type(&self, binding: BindingId) -> AnalyzedType {
        self.scopes
            .declaration(binding)
            .map(|decl| decl.ty().clone())
            .unwrap_or(AnalyzedType::Dynamic)
    }

    /// Enter a fresh projection scope and stay there for the rest of the
    /// pipeline.
    ///
    /// `boundary = false` matches ISO Feature `GA07` ("Ordering by discarded
    /// binding variables") for `RETURN`-style projections: pre-projection
    /// bindings stay reachable for downstream `ORDER BY` / `OFFSET` /
    /// `LIMIT`, and `RETURN *` keeps the entire input row visible.
    ///
    /// `boundary = true` matches the `WITH` continuation rule: pre-`WITH`
    /// bindings end at the boundary and only the WITH-projected aliases
    /// flow into the next clauses.
    pub(crate) fn enter_projection_scope(&mut self, span: SourceSpan, boundary: bool) {
        let child = self
            .scopes
            .push_scope(self.current, ScopeKind::Projection, span, boundary);
        self.current = child;
    }

    pub(crate) fn current_scope(&self) -> ScopeId {
        self.current
    }

    pub(crate) fn current_scope_has_visible_bindings(&self) -> bool {
        self.scopes.has_visible_bindings(self.current)
    }

    pub(crate) fn set_scope(&mut self, scope: ScopeId) {
        self.current = scope;
    }

    pub(crate) fn registry(&self) -> &'ctx dyn ProcedureRegistry {
        self.registry
    }

    pub(crate) fn with_expr_depth<T>(
        &mut self,
        f: impl FnOnce(&mut Self) -> Result<T, AnalysisError>,
    ) -> Result<T, AnalysisError> {
        let next = self.expr_depth.saturating_add(1);
        if next > ANALYZER_MAX_DEPTH {
            return Err(AnalysisError::RecursionLimitExceeded { depth: next });
        }
        self.expr_depth = next;
        let result = f(self);
        self.expr_depth = self.expr_depth.saturating_sub(1);
        result
    }

    pub(crate) const fn at_expr_root(&self) -> bool {
        self.expr_depth == 0
    }
}