use std::sync::Arc;
use hamelin_lib::tree::{
ast::{
command::Command,
expression::Expression,
identifier::{Identifier, SimpleIdentifier},
},
builder::{drop_command, field_ref, set_command},
typed_ast::{clause::Projections, environment::TypeEnvironment},
};
pub use crate::unique::UniqueNameGenerator;
pub fn lower_compound_assignments(
projections: &Projections,
name_gen: &mut UniqueNameGenerator,
schema: &TypeEnvironment,
) -> (Vec<(SimpleIdentifier, Arc<Expression>)>, Vec<Command>) {
let mut assignments = Vec::new();
let mut set_builder = set_command();
let mut drop_builder = drop_command();
let mut has_compounds = false;
for assignment in &projections.assignments {
match assignment.identifier.valid_ref() {
Ok(Identifier::Compound(compound)) => {
let flat_name = name_gen.next(schema);
assignments.push((flat_name.clone(), assignment.expression.ast.clone()));
let original: Identifier = compound.clone().into();
set_builder = set_builder.named_field(original, field_ref(flat_name.as_str()));
drop_builder = drop_builder.field(flat_name);
has_compounds = true;
}
Ok(Identifier::Simple(simple)) => {
assignments.push((simple.clone(), assignment.expression.ast.clone()));
}
Err(_) => {
}
}
}
if has_compounds {
(assignments, vec![set_builder.build(), drop_builder.build()])
} else {
(assignments, vec![])
}
}