uqa_execution/mutation/rules/columns/
selection.rs1use super::{invalid, RuleColumnSets};
8use crate::mutation::rules::indices::RuleIndexIter;
9use crate::mutation::rules::PreparedRuleBatch;
10use std::cmp::Reverse;
11use std::collections::{BTreeSet, BinaryHeap};
12use uqa_sql::SQLError;
13
14struct SelectedColumns {
15 indices: RuleIndexIter,
16 next: Option<usize>,
17 columns: BTreeSet<String>,
18}
19
20impl SelectedColumns {
21 fn advance(&mut self, previous: usize) -> Result<(), SQLError> {
22 self.next = self.indices.next().transpose()?;
23 if self.next.is_some_and(|next| next <= previous) {
24 return Err(invalid(
25 "qualification ordinals are not strictly increasing",
26 ));
27 }
28 Ok(())
29 }
30}
31
32impl PreparedRuleBatch {
33 pub fn matched_action_row_columns(&self) -> Result<RuleColumnSets<1>, SQLError> {
34 let mut selected = Vec::new();
35 for rule in &self.rules {
36 let columns = rule
37 .action_row_columns
38 .iter()
39 .flatten()
40 .cloned()
41 .collect::<BTreeSet<_>>();
42 if columns.is_empty() {
43 continue;
44 }
45 let mut indices = rule.matching_rows.reader()?;
46 let next = indices.next().transpose()?;
47 selected.push(SelectedColumns {
48 indices,
49 next,
50 columns,
51 });
52 }
53 let mut next_rows: BinaryHeap<_> = selected
54 .iter()
55 .enumerate()
56 .filter_map(|(rule, selected)| selected.next.map(|row| Reverse((row, rule))))
57 .collect();
58 let output = RuleColumnSets::from_rows(
60 (0..self.rows.len()).map(|index| {
61 let mut columns = BTreeSet::new();
62 while next_rows.peek().is_some_and(|next| next.0 .0 == index) {
63 let Reverse((_, rule)) = next_rows.pop().expect("peek found a rule");
64 let selection = &mut selected[rule];
65 columns.extend(selection.columns.iter().cloned());
66 selection.advance(index)?;
67 if let Some(row) = selection.next {
68 next_rows.push(Reverse((row, rule)));
69 }
70 }
71 Ok([columns])
72 }),
73 self.work_mem,
74 self.cancellation.clone(),
75 )?;
76 if selected.iter().any(|selection| selection.next.is_some()) {
77 return Err(invalid("qualification ordinal is outside the event set"));
78 }
79 Ok(output)
80 }
81
82 pub fn missing_action_row_columns(&self) -> Result<RuleColumnSets<2>, SQLError> {
83 let matched = self.matched_action_row_columns()?;
84 RuleColumnSets::from_rows(
85 matched
86 .reader()?
87 .zip(self.rows.iter())
88 .map(|(columns, row)| {
89 let [columns] = columns?;
90 let row = row?;
91 let missing = |record: &Option<uqa_storage::document_store::Document>| {
92 if let Some(record) = record {
93 columns
94 .iter()
95 .filter(|column| !record.contains_key(*column))
96 .cloned()
97 .collect()
98 } else {
99 BTreeSet::new()
100 }
101 };
102 Ok([missing(&row.old), missing(&row.new)])
103 }),
104 self.work_mem,
105 self.cancellation.clone(),
106 )
107 }
108}