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
//! ValueRowContext: Expression evaluation context for streaming rows
//!
//! Provides expression evaluation context for Vec<Value> rows.
//! Runtime uses SlotId-based access via SlotLayout; column-name lookup
//! at runtime is prohibited — all Variable references are resolved through
//! the layout.

use crate::executor::expression::evaluator::traits::ExpressionContext;
use crate::executor::expression::ExpressionError;
use crate::executor::streaming::slot::{SlotId, SlotLayout};
use crate::executor::streaming::subquery::{EvalEnv, SubqueryExecutor};
use linkrs_core::Value;
use std::collections::HashMap;
use std::sync::Arc;

use super::parameters::{ParameterFrame, ParameterSchema};

/// Row context for expression evaluation with Value types
///
/// Every context carries an [`Arc<SlotLayout>`] so that `get_variable(name)`
/// resolves through `layout.slot_id(name)` → `row[slot]` without any
/// separate name-to-index map or runtime fallback.
pub struct ValueRowContext {
    /// Column values (as Values, no conversion needed)
    row: Vec<Value>,
    /// Extra variables for expression evaluation
    variables: HashMap<String, Value>,
    /// Slot layout — always set; drives all variable resolution
    layout: Arc<SlotLayout>,
    /// Parameter name→value map (shared via Arc across rows).
    parameters: Option<Arc<HashMap<String, Value>>>,
    /// Session variable name→value snapshot (shared via Arc across rows).
    session_variables: Option<Arc<HashMap<String, Value>>>,
    /// Expression-level subquery executor of the hosting operator.
    subquery_executor: Option<Arc<SubqueryExecutor>>,
    /// Sequence catalog manager for `curr_val` / `next_val`.
    sequence_manager: Option<Arc<linkrs_core::metadata::SequenceManager>>,
}

impl ValueRowContext {
    /// Create a new context from a row and slot layout.
    pub fn new(row: Vec<Value>, layout: Arc<SlotLayout>) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: None,
            session_variables: None,
            subquery_executor: None,
            sequence_manager: None,
        }
    }

    /// Create a new context with parameter values for `@name` resolution.
    pub fn with_parameters(
        row: Vec<Value>,
        layout: Arc<SlotLayout>,
        parameters: Arc<HashMap<String, Value>>,
    ) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: Some(parameters),
            session_variables: None,
            subquery_executor: None,
            sequence_manager: None,
        }
    }

    /// Create a new context from a full evaluation environment.
    pub fn with_env(row: Vec<Value>, layout: Arc<SlotLayout>, env: &EvalEnv) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: env.params.clone(),
            session_variables: env.session_variables.clone(),
            subquery_executor: env.subquery_executor.clone(),
            sequence_manager: env.sequence_manager.clone(),
        }
    }

    /// Build a name→value map from schema and frame.
    pub fn build_parameter_map(
        schema: &ParameterSchema,
        frame: &ParameterFrame,
    ) -> HashMap<String, Value> {
        schema
            .params
            .iter()
            .filter_map(|p| frame.get(p.slot).map(|v| (p.name.clone(), v.clone())))
            .collect()
    }

    /// Create a new context by building a layout from column names.
    ///
    /// This is a convenience for sites that only have column-name strings
    /// (e.g. helper functions).  The layout is
    /// created once and reused for all subsequent `get_variable()` calls
    /// so there is never a name-map fallback at runtime.
    pub fn from_names(row: Vec<Value>, col_names: Vec<String>) -> Self {
        let layout = Arc::new(SlotLayout::from_names(&col_names));
        Self::new(row, layout)
    }
}

impl ExpressionContext for ValueRowContext {
    fn get_variable(&self, name: &str) -> Option<Value> {
        // First check explicit variables (e.g. bindings from Apply)
        if let Some(value) = self.variables.get(name) {
            return Some(value.clone());
        }
        // Slot-based access via layout — the ONLY resolution path at runtime.
        self.layout
            .slot_id(name)
            .and_then(|slot_id| self.row.get(slot_id).cloned())
    }

