use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use crate::sync_plan::{ ReplicationEmbedder, StringInterner, Symbol, expression::{ BinaryOperator, CaseWhenExpression, CastType, LiteralExpression, ScalarFunction, SqlExpression, TableValuedFunction, UnaryOperator, WhenThen, }, plan::{ RowProjection, StreamDataSource, StreamParameterIndexLookupCreator, TableProcessor, TableProcessorData, TableProcessorExpression, }, }; /// A prepared group of processors, typically all processors matching a source table. /// /// Groups are built by callers, who are responsible for only including processors that apply to the /// rows evaluated with the group. /// /// In each group, processors can share decoded values. For example, if one stream has a /// `SELECT * FROM users WHERE id = ...` and another has `SELECT id FROM users WHERE ...`, we'd /// share a slot for the decoded `users.id` column instead of extracing them multiple times. /// /// By assignings slots to inputs, we can efficiently skip past unused fields in source data and can /// lookup values very efficiently. #[derive(Debug)] pub struct ProcessorGroup { /// Interned column names used in inputs and outputs of [Self::processors]. pub interner: StringInterner, pub processors: Vec>, /// The maximum amount of [Slot::Input] slots used by a processor. /// /// Input slots are readonly while evaluating instructions, and can be shared by all processors /// in this group. pub num_input_slots: u32, /// The maximum amount of [Slot::Internal] slots used by any processor. /// /// Internal slots are cleared between processors, but we allocate a shared buffer ahead of /// time. pub num_internal_slots: u32, /// The maximum amount of parameters of any data or parameter source in this group, where the /// outputs of parameter sources count as parameters too. /// /// This is used to allocate a shared buffer for parameters ahead of time. pub max_parameters: usize, /// The maximum amount of table-valued functions in any processor of this group. pub max_table_valued_functions: usize, /// For each column name used as input by any processor, the input slot to store it in when /// decoding a value. pub input_columns: HashMap, /// The input slot in which to write the schema name of the replicated row. pub input_schema_name: Option, /// The input slot in which to write the full table name of the replicated row. pub input_table_name: Option, /// Input slots in which to write prefixes of the table name. pub inputs_table_suffix: Vec, /// Whether any processor in this group has a `*` projection. pub has_star_projection: bool, } /// A reference to a value used while evaluating a [ProcessorGroup]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Slot { /// A value derived from the source row before evaluating processors, like a column value or the /// name of the table. Input(u32), /// An intermediate value written by an instruction of the processor being evaluated. Internal(u32), } #[derive(Debug)] pub enum ProcessedGroupMember { Data(ProcessedDataSource), Parameter(ProcessedParameterSource), } #[derive(Debug)] pub struct ProcessedDataSource { pub id: E::BucketId, pub projection: PreparedProjection, /// The name of the output table for evaluated rows. /// /// When [None], the name of the table being evaluated should be used instead. pub output_table_name: Option, pub common: CommonProcessedSource, } /// A non-`*` output column of a [ProcessedDataSource]. #[derive(Debug)] pub struct PreparedColumn { pub alias: Symbol, /// The slot storing the value of this column once all instructions have run. pub slot: Slot, } /// A [RowProjection] with an index of shadowed source row fields, used to emit every output /// column at most once. /// /// Since explicit columns have unique aliases (duplicates are removed when deserializing the /// plan), a column can only be shadowed by a field of the /// source row or vice-versa: /// /// 1. Fields of the source row with the same name as a column after the `*` are not emitted. /// These are known statically and stored in [Self::after_aliases]. /// 2. Columns before the `*` are not emitted if the source row has a field with the same name, /// which is checked during evaluation. #[derive(Debug)] pub struct PreparedProjection { pub columns: RowProjection, /// Aliases of columns after the `*`, shadowing fields of the source row with the same name. pub after_aliases: HashMap, } impl PreparedProjection { pub fn new(columns: RowProjection) -> Self { debug_assert!( { let explicit = columns.before().iter().chain(columns.after()); let mut seen = HashSet::new(); explicit.into_iter().all(|c| seen.insert(c.alias)) }, "explicit columns of a projection must have unique aliases" ); Self { after_aliases: columns.after().iter().map(|c| (c.alias, c.slot)).collect(), columns, } } } #[derive(Debug)] pub struct ProcessedParameterSource { pub id: E::ParameterId, /// The slots storing outputs to persist in the lookup. pub outputs: Vec, pub common: CommonProcessedSource, } #[derive(Debug)] pub struct CommonProcessedSource { /// Instructions to run for each row. /// /// After running all instructions without an [EvaluatorInstruction::CheckFilter] failing, the /// slots referenced by [Self::parameters] and source-specific outputs contain the values for a /// match. Since [EvaluatorInstruction::ExpandTableValuedFunction] runs the remaining /// instructions once per row of the function, a source row can have multiple matches. pub instructions: Vec, /// The slots storing bucket parameters (for data sources) or lookup inputs (for parameter /// sources). pub parameters: Vec, } /// An instruction to evaluate this processor. /// /// We use instructions instead of direct [SqlExpression]s to save memory: Instead of evaluating an /// AST (which requires allocating a slice representing inputs for each function call), we assign /// [Slot]s for inputs once. This allows evaluator to allocate a sufficiently large buffer ahead of /// time. #[derive(Debug)] pub enum EvaluatorInstruction { /// Evaluate a scalar operation, writing its output into the given slot. Evaluate { op: ScalarOperation, output_slot: Slot, }, /// Used to implement if-else chains for `CASE WHEN` expressions. /// /// For example, the expression `CASE a WHEN b THEN 'foo' ELSE 'bar' END` (where `a` and `b` /// are columns stored in input slots `$a` and `$b`) is represented by this sequence of /// instructions, with `s0` storing the result: /// /// 1. `Evaluate($a = $b, output_slot: s1)` /// 2. `JumpForward(when_falsy: s1, skip: 3)` /// 3. `Evaluate('foo', output_slot: s2)` /// 4. `Evaluate(Copy(s2), output_slot: s0)` /// 5. `JumpForward(skip: 2)` /// 6. `Evaluate('bar', output_slot: s3)` /// 7. `Evaluate(Copy(s3), output_slot: s0)` JumpForward { /// The amount of instructions, after this one, to skip. skip: usize, /// When set, only jump if memory at the slot contains a falsy value. when_falsy: Option, }, /// Check that the given slot contains a truthy value, and stop processing the match otherwise. CheckFilter(Slot), /// Evaluates a table-valued function, running the remaining instructions once for each of its /// rows. ExpandTableValuedFunction(ProcessedTableValuedFunction), } /// A single, non-nested step of evaluating a [SqlExpression], with operands read from slots. #[derive(Debug)] pub enum ScalarOperation { Copy(Slot), Literal(LiteralExpression), Unary { operator: UnaryOperator, operand: Slot, }, Binary { left: Slot, operator: BinaryOperator, right: Slot, }, Between { value: Slot, low: Slot, high: Slot, }, ScalarIn { target: Slot, r#in: Vec, }, Cast { operand: Slot, cast_as: CastType, }, FunctionCall { function: ScalarFunction, inputs: Vec, }, } #[derive(Debug)] pub struct ProcessedTableValuedFunction { pub function: TableValuedFunction, pub inputs: Vec, pub outputs: Vec, } #[derive(Debug)] pub struct TableSuffixInput { pub prefix_length: usize, pub slot: Slot, } impl Default for ProcessorGroup { // Not derived, since that would require E: Default. fn default() -> Self { Self { processors: Vec::new(), interner: StringInterner::default(), num_input_slots: 0, num_internal_slots: 0, max_parameters: 0, max_table_valued_functions: 0, input_columns: HashMap::new(), input_schema_name: None, input_table_name: None, inputs_table_suffix: Vec::new(), has_star_projection: false, } } } impl ProcessorGroup { pub fn include_data(&mut self, id: E::BucketId, source: &StreamDataSource) { let mut translator = ProcessorTranslator::new(self, &source.processor); let parameters = translator.translate_common(); let projection = PreparedProjection::new(source.projection.map(|column| { PreparedColumn { alias: translator .group .interner .get_or_intern(column.alias.as_str()), slot: translator.lower(&column.expr, None).slot, } })); let common = translator.finish(parameters); self.has_star_projection = self.has_star_projection || projection.columns.has_star(); self.processors .push(ProcessedGroupMember::Data(ProcessedDataSource { id, projection, output_table_name: source .output_table_name .as_deref() .map(|name| self.interner.get_or_intern(name)), common, })); } pub fn include_parameter( &mut self, id: E::ParameterId, source: &StreamParameterIndexLookupCreator, ) { let mut translator = ProcessorTranslator::new(self, &source.processor); let parameters = translator.translate_common(); let outputs = translator.lower_all(&source.outputs, None, &mut 0); let common = translator.finish(parameters); // Lookups and outputs share the parameter buffer. self.max_parameters = self .max_parameters .max(common.parameters.len() + outputs.len()); self.processors .push(ProcessedGroupMember::Parameter(ProcessedParameterSource { id, outputs, common, })); } } /// Allocates a new value slot, given a mutable reference to a slot counter like /// [ProcessorGroup::num_input_slots]. /// /// This takes the field instead of the group so that it can be called while other fields of the /// group are borrowed. fn next_slot(num_slots: &mut u32) -> u32 { let current = *num_slots; *num_slots += 1; current } /// A slot storing the value of an expression, along with the amount of table-valued functions /// that need to be expanded before the value is available. /// /// A depth of `0` means that the value only depends on the source row, a depth of `i + 1` means /// that it depends on outputs of the `i`-th table-valued function (and potentially earlier ones). #[derive(Clone, Copy)] struct LoweredValue { slot: Slot, depth: usize, } /// Lowers expressions of a single [TableProcessor] into [EvaluatorInstruction]s operating on slots /// of a [ProcessorGroup]. struct ProcessorTranslator<'a, E: ReplicationEmbedder> { group: &'a mut ProcessorGroup, processor: &'a TableProcessor, /// For each entry in [TableProcessor::table_valued_functions], the slots assigned to its /// output columns. function_outputs: Vec>, /// The amount of internal slots used by this processor so far. num_internal_slots: u32, /// Instructions to run, grouped by the depth (see [LoweredValue::depth]) of their inputs. /// /// This allows evaluating expressions (and in particular, filters) before expanding /// table-valued functions they don't depend on. sections: Vec>, } impl<'a, E: ReplicationEmbedder> ProcessorTranslator<'a, E> { fn new(group: &'a mut ProcessorGroup, processor: &'a TableProcessor) -> Self { let mut num_internal_slots = 0; let function_outputs = processor .table_valued_functions .iter() .map(|f| { f.function .output_columns() .iter() .map(|_| Slot::Internal(next_slot(&mut num_internal_slots))) .collect() }) .collect(); Self { group, processor, function_outputs, num_internal_slots, sections: (0..=processor.table_valued_functions.len()) .map(|_| Vec::new()) .collect(), } } /// Lowers table-valued function inputs and filters, returning the slots for parameters. fn translate_common(&mut self) -> Vec { let processor = self.processor; for (index, function) in processor.table_valued_functions.iter().enumerate() { let mut depth = 0; let inputs = self.lower_all(&function.inputs, None, &mut depth); debug_assert!( depth <= index, "table-valued function inputs can only depend on earlier functions" ); self.sections[index + 1].push(EvaluatorInstruction::ExpandTableValuedFunction( ProcessedTableValuedFunction { function: function.function, inputs, outputs: self.function_outputs[index].clone(), }, )); } for filter in &processor.filters { let value = self.lower(filter, None); self.sections[value.depth].push(EvaluatorInstruction::CheckFilter(value.slot)); } self.lower_all(&processor.parameters, None, &mut 0) } /// Concatenates lowered instructions, so that every instruction runs after the table-valued /// functions it depends on have been expanded. fn finish(self, parameters: Vec) -> CommonProcessedSource { let group = self.group; group.num_internal_slots = group.num_internal_slots.max(self.num_internal_slots); group.max_parameters = group.max_parameters.max(parameters.len()); group.max_table_valued_functions = group .max_table_valued_functions .max(self.processor.table_valued_functions.len()); CommonProcessedSource { instructions: self.sections.into_iter().flatten().collect(), parameters, } } /// Lowers an expression, returning the slot storing its value along with its depth. /// /// For references to external data, this is the slot storing that data and no instruction is /// emitted. fn lower( &mut self, expr: &TableProcessorExpression, // When set, emit instructions into this buffer instead of hoisting subexpressions. This is // needed for CASE WHEN expressions, where whens and thens evaluate conditionally and thus // can't be hoisted. mut target_buffer: Option<&mut Vec>, ) -> LoweredValue { let mut depth = 0; let op = match expr { SqlExpression::ExternalData(data) => return self.slot_for(data), SqlExpression::Literal(literal) => ScalarOperation::Literal(literal.clone()), SqlExpression::Unary(unary) => ScalarOperation::Unary { operator: unary.operator, operand: self.lower_operand( &unary.operand, target_buffer.as_deref_mut(), &mut depth, ), }, SqlExpression::Binary(binary) => ScalarOperation::Binary { left: self.lower_operand(&binary.left, target_buffer.as_deref_mut(), &mut depth), operator: binary.operator, right: self.lower_operand(&binary.right, target_buffer.as_deref_mut(), &mut depth), }, SqlExpression::Between(between) => ScalarOperation::Between { value: self.lower_operand(&between.value, target_buffer.as_deref_mut(), &mut depth), low: self.lower_operand(&between.low, target_buffer.as_deref_mut(), &mut depth), high: self.lower_operand(&between.high, target_buffer.as_deref_mut(), &mut depth), }, SqlExpression::ScalarIn(scalar_in) => ScalarOperation::ScalarIn { target: self.lower_operand( &scalar_in.target, target_buffer.as_deref_mut(), &mut depth, ), r#in: self.lower_all(&scalar_in.r#in, target_buffer.as_deref_mut(), &mut depth), }, SqlExpression::CaseWhen(case_when) => { return self.lower_case_when(case_when, target_buffer.as_deref_mut()); } SqlExpression::Cast(cast) => ScalarOperation::Cast { operand: self.lower_operand( &cast.operand, target_buffer.as_deref_mut(), &mut depth, ), cast_as: cast.cast_as, }, SqlExpression::FunctionCall(call) => ScalarOperation::FunctionCall { function: call.function, inputs: self.lower_all(&call.parameters, target_buffer.as_deref_mut(), &mut depth), }, }; let output_slot = self.next_internal_slot(); let instruction = EvaluatorInstruction::Evaluate { op, output_slot }; target_buffer .unwrap_or_else(|| &mut self.sections[depth]) .push(instruction); LoweredValue { slot: output_slot, depth, } } /// Lowers a `CASE WHEN` expression into a chain of conditional jumps. /// /// See [EvaluatorInstruction::JumpForward] for a description of the code this generates. fn lower_case_when( &mut self, case_when: &CaseWhenExpression, mut target_buffer: Option<&mut Vec>, ) -> LoweredValue { let mut depth = 0; let operand = case_when .operand .as_ref() .map(|operand| self.lower_operand(operand, target_buffer.as_deref_mut(), &mut depth)); let output_slot = self.next_internal_slot(); let mut instructions = vec![]; // Indices of jumps at the end of each THEN block, patched to jump past the entire // expression. let mut jump_to_end = vec![]; for (i, WhenThen { when, then }) in case_when.whens.iter().enumerate() { let when_target = if i == 0 { target_buffer.as_deref_mut() } else { Some(&mut instructions) }; let when = self.lower_operand(when, when_target, &mut depth); let condition = match operand { None => when, Some(operand) => { // CASE with operand: Emit a `$operand = $when` check. let comparison = self.next_internal_slot(); instructions.push(EvaluatorInstruction::Evaluate { op: ScalarOperation::Binary { left: operand, operator: BinaryOperator::Equals, right: when, }, output_slot: comparison, }); comparison } }; let jump_if_falsy = Self::emit_jump(&mut instructions, Some(condition)); self.assign_branch(output_slot, then, &mut instructions, &mut depth); jump_to_end.push(Self::emit_jump(&mut instructions, None)); Self::patch_jump(&mut instructions, jump_if_falsy); } if let Some(otherwise) = &case_when.r#else { self.assign_branch(output_slot, otherwise, &mut instructions, &mut depth); } else { // If no condition matched and there's no else, evaluate to NULL. instructions.push(EvaluatorInstruction::Evaluate { op: ScalarOperation::Literal(LiteralExpression::Null), output_slot, }); } for jump in jump_to_end { Self::patch_jump(&mut instructions, jump); } // Jumps are relative, so the block can be moved as a whole. target_buffer .unwrap_or_else(|| &mut self.sections[depth]) .extend(instructions); LoweredValue { slot: output_slot, depth, } } /// Lowers a `THEN` or `ELSE` branch into `instructions`, copying its value into `output_slot`. fn assign_branch( &mut self, output_slot: Slot, expr: &TableProcessorExpression, instructions: &mut Vec, depth: &mut usize, ) { let slot = self.lower_operand(expr, Some(instructions), depth); instructions.push(EvaluatorInstruction::Evaluate { op: ScalarOperation::Copy(slot), output_slot, }); } /// Emits a forward jump whose target is set later by [Self::patch_jump]. fn emit_jump(instructions: &mut Vec, when_falsy: Option) -> usize { instructions.push(EvaluatorInstruction::JumpForward { skip: 0, when_falsy, }); instructions.len() - 1 } /// Makes the jump at `index` land on the next instruction to be pushed. fn patch_jump(instructions: &mut [EvaluatorInstruction], index: usize) { let target = instructions.len(); let EvaluatorInstruction::JumpForward { skip, .. } = &mut instructions[index] else { unreachable!() }; *skip = target - index - 1; } fn next_internal_slot(&mut self) -> Slot { Slot::Internal(next_slot(&mut self.num_internal_slots)) } /// Lowers an operand of an expression, raising `depth` to the depth of the operand. fn lower_operand( &mut self, expr: &TableProcessorExpression, conditional: Option<&mut Vec>, depth: &mut usize, ) -> Slot { let value = self.lower(expr, conditional); *depth = (*depth).max(value.depth); value.slot } /// Lowers multiple operands, see [Self::lower_operand]. fn lower_all( &mut self, expressions: &[TableProcessorExpression], mut conditional: Option<&mut Vec>, depth: &mut usize, ) -> Vec { expressions .iter() .map(|expr| self.lower_operand(expr, conditional.as_deref_mut(), depth)) .collect() } fn slot_for(&mut self, data: &TableProcessorData) -> LoweredValue { let group = &mut *self.group; let slot = match data { TableProcessorData::ColumnInSourceRow(name) => *group .input_columns .entry(group.interner.get_or_intern(name.as_str())) .or_insert_with(|| Slot::Input(next_slot(&mut group.num_input_slots))), TableProcessorData::SchemaName => *group .input_schema_name .get_or_insert_with(|| Slot::Input(next_slot(&mut group.num_input_slots))), TableProcessorData::TableName => *group .input_table_name .get_or_insert_with(|| Slot::Input(next_slot(&mut group.num_input_slots))), TableProcessorData::TableSuffix => { let prefix_length = self.processor.source_table.table.name.len(); match group .inputs_table_suffix .binary_search_by_key(&prefix_length, |input| input.prefix_length) { Ok(idx) => group.inputs_table_suffix[idx].slot, Err(idx) => { let slot = Slot::Input(next_slot(&mut group.num_input_slots)); group.inputs_table_suffix.insert( idx, TableSuffixInput { prefix_length, slot, }, ); slot } } } TableProcessorData::TableValuedFunction(output) => { let index = self .processor .table_valued_functions .iter() .position(|f| Arc::ptr_eq(f, &output.function)) .expect("table-valued function output must reference a function of the same processor"); return LoweredValue { slot: self.function_outputs[index][output.output_slot], depth: index + 1, }; } }; LoweredValue { slot, depth: 0 } } } #[cfg(test)] mod test { use std::sync::Arc; use super::{ EvaluatorInstruction::{self, Evaluate, JumpForward}, ProcessedGroupMember, ProcessedTableValuedFunction, ProcessorGroup, ScalarOperation, Slot, }; use crate::sync_plan::{ ReplicationEmbedder, expression::{ BinaryOperator, CaseWhenExpression, LiteralExpression, SqlExpression, TableValuedFunction, WhenThen, }, plan::{ StreamParameterIndexLookupCreator, TableProcessor, TableProcessorData, TableProcessorExpression, TableProcessorTableValuedFunction, TableProcessorTableValuedFunctionOutput, }, test::table_pattern, }; struct TestEmbedder; impl ReplicationEmbedder for TestEmbedder { type BucketId = (); type ParameterId = (); } fn column(name: &str) -> TableProcessorExpression { SqlExpression::ExternalData(TableProcessorData::ColumnInSourceRow(name.to_string())) } fn processor() -> TableProcessor { TableProcessor { source_table: table_pattern("users"), filters: vec![], parameters: vec![], table_valued_functions: vec![], } } #[test] fn evaluates_filters_before_expanding_functions() { // SELECT id FROM users, json_each(users.tags) WHERE users.active AND tags.value AND tags.key = $inputParameter let json_each = Arc::new(TableProcessorTableValuedFunction { function: TableValuedFunction::JsonEach, inputs: vec![column("tags")], }); let output = |output_slot| { SqlExpression::ExternalData(TableProcessorData::TableValuedFunction( TableProcessorTableValuedFunctionOutput { function: Arc::clone(&json_each), output_slot, }, )) }; let source = StreamParameterIndexLookupCreator { processor: TableProcessor { filters: vec![column("active"), output(1)], parameters: vec![output(0)], table_valued_functions: vec![Arc::clone(&json_each)], ..processor() }, outputs: vec![column("id")], }; let mut group = ProcessorGroup::::default(); group.include_parameter((), &source); let input = |name: &str| group.input_columns[&group.interner.get(name).unwrap()]; let (tags, active, id) = (input("tags"), input("active"), input("id")); let ProcessedGroupMember::Parameter(source) = &group.processors[0] else { panic!("expected parameter source"); }; let instructions = &source.common.instructions; let [ EvaluatorInstruction::CheckFilter(checked_active), EvaluatorInstruction::ExpandTableValuedFunction(ProcessedTableValuedFunction { function: TableValuedFunction::JsonEach, inputs, outputs: function_outputs, }), EvaluatorInstruction::CheckFilter(checked_value), ] = instructions.as_slice() else { panic!("unexpected instructions: {instructions:#?}"); }; // Should check the active column before evaluating the table-valued function. assert_eq!(*checked_active, active); assert_eq!(*inputs, [tags]); assert_eq!(function_outputs.len(), 2); assert_eq!(*checked_value, function_outputs[1]); assert_eq!(source.common.parameters, [function_outputs[0]]); assert_eq!(source.outputs, [id]); assert_eq!(group.num_input_slots, 3); assert_eq!(group.num_internal_slots, 2); // One lookup parameter and one output. assert_eq!(group.max_parameters, 2); assert_eq!(group.max_table_valued_functions, 1); } #[test] fn case_when_then() { // CASE WHEN 1 THEN 2 ELSE 3 END let source = StreamParameterIndexLookupCreator { processor: TableProcessor { filters: vec![], parameters: vec![], table_valued_functions: vec![], ..processor() }, outputs: vec![SqlExpression::CaseWhen(CaseWhenExpression { operand: None, whens: vec![WhenThen { when: SqlExpression::Literal(LiteralExpression::Integer(1)), then: SqlExpression::Literal(LiteralExpression::Integer(2)), }], r#else: Some(Box::new(SqlExpression::Literal( LiteralExpression::Integer(3), ))), })], }; let mut group = ProcessorGroup::::default(); group.include_parameter((), &source); let ProcessedGroupMember::Parameter(p) = &group.processors[0] else { panic!("Expected parameter"); }; let instructions = &p.common.instructions; assert!( matches!( instructions.as_slice(), [ // WHEN 1 Evaluate { op: ScalarOperation::Literal(LiteralExpression::Integer(1)), output_slot: Slot::Internal(1), }, JumpForward { skip: 3, when_falsy: Some(Slot::Internal(1)), }, // THEN 2 Evaluate { op: ScalarOperation::Literal(LiteralExpression::Integer(2)), output_slot: Slot::Internal(2), }, Evaluate { op: ScalarOperation::Copy(Slot::Internal(2)), output_slot: Slot::Internal(0), }, JumpForward { skip: 2, when_falsy: None, }, // ELSE 3 Evaluate { op: ScalarOperation::Literal(LiteralExpression::Integer(3)), output_slot: Slot::Internal(3), }, Evaluate { op: ScalarOperation::Copy(Slot::Internal(3)), output_slot: Slot::Internal(0), }, ] ), "unexpected instructions: {instructions:#?}" ); assert_eq!(p.outputs, [Slot::Internal(0)]); } #[test] fn case_when_with_operand() { let string = |s: &str| SqlExpression::Literal(LiteralExpression::String(Arc::new(s.into()))); // CASE a WHEN b THEN 'foo' ELSE 'bar' END let source = StreamParameterIndexLookupCreator { processor: processor(), outputs: vec![SqlExpression::CaseWhen(CaseWhenExpression { operand: Some(Box::new(column("a"))), whens: vec![WhenThen { when: column("b"), then: string("foo"), }], r#else: Some(Box::new(string("bar"))), })], }; let mut group = ProcessorGroup::::default(); group.include_parameter((), &source); let input = |name: &str| group.input_columns[&group.interner.get(name).unwrap()]; let (a, b) = (input("a"), input("b")); let ProcessedGroupMember::Parameter(p) = &group.processors[0] else { panic!("Expected parameter"); }; let instructions = &p.common.instructions; let [ // WHEN a == b Evaluate { op: ScalarOperation::Binary { left, operator: BinaryOperator::Equals, right, }, output_slot: Slot::Internal(1), }, // THEN 'foo' JumpForward { skip: 3, when_falsy: Some(Slot::Internal(1)), }, Evaluate { op: ScalarOperation::Literal(LiteralExpression::String(foo)), output_slot: Slot::Internal(2), }, Evaluate { op: ScalarOperation::Copy(Slot::Internal(2)), output_slot: Slot::Internal(0), }, JumpForward { skip: 2, when_falsy: None, }, // ELSE 'bar' Evaluate { op: ScalarOperation::Literal(LiteralExpression::String(bar)), output_slot: Slot::Internal(3), }, Evaluate { op: ScalarOperation::Copy(Slot::Internal(3)), output_slot: Slot::Internal(0), }, ] = instructions.as_slice() else { panic!("unexpected instructions: {instructions:#?}"); }; assert_eq!((*left, *right), (a, b)); assert_eq!((foo.as_str(), bar.as_str()), ("foo", "bar")); assert_eq!(p.outputs, [Slot::Internal(0)]); } }