1use std::path::Path;
13
14use anyhow::{anyhow, Result};
15use serde_json::{json, Map, Value};
16
17use crate::meta::{self, ColumnFacts};
18
19#[derive(Clone, Debug)]
21pub enum Condition {
22 Compare {
24 column: String,
25 op: String,
26 value: Value,
27 },
28 In { column: String, values: Vec<Value> },
30 Between {
32 column: String,
33 low: Value,
34 high: Value,
35 },
36 And(Vec<Condition>),
38 Or(Vec<Condition>),
40 Not(Box<Condition>),
42}
43
44impl Condition {
45 pub fn columns(&self) -> Vec<String> {
47 match self {
48 Condition::Compare { column, .. }
49 | Condition::In { column, .. }
50 | Condition::Between { column, .. } => vec![column.clone()],
51 Condition::And(conditions) | Condition::Or(conditions) => conditions
52 .iter()
53 .flat_map(|condition| condition.columns())
54 .collect(),
55 Condition::Not(condition) => condition.columns(),
56 }
57 }
58
59 fn may_match(&self, column: &ColumnFacts) -> bool {
63 match self {
64 Condition::Compare { op, value, .. } => {
65 let (Some(min), Some(max)) = (&column.min, &column.max) else {
66 return true;
67 };
68 match op.as_str() {
69 "==" => in_range(value, min, max),
70 "!=" => true, "<" => less_than(min, value),
74 "<=" => less_or_equal(min, value),
75 ">" => greater_than(max, value),
76 ">=" => greater_or_equal(max, value),
77 _ => true,
78 }
79 }
80 Condition::In { values, .. } => {
81 let (Some(min), Some(max)) = (&column.min, &column.max) else {
82 return true;
83 };
84 values.iter().any(|value| in_range(value, min, max))
85 }
86 Condition::Between { low, high, .. } => {
87 let (Some(min), Some(max)) = (&column.min, &column.max) else {
88 return true;
89 };
90 less_or_equal(low, max) && greater_or_equal(high, min)
92 }
93 Condition::And(conditions) => conditions
94 .iter()
95 .all(|condition| condition.may_match(column)),
96 Condition::Or(conditions) => conditions
97 .iter()
98 .any(|condition| condition.may_match(column)),
99 Condition::Not(condition) => condition.may_match(column),
100 }
101 }
102}
103
104pub fn parse(value: &Value) -> Result<Condition> {
106 let object = value
107 .as_object()
108 .ok_or_else(|| anyhow!("a condition is a table"))?;
109
110 if let Some(conditions) = object.get("and") {
111 return Ok(Condition::And(parse_all(conditions)?));
112 }
113 if let Some(conditions) = object.get("or") {
114 return Ok(Condition::Or(parse_all(conditions)?));
115 }
116 if let Some(inner) = object.get("not") {
117 return Ok(Condition::Not(Box::new(parse(inner)?)));
118 }
119
120 let column = object
121 .get("column")
122 .and_then(Value::as_str)
123 .ok_or_else(|| anyhow!("a condition needs a column"))?
124 .to_string();
125
126 if let Some(values) = object.get("in") {
127 let values = values
128 .as_array()
129 .ok_or_else(|| anyhow!("in takes a list"))?
130 .clone();
131 return Ok(Condition::In { column, values });
132 }
133 if let Some(bounds) = object.get("between") {
134 let bounds = bounds
135 .as_array()
136 .ok_or_else(|| anyhow!("between takes a list of two"))?;
137 if bounds.len() != 2 {
138 return Err(anyhow!("between takes a list of two"));
139 }
140 return Ok(Condition::Between {
141 column,
142 low: bounds[0].clone(),
143 high: bounds[1].clone(),
144 });
145 }
146
147 let op = object
148 .get("op")
149 .and_then(Value::as_str)
150 .ok_or_else(|| anyhow!("a condition needs an op"))?
151 .to_string();
152 let value = object
153 .get("value")
154 .cloned()
155 .ok_or_else(|| anyhow!("a condition needs a value"))?;
156 Ok(Condition::Compare { column, op, value })
157}
158
159fn parse_all(value: &Value) -> Result<Vec<Condition>> {
161 let list = value
162 .as_array()
163 .ok_or_else(|| anyhow!("and/or take a list of conditions"))?;
164 list.iter().map(parse).collect()
165}
166
167#[derive(Clone, Debug)]
169pub struct Prune {
170 pub groups_total: usize,
172 pub groups_skipped: usize,
174 pub groups_read: usize,
176 pub rows_total: i64,
178 pub rows_read: i64,
180 pub bytes_total: i64,
182 pub bytes_read: i64,
184 pub groups: Vec<GroupPrune>,
186}
187
188#[derive(Clone, Debug)]
190pub struct GroupPrune {
191 pub index: usize,
192 pub rows: i64,
193 pub bytes: i64,
194 pub skipped: bool,
196 pub ruled_out_by: Option<String>,
198}
199
200impl Prune {
201 pub fn to_json(&self) -> Value {
202 json!({
203 "groups_total": self.groups_total,
204 "groups_skipped": self.groups_skipped,
205 "groups_read": self.groups_read,
206 "rows_total": self.rows_total,
207 "rows_read": self.rows_read,
208 "bytes_total": self.bytes_total,
209 "bytes_read": self.bytes_read,
210 "skip_ratio": if self.groups_total > 0 {
211 self.groups_skipped as f64 / self.groups_total as f64
212 } else {
213 0.0
214 },
215 "groups": self.groups.iter().map(|group| json!({
216 "index": group.index,
217 "rows": group.rows,
218 "bytes": group.bytes,
219 "skipped": group.skipped,
220 "ruled_out_by": group.ruled_out_by,
221 })).collect::<Vec<Value>>(),
222 })
223 }
224}
225
226pub fn prune(path: &Path, condition: &Condition) -> Result<Prune> {
228 let facts = meta::file_facts(path)?;
229 let columns = meta::column_facts(path, false)?;
230
231 let wanted: Vec<String> = condition.columns();
232 let mut per_column: Vec<(&String, &ColumnFacts)> = Vec::new();
233 for name in &wanted {
234 match columns.iter().find(|column| &column.name == name) {
235 Some(column) => per_column.push((name, column)),
236 None => return Err(anyhow!("the file has no column named {name}")),
237 }
238 }
239
240 let group_count = facts.row_group_rows.len();
241 let mut groups = Vec::new();
242 let mut groups_skipped = 0;
243 let mut rows_read = 0;
244 let mut bytes_read = 0;
245
246 for (index, group) in facts.row_group_rows.iter().enumerate() {
247 let bytes = facts
248 .row_group_bytes
249 .get(index)
250 .copied()
251 .unwrap_or_default();
252 let mut skipped = false;
253 let mut ruled_out_by = None;
254 for (name, column) in &per_column {
255 let group_min = column
256 .row_groups
257 .get(index)
258 .and_then(|group| group.min.as_ref());
259 let group_max = column
260 .row_groups
261 .get(index)
262 .and_then(|group| group.max.as_ref());
263 let scoped = ColumnFacts {
264 min: group_min.cloned(),
265 max: group_max.cloned(),
266 ..(*column).clone()
267 };
268 if !condition.may_match(&scoped) {
269 skipped = true;
270 ruled_out_by = Some((*name).clone());
271 break;
272 }
273 }
274 if skipped {
275 groups_skipped += 1;
276 } else {
277 rows_read += group;
278 bytes_read += bytes;
279 }
280 groups.push(GroupPrune {
281 index,
282 rows: *group,
283 bytes,
284 skipped,
285 ruled_out_by,
286 });
287 }
288
289 Ok(Prune {
290 groups_total: group_count,
291 groups_skipped,
292 groups_read: group_count - groups_skipped,
293 rows_total: facts.rows,
294 rows_read,
295 bytes_total: facts.size_bytes as i64,
296 bytes_read,
297 groups,
298 })
299}
300
301fn in_range(value: &Value, min: &Value, max: &Value) -> bool {
303 less_or_equal(min, value) && less_or_equal(value, max)
304}
305
306fn less_than(value: &Value, bound: &Value) -> bool {
308 compare(value, bound)
309 .map(|order| order.is_lt())
310 .unwrap_or(true)
311}
312
313fn less_or_equal(value: &Value, bound: &Value) -> bool {
315 compare(value, bound)
316 .map(|order| order.is_le())
317 .unwrap_or(true)
318}
319
320fn greater_than(value: &Value, bound: &Value) -> bool {
322 compare(value, bound)
323 .map(|order| order.is_gt())
324 .unwrap_or(true)
325}
326
327fn greater_or_equal(value: &Value, bound: &Value) -> bool {
329 compare(value, bound)
330 .map(|order| order.is_ge())
331 .unwrap_or(true)
332}
333
334fn compare(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
336 match (left, right) {
337 (Value::Number(left), Value::Number(right)) => left
338 .as_f64()
339 .zip(right.as_f64())
340 .and_then(|(left, right)| left.partial_cmp(&right)),
341 (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
342 (Value::Bool(left), Value::Bool(right)) => Some(left.cmp(right)),
343 _ => None,
344 }
345}
346
347pub fn describe(condition: &Condition) -> Value {
349 match condition {
350 Condition::Compare { column, op, value } => {
351 let mut object = Map::new();
352 object.insert("column".into(), Value::String(column.clone()));
353 object.insert("op".into(), Value::String(op.clone()));
354 object.insert("value".into(), value.clone());
355 Value::Object(object)
356 }
357 Condition::In { column, values } => {
358 let mut object = Map::new();
359 object.insert("column".into(), Value::String(column.clone()));
360 object.insert("in".into(), Value::Array(values.clone()));
361 Value::Object(object)
362 }
363 Condition::Between { column, low, high } => {
364 let mut object = Map::new();
365 object.insert("column".into(), Value::String(column.clone()));
366 object.insert(
367 "between".into(),
368 Value::Array(vec![low.clone(), high.clone()]),
369 );
370 Value::Object(object)
371 }
372 Condition::And(conditions) => {
373 let mut object = Map::new();
374 object.insert(
375 "and".into(),
376 Value::Array(conditions.iter().map(describe).collect()),
377 );
378 Value::Object(object)
379 }
380 Condition::Or(conditions) => {
381 let mut object = Map::new();
382 object.insert(
383 "or".into(),
384 Value::Array(conditions.iter().map(describe).collect()),
385 );
386 Value::Object(object)
387 }
388 Condition::Not(inner) => {
389 let mut object = Map::new();
390 object.insert("not".into(), describe(inner));
391 Value::Object(object)
392 }
393 }
394}