vibesql-executor 0.2.0

Query execution engine for vibesql SQL database
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
//! Execution Context
//!
//! This module provides the `ExecutionContext` struct that bundles all the context
//! needed for query execution, eliminating the need for multiple evaluator constructor
//! variants throughout the codebase.

use std::collections::HashMap;

use crate::{
    evaluator::CombinedExpressionEvaluator, procedural, schema::CombinedSchema,
    select::cte::CteResult,
};

/// Execution context that bundles all information needed for query execution.
///
/// This struct consolidates the various optional contexts (outer row, procedural,
/// CTE, windows) that were previously passed separately, reducing the number of
/// evaluator constructor variants needed.
///
/// # Example
///
/// ```text
/// let ctx = ExecutionContext::new(schema, database)
///     .with_cte_context(cte_results)
///     .with_outer_context(outer_row, outer_schema);
///
/// let evaluator = ctx.create_evaluator();
/// ```
pub struct ExecutionContext<'a> {
    /// The combined schema for column resolution
    pub schema: &'a CombinedSchema,
    /// Database reference for table access and subqueries
    pub database: &'a vibesql_storage::Database,
    /// Optional outer row for correlated subqueries
    pub outer_row: Option<&'a vibesql_storage::Row>,
    /// Optional outer schema for correlated subqueries
    pub outer_schema: Option<&'a CombinedSchema>,
    /// Optional all outer rows for outer-correlated aggregates (issue #4930)
    /// When an aggregate in a scalar subquery references only outer columns,
    /// it should aggregate over ALL outer rows, not just the current one.
    pub outer_rows: Option<&'a [vibesql_storage::Row]>,
    /// Optional procedural context for stored procedures/functions
    pub procedural_context: Option<&'a procedural::ExecutionContext>,
    /// Optional trigger context for OLD/NEW pseudo-variable resolution inside trigger bodies
    /// (e.g. UPDATE…FROM in a trigger body referencing NEW.x / OLD.x — issue #5082)
    pub trigger_context: Option<&'a crate::trigger_execution::TriggerContext<'a>>,
    /// Optional CTE context for WITH clause results
    pub cte_context: Option<&'a HashMap<String, CteResult>>,
    /// Optional window function mapping
    pub window_mapping: Option<&'a HashMap<crate::select::WindowFunctionKey, usize>>,
}

impl<'a> ExecutionContext<'a> {
    /// Create a new execution context with required parameters.
    ///
    /// # Arguments
    /// * `schema` - The combined schema for column resolution
    /// * `database` - Database reference for table access
    pub fn new(schema: &'a CombinedSchema, database: &'a vibesql_storage::Database) -> Self {
        Self {
            schema,
            database,
            outer_row: None,
            outer_schema: None,
            outer_rows: None,
            procedural_context: None,
            trigger_context: None,
            cte_context: None,
            window_mapping: None,
        }
    }

    /// Add outer context for correlated subqueries.
    ///
    /// # Arguments
    /// * `outer_row` - The current row from the outer query
    /// * `outer_schema` - The schema of the outer query
    #[must_use]
    pub fn with_outer_context(
        mut self,
        outer_row: &'a vibesql_storage::Row,
        outer_schema: &'a CombinedSchema,
    ) -> Self {
        self.outer_row = Some(outer_row);
        self.outer_schema = Some(outer_schema);
        self
    }

    /// Add all outer rows for outer-correlated aggregates (issue #4930).
    ///
    /// When an aggregate function in a scalar subquery references only outer columns,
    /// it should aggregate over ALL outer rows, not just the current one. This enables
    /// queries like `SELECT (SELECT string_agg(a1,'x') FROM t2) FROM t1` to work correctly.
    ///
    /// # Arguments
    /// * `outer_rows` - All rows from the outer query
    #[must_use]
    pub fn with_outer_rows(mut self, outer_rows: &'a [vibesql_storage::Row]) -> Self {
        self.outer_rows = Some(outer_rows);
        self
    }

    /// Add procedural context for stored procedures/functions.
    ///
    /// # Arguments
    /// * `proc_ctx` - The procedural execution context
    #[must_use]
    pub fn with_procedural_context(mut self, proc_ctx: &'a procedural::ExecutionContext) -> Self {
        self.procedural_context = Some(proc_ctx);
        self
    }

    /// Add trigger context for OLD/NEW pseudo-variable resolution.
    ///
    /// Used by the synthetic SELECT inside `UPDATE … FROM …` when running inside
    /// a trigger body so that `OLD.col` / `NEW.col` resolve against the firing
    /// row (issue #5082).
    ///
    /// # Arguments
    /// * `trigger_ctx` - The trigger execution context
    #[must_use]
    pub fn with_trigger_context(
        mut self,
        trigger_ctx: &'a crate::trigger_execution::TriggerContext<'a>,
    ) -> Self {
        self.trigger_context = Some(trigger_ctx);
        self
    }