    fn get_variable_by_slot(&self, slot: SlotId) -> Option<Value> {
        self.row.get(slot).cloned()
    }

    fn set_variable(&mut self, name: String, value: Value) {
        self.variables.insert(name, value);
    }

    fn get_parameter(&self, name: &str) -> Option<Value> {
        self.parameters.as_ref().and_then(|p| p.get(name).cloned())
    }

    fn get_session_variable(&self, name: &str) -> Result<Value, ExpressionError> {
        self.session_variables
            .as_ref()
            .and_then(|vars| vars.get(name).cloned())
            .ok_or_else(|| {
                ExpressionError::type_error(format!("Session variable `{}` is not defined", name))
            })
    }

    fn get_sequence_manager(&self) -> Option<Arc<linkrs_core::metadata::SequenceManager>> {
        self.sequence_manager.clone()
    }

    fn execute_exists(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<bool, ExpressionError> {
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_exists(body, self.layout.clone(), self.row.clone())
    }

    fn execute_scalar_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<Value, ExpressionError> {
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error(
                    "Scalar subquery execution not supported in this context",
                )
            })?
            .execute_scalar(body, self.layout.clone(), self.row.clone())
    }

    fn contains_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
        value: &Value,
    ) -> Result<Value, ExpressionError> {
        if value.is_null() {
            return Ok(Value::Bool(false));
        }
        let found = self
            .subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_contains(body, self.layout.clone(), self.row.clone(), value)?;
        Ok(Value::Bool(found))
    }
}

/// A light-weight expression context that borrows the row data instead
/// of cloning it.  Use this in hot paths (e.g. Filter) where the
/// expression only reads from the row and does not take ownership.
///
/// Individual values returned by `get_variable` are still cloned (that
/// is inherent in the `ExpressionContext` trait), but the `Vec<Value>`
/// wrapper itself is not — saving one allocation per row.
pub struct BorrowedRowContext<'a> {
    row: &'a [Value],
    variables: HashMap<String, Value>,
    layout: Arc<SlotLayout>,
    parameters: Option<Arc<HashMap<String, Value>>>,
    /// Session variable name→value snapshot (shared via Arc across rows).
    session_variables: Option<Arc<HashMap<String, Value>>>,
    /// Expression-level subquery executor of the hosting operator.
    subquery_executor: Option<Arc<SubqueryExecutor>>,
    /// Sequence catalog manager for `curr_val` / `next_val`.
    sequence_manager: Option<Arc<linkrs_core::metadata::SequenceManager>>,
}

impl<'a> BorrowedRowContext<'a> {
    pub fn new(row: &'a [Value], layout: Arc<SlotLayout>) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: None,
            session_variables: None,
            subquery_executor: None,
            sequence_manager: None,
        }
    }

    /// Create with parameter values for `@name` resolution.
    pub fn with_parameters(
        row: &'a [Value],
        layout: Arc<SlotLayout>,
        parameters: Arc<HashMap<String, Value>>,
    ) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: Some(parameters),
            session_variables: None,
            subquery_executor: None,
            sequence_manager: None,
        }
    }

    /// Create from a full evaluation environment (parameters + subquery
    /// executor).
    pub fn with_env(row: &'a [Value], layout: Arc<SlotLayout>, env: &EvalEnv) -> Self {
        Self {
            row,
            variables: HashMap::new(),
            layout,
            parameters: env.params.clone(),
            session_variables: env.session_variables.clone(),
            subquery_executor: env.subquery_executor.clone(),
            sequence_manager: env.sequence_manager.clone(),
        }
    }

    /// Update the row reference and clear per-row variables.
    ///
    /// Call this in a hot loop to reuse the same context across many rows,
    /// avoiding repeated `Arc::clone` on the slot layout.
    pub fn set_row(&mut self, row: &'a [Value]) {
        self.row = row;
        self.variables.clear();
    }
}