    /// Add CTE context for WITH clause results.
    ///
    /// # Arguments
    /// * `cte_ctx` - Map of CTE names to their results
    #[must_use]
    pub fn with_cte_context(mut self, cte_ctx: &'a HashMap<String, CteResult>) -> Self {
        self.cte_context = Some(cte_ctx);
        self
    }

    /// Add window function mapping.
    ///
    /// # Arguments
    /// * `window_mapping` - Map of window function keys to result column indices
    #[must_use]
    pub fn with_window_mapping(
        mut self,
        window_mapping: &'a HashMap<crate::select::WindowFunctionKey, usize>,
    ) -> Self {
        self.window_mapping = Some(window_mapping);
        self
    }

    /// Create a CombinedExpressionEvaluator with all the context from this struct.
    ///
    /// This replaces the many constructor variants like:
    /// - `with_database()`
    /// - `with_database_and_cte()`
    /// - `with_database_and_outer_context()`
    /// - `with_database_and_outer_context_and_cte()`
    /// - `with_database_and_procedural_context()`
    /// - `with_database_and_procedural_context_and_cte()`
    /// - `with_database_and_windows()`
    /// - `with_database_and_windows_and_cte()`
    ///
    /// By using a builder pattern, we consolidate all 8+ variants into a single method.
    /// If outer_rows is set, it will be propagated to the evaluator for outer-correlated
    /// aggregates (issue #4930).
    pub fn create_evaluator(&self) -> CombinedExpressionEvaluator<'a> {
        // Trigger context takes priority — used by the synthetic SELECT inside
        // UPDATE…FROM running inside a trigger body so OLD/NEW resolve correctly
        // (issue #5082). Trigger context is mutually exclusive with procedural
        // context (a trigger body cannot run inside a stored procedure body), but
        // we still allow it to compose with outer_rows, set below.
        if let Some(trigger_ctx) = self.trigger_context {
            let mut evaluator =
                CombinedExpressionEvaluator::with_database_and_trigger_context(
                    self.schema,
                    self.database,
                    trigger_ctx,
                );
            if let Some(outer_rows) = self.outer_rows {
                evaluator.set_outer_rows(outer_rows);
            }
            return evaluator;
        }

        // Use the most complete constructor and set optional fields
        // We match on the combination of optional fields to call the right constructor
        // This is temporary until we refactor CombinedExpressionEvaluator itself
        let mut evaluator = match (
            self.outer_row,
            self.outer_schema,
            self.procedural_context,
            self.cte_context,
            self.window_mapping,
        ) {
            // With outer context and CTE
            (Some(outer_row), Some(outer_schema), None, Some(cte_ctx), None) => {
                CombinedExpressionEvaluator::with_database_and_outer_context_and_cte(
                    self.schema,
                    self.database,
                    outer_row,
                    outer_schema,
                    cte_ctx,
                )
            }
            // With outer context only
            (Some(outer_row), Some(outer_schema), None, None, None) => {
                CombinedExpressionEvaluator::with_database_and_outer_context(
                    self.schema,
                    self.database,
                    outer_row,
                    outer_schema,
                )
            }
            // With procedural context and CTE
            (None, None, Some(proc_ctx), Some(cte_ctx), None) => {
                CombinedExpressionEvaluator::with_database_and_procedural_context_and_cte(
                    self.schema,
                    self.database,
                    proc_ctx,
                    cte_ctx,
                )
            }
            // With procedural context only
            (None, None, Some(proc_ctx), None, None) => {
                CombinedExpressionEvaluator::with_database_and_procedural_context(
                    self.schema,
                    self.database,
                    proc_ctx,
                )
            }
            // With CTE context only
            (None, None, None, Some(cte_ctx), None) => {
                CombinedExpressionEvaluator::with_database_and_cte(
                    self.schema,
                    self.database,
                    cte_ctx,
                )
            }
            // With window mapping and CTE
            (None, None, None, Some(cte_ctx), Some(window_map)) => {
                CombinedExpressionEvaluator::with_database_and_windows_and_cte(
                    self.schema,
                    self.database,
                    window_map,
                    cte_ctx,
                )
            }
            // With window mapping only
            (None, None, None, None, Some(window_map)) => {
                CombinedExpressionEvaluator::with_database_and_windows(
                    self.schema,
                    self.database,
                    window_map,
                )
            }
            // Base case: just database
            (None, None, None, None, None) => {
                CombinedExpressionEvaluator::with_database(self.schema, self.database)
            }
            // Unsupported combinations fall back to base
            // Note: outer + procedural is not a valid combination in current usage
            _ => CombinedExpressionEvaluator::with_database(self.schema, self.database),
        };