impl ExpressionContext for BorrowedRowContext<'_> {
    fn get_variable(&self, name: &str) -> Option<Value> {
        if let Some(value) = self.variables.get(name) {
            return Some(value.clone());
        }
        self.layout
            .slot_id(name)
            .and_then(|slot_id| self.row.get(slot_id).cloned())
    }

    fn get_variable_by_slot(&self, slot: SlotId) -> Option<Value> {
        self.row.get(slot).cloned()
    }

    fn set_variable(&mut self, name: String, value: Value) {
        self.variables.insert(name, value);
    }

    fn get_parameter(&self, name: &str) -> Option<Value> {
        self.parameters.as_ref().and_then(|p| p.get(name).cloned())
    }

    fn get_session_variable(&self, name: &str) -> Result<Value, ExpressionError> {
        self.session_variables
            .as_ref()
            .and_then(|vars| vars.get(name).cloned())
            .ok_or_else(|| {
                ExpressionError::type_error(format!("Session variable `{}` is not defined", name))
            })
    }

    fn get_sequence_manager(&self) -> Option<Arc<linkrs_core::metadata::SequenceManager>> {
        self.sequence_manager.clone()
    }

    fn execute_exists(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<bool, ExpressionError> {
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_exists(body, self.layout.clone(), self.row.to_vec())
    }

    fn execute_scalar_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<Value, ExpressionError> {
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error(
                    "Scalar subquery execution not supported in this context",
                )
            })?
            .execute_scalar(body, self.layout.clone(), self.row.to_vec())
    }

    fn contains_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
        value: &Value,
    ) -> Result<Value, ExpressionError> {
        if value.is_null() {
            return Ok(Value::Bool(false));
        }
        let found = self
            .subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_contains(body, self.layout.clone(), self.row.to_vec(), value)?;
        Ok(Value::Bool(found))
    }
}

/// A context that presents two disjoint row halves as a single combined row
/// without allocating a combined `Vec<Value>`.
///
/// Slots `0..split` map to the left slice; slots `split..` map to the right
/// slice.  Use this in hash join condition evaluation to avoid cloning
/// every column before the condition is checked.
pub struct SplitRowContext<'a> {
    left: &'a [Value],
    right: &'a [Value],
    split: usize,
    variables: HashMap<String, Value>,
    layout: Arc<SlotLayout>,
    parameters: Option<Arc<HashMap<String, Value>>>,
    /// Session variable name→value snapshot (shared via Arc across rows).
    session_variables: Option<Arc<HashMap<String, Value>>>,
    /// Expression-level subquery executor of the hosting operator.
    subquery_executor: Option<Arc<SubqueryExecutor>>,
    /// Sequence catalog manager for `curr_val` / `next_val`.
    sequence_manager: Option<Arc<linkrs_core::metadata::SequenceManager>>,
}

impl<'a> SplitRowContext<'a> {
    pub fn new(left: &'a [Value], right: &'a [Value], layout: Arc<SlotLayout>) -> Self {
        let split = left.len();
        Self {
            left,
            right,
            split,
            variables: HashMap::new(),
            layout,
            parameters: None,
            session_variables: None,
            subquery_executor: None,
            sequence_manager: None,
        }
    }

    /// Create from a full evaluation environment (parameters + subquery
    /// executor).
    pub fn with_env(
        left: &'a [Value],
        right: &'a [Value],
        layout: Arc<SlotLayout>,
        env: &EvalEnv,
    ) -> Self {
        let split = left.len();
        Self {
            left,
            right,
            split,
            variables: HashMap::new(),
            layout,
            parameters: env.params.clone(),
            session_variables: env.session_variables.clone(),
            subquery_executor: env.subquery_executor.clone(),
            sequence_manager: env.sequence_manager.clone(),
        }
    }
}

impl ExpressionContext for SplitRowContext<'_> {
    fn get_variable(&self, name: &str) -> Option<Value> {
        if let Some(value) = self.variables.get(name) {
            return Some(value.clone());
        }
        self.layout
            .slot_id(name)
            .and_then(|slot_id| self.get_variable_by_slot(slot_id))
    }

    fn get_variable_by_slot(&self, slot: SlotId) -> Option<Value> {
        if slot < self.split {
            self.left.get(slot).cloned()
        } else {
            self.right.get(slot - self.split).cloned()
        }
    }

    fn set_variable(&mut self, name: String, value: Value) {
        self.variables.insert(name, value);
    }

    fn get_parameter(&self, name: &str) -> Option<Value> {
        self.parameters.as_ref().and_then(|p| p.get(name).cloned())
    }

    fn get_session_variable(&self, name: &str) -> Result<Value, ExpressionError> {
        self.session_variables
            .as_ref()
            .and_then(|vars| vars.get(name).cloned())
            .ok_or_else(|| {
                ExpressionError::type_error(format!("Session variable `{}` is not defined", name))
            })
    }

    fn get_sequence_manager(&self) -> Option<Arc<linkrs_core::metadata::SequenceManager>> {
        self.sequence_manager.clone()
    }

    fn execute_exists(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<bool, ExpressionError> {
        let mut row = self.left.to_vec();
        row.extend_from_slice(self.right);
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_exists(body, self.layout.clone(), row)
    }

    fn execute_scalar_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
    ) -> Result<Value, ExpressionError> {
        let mut row = self.left.to_vec();
        row.extend_from_slice(self.right);
        self.subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error(
                    "Scalar subquery execution not supported in this context",
                )
            })?
            .execute_scalar(body, self.layout.clone(), row)
    }

    fn contains_subquery(
        &mut self,
        body: &linkrs_core::types::expr::SubqueryBody,
        value: &Value,
    ) -> Result<Value, ExpressionError> {
        if value.is_null() {
            return Ok(Value::Bool(false));
        }
        let mut row = self.left.to_vec();
        row.extend_from_slice(self.right);
        let found = self
            .subquery_executor
            .as_ref()
            .ok_or_else(|| {
                ExpressionError::type_error("Subquery execution not supported in this context")
            })?
            .execute_contains(body, self.layout.clone(), row, value)?;
        Ok(Value::Bool(found))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_context_creation() {
        let row = vec![Value::Int(1), Value::string("test"), Value::Bool(true)];
        let col_names = vec!["id".to_string(), "name".to_string(), "active".to_string()];
        let layout = Arc::new(SlotLayout::from_names(&col_names));

        let context = ValueRowContext::new(row, layout);

        assert_eq!(context.get_variable("id"), Some(Value::Int(1)));
        assert_eq!(context.get_variable("name"), Some(Value::string("test")));
        assert_eq!(context.get_variable("active"), Some(Value::Bool(true)));
    }

    #[test]
    fn test_variable_storage() {
        let row = vec![Value::Int(1)];
        let col_names = vec!["id".to_string()];
        let layout = Arc::new(SlotLayout::from_names(&col_names));
        let mut context = ValueRowContext::new(row, layout);

        context.set_variable("var1".into(), Value::string("hello"));
        context.set_variable("var2".into(), Value::Int(42));

        assert_eq!(context.get_variable("var1"), Some(Value::string("hello")));
        assert_eq!(context.get_variable("var2"), Some(Value::Int(42)));
    }

    #[test]
    fn test_missing_column() {
        let row = vec![Value::Int(1), Value::string("test")];
        let col_names = vec!["id".to_string(), "name".to_string()];
        let layout = Arc::new(SlotLayout::from_names(&col_names));

        let context = ValueRowContext::new(row, layout);

        assert_eq!(context.get_variable("nonexistent"), None);
        assert_eq!(context.get_variable("var_not_set"), None);
    }
}