        // Set outer_rows if available (for outer-correlated aggregates, issue #4930)
        if let Some(outer_rows) = self.outer_rows {
            evaluator.set_outer_rows(outer_rows);
        }

        evaluator
    }

    /// Check if this context has outer context (for correlated subqueries).
    #[inline]
    pub fn has_outer_context(&self) -> bool {
        self.outer_row.is_some() && self.outer_schema.is_some()
    }

    /// Check if this context has CTE context.
    #[inline]
    pub fn has_cte_context(&self) -> bool {
        self.cte_context.is_some()
    }

    /// Check if this context has procedural context.
    #[inline]
    pub fn has_procedural_context(&self) -> bool {
        self.procedural_context.is_some()
    }
}

#[cfg(test)]
mod tests {
    use vibesql_catalog::TableSchema;

    use super::*;
    use crate::schema::CombinedSchema;

    /// Builder for creating ExecutionContext from SelectExecutor fields.
    ///
    /// This helper extracts common context-building logic that's repeated
    /// across multiple execution methods.
    struct ExecutionContextBuilder<'a> {
        schema: &'a CombinedSchema,
        database: &'a vibesql_storage::Database,
        outer_row: Option<&'a vibesql_storage::Row>,
        outer_schema: Option<&'a CombinedSchema>,
        procedural_context: Option<&'a procedural::ExecutionContext>,
        cte_context: Option<&'a HashMap<String, CteResult>>,
        executor_cte_context: Option<&'a HashMap<String, CteResult>>,
    }

    impl<'a> ExecutionContextBuilder<'a> {
        /// Create a new builder with required parameters.
        fn new(schema: &'a CombinedSchema, database: &'a vibesql_storage::Database) -> Self {
            Self {
                schema,
                database,
                outer_row: None,
                outer_schema: None,
                procedural_context: None,
                cte_context: None,
                executor_cte_context: None,
            }
        }

        /// Set CTE context from query-level CTEs.
        #[must_use]
        fn cte_from_query(mut self, cte_results: &'a HashMap<String, CteResult>) -> Self {
            if !cte_results.is_empty() {
                self.cte_context = Some(cte_results);
            }
            self
        }

        /// Build the ExecutionContext.
        ///
        /// CTE context priority: query-level CTEs take precedence over executor-level.
        fn build(self) -> ExecutionContext<'a> {
            let mut ctx = ExecutionContext::new(self.schema, self.database);

            // Set outer context if both row and schema are present
            if let (Some(outer_row), Some(outer_schema)) = (self.outer_row, self.outer_schema) {
                ctx = ctx.with_outer_context(outer_row, outer_schema);
            }

            // Set procedural context if present
            if let Some(proc_ctx) = self.procedural_context {
                ctx = ctx.with_procedural_context(proc_ctx);
            }

            // Set CTE context (query-level takes precedence)
            if let Some(cte_ctx) = self.cte_context {
                ctx = ctx.with_cte_context(cte_ctx);
            } else if let Some(executor_cte) = self.executor_cte_context {
                ctx = ctx.with_cte_context(executor_cte);
            }

            ctx
        }
    }

    fn create_test_schema() -> CombinedSchema {
        let table_schema = TableSchema::new("test".to_string(), vec![]);
        CombinedSchema::from_table("test".to_string(), table_schema)
    }

    #[test]
    fn test_execution_context_builder_basic() {
        let schema = create_test_schema();
        let database = vibesql_storage::Database::new();

        let ctx = ExecutionContext::new(&schema, &database);

        assert!(!ctx.has_outer_context());
        assert!(!ctx.has_cte_context());
        assert!(!ctx.has_procedural_context());
    }

    #[test]
    fn test_execution_context_with_cte() {
        let schema = create_test_schema();
        let database = vibesql_storage::Database::new();
        let cte_results: HashMap<String, CteResult> = HashMap::new();

        let ctx = ExecutionContext::new(&schema, &database).with_cte_context(&cte_results);

        assert!(ctx.has_cte_context());
    }

    #[test]
    fn test_execution_context_builder_chain() {
        let schema = create_test_schema();
        let database = vibesql_storage::Database::new();
        let cte_results: HashMap<String, CteResult> = HashMap::new();

        let ctx =
            ExecutionContextBuilder::new(&schema, &database).cte_from_query(&cte_results).build();

        // Empty CTE map should not set context
        assert!(!ctx.has_cte_context());
    }
}