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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
mod group_by;
mod join;
mod keys;
mod rename;
mod utils;
use polars_core::config::verbose;
use polars_core::datatypes::PlHashMap;
use polars_core::prelude::*;
use utils::*;
use super::*;
use crate::dsl::function_expr::FunctionExpr;
use crate::prelude::optimizer::predicate_pushdown::group_by::process_group_by;
use crate::prelude::optimizer::predicate_pushdown::join::process_join;
use crate::prelude::optimizer::predicate_pushdown::rename::process_rename;
use crate::utils::{check_input_node, has_aexpr};
pub type HiveEval<'a> = Option<&'a dyn Fn(Node, &Arena<AExpr>) -> Option<Arc<dyn PhysicalIoExpr>>>;
pub struct PredicatePushDown<'a> {
hive_partition_eval: HiveEval<'a>,
verbose: bool,
}
impl<'a> PredicatePushDown<'a> {
pub fn new(hive_partition_eval: HiveEval<'a>) -> Self {
Self {
hive_partition_eval,
verbose: verbose(),
}
}
fn optional_apply_predicate(
&self,
lp: ALogicalPlan,
local_predicates: Vec<Node>,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
) -> ALogicalPlan {
if !local_predicates.is_empty() {
let predicate = combine_predicates(local_predicates.into_iter(), expr_arena);
let input = lp_arena.add(lp);
ALogicalPlan::Selection { input, predicate }
} else {
lp
}
}
fn pushdown_and_assign(
&self,
input: Node,
acc_predicates: PlHashMap<Arc<str>, Node>,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<()> {
let alp = lp_arena.take(input);
let lp = self.push_down(alp, acc_predicates, lp_arena, expr_arena)?;
lp_arena.replace(input, lp);
Ok(())
}
/// Filter will be pushed down.
fn pushdown_and_continue(
&self,
lp: ALogicalPlan,
mut acc_predicates: PlHashMap<Arc<str>, Node>,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
has_projections: bool,
) -> PolarsResult<ALogicalPlan> {
let inputs = lp.get_inputs();
let exprs = lp.get_exprs();
if has_projections {
// projections should only have a single input.
if inputs.len() > 1 {
// except for ExtContext
assert!(matches!(lp, ALogicalPlan::ExtContext { .. }));
}
let input = inputs[inputs.len() - 1];
let input_schema = lp_arena.get(input).schema(lp_arena);
let (eligibility, alias_rename_map) =
pushdown_eligibility(input_schema.as_ref(), &exprs, &acc_predicates, expr_arena)?;
let local_predicates = match eligibility {
PushdownEligibility::Full => vec![],
PushdownEligibility::Partial { to_local } => {
let mut out = Vec::<Node>::with_capacity(to_local.len());
for key in to_local {
out.push(acc_predicates.remove(&key).unwrap());
}
out
},
PushdownEligibility::NoPushdown => {
return self.no_pushdown_restart_opt(lp, acc_predicates, lp_arena, expr_arena)
},
};
if !alias_rename_map.is_empty() {
for (_, node) in acc_predicates.iter_mut() {
let mut needs_rename = false;
for (_, ae) in (&*expr_arena).iter(*node) {
if let AExpr::Column(name) = ae {
needs_rename |= alias_rename_map.contains_key(name);
if needs_rename {
break;
}
}
}
if needs_rename {
let mut new_expr = node_to_expr(*node, expr_arena);
new_expr.mutate().apply(|e| {
if let Expr::Column(name) = e {
if let Some(rename_to) = alias_rename_map.get(name) {
*name = rename_to.clone();
};
};
true
});
let predicate = to_aexpr(new_expr, expr_arena);
*node = predicate;
}
}
}
let alp = lp_arena.take(input);
let alp = self.push_down(alp, acc_predicates, lp_arena, expr_arena)?;
lp_arena.replace(input, alp);
let lp = lp.with_exprs_and_input(exprs, inputs);
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
} else {
let mut local_predicates = Vec::with_capacity(acc_predicates.len());
// determine new inputs by pushing down predicates
let new_inputs = inputs
.iter()
.map(|&node| {
// first we check if we are able to push down the predicate passed this node
// it could be that this node just added the column where we base the predicate on
let input_schema = lp_arena.get(node).schema(lp_arena);
let mut pushdown_predicates =
optimizer::init_hashmap(Some(acc_predicates.len()));
for (_, &predicate) in acc_predicates.iter() {
// we can pushdown the predicate
if check_input_node(predicate, &input_schema, expr_arena) {
insert_and_combine_predicate(
&mut pushdown_predicates,
predicate,
expr_arena,
)
}
// we cannot pushdown the predicate we do it here
else {
local_predicates.push(predicate);
}
}
let alp = lp_arena.take(node);
let alp = self.push_down(alp, pushdown_predicates, lp_arena, expr_arena)?;
lp_arena.replace(node, alp);
Ok(node)
})
.collect::<PolarsResult<Vec<_>>>()?;
let lp = lp.with_exprs_and_input(exprs, new_inputs);
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
}
/// Filter will be done at this node, but we continue optimization
fn no_pushdown_restart_opt(
&self,
lp: ALogicalPlan,
acc_predicates: PlHashMap<Arc<str>, Node>,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<ALogicalPlan> {
let inputs = lp.get_inputs();
let exprs = lp.get_exprs();
let new_inputs = inputs
.iter()
.map(|&node| {
let alp = lp_arena.take(node);
let alp = self.push_down(
alp,
init_hashmap(Some(acc_predicates.len())),
lp_arena,
expr_arena,
)?;
lp_arena.replace(node, alp);
Ok(node)
})
.collect::<PolarsResult<Vec<_>>>()?;
let lp = lp.with_exprs_and_input(exprs, new_inputs);
// all predicates are done locally
let local_predicates = acc_predicates.values().copied().collect::<Vec<_>>();
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
/// Predicate pushdown optimizer
///
/// # Arguments
///
/// * `AlogicalPlan` - Arena based logical plan tree representing the query.
/// * `acc_predicates` - The predicates we accumulate during tree traversal.
/// The hashmap maps from leaf-column name to predicates on that column.
/// If the key is already taken we combine the predicate with a bitand operation.
/// The `Node`s are indexes in the `expr_arena`
/// * `lp_arena` - The local memory arena for the logical plan.
/// * `expr_arena` - The local memory arena for the expressions.
fn push_down(
&self,
lp: ALogicalPlan,
mut acc_predicates: PlHashMap<Arc<str>, Node>,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<ALogicalPlan> {
use ALogicalPlan::*;
match lp {
Selection { predicate, input } => {
// Use a tmp_key to avoid inadvertently combining predicates that otherwise would have
// been partially pushed:
//
// (1) .filter(pl.count().over("key") == 1)
// (2) .filter(pl.col("key") == 1)
//
// (2) can be pushed past (1) but they both have the same predicate
// key name in the hashtable.
let tmp_key = Arc::<str>::from(&*temporary_unique_key(&acc_predicates));
acc_predicates.insert(tmp_key.clone(), predicate);
let local_predicates = match pushdown_eligibility(lp.schema(lp_arena).as_ref(), &[], &acc_predicates, expr_arena)?.0 {
PushdownEligibility::Full => vec![],
PushdownEligibility::Partial { to_local } => {
let mut out = Vec::<Node>::with_capacity(to_local.len());
for key in to_local {
out.push(acc_predicates.remove(&key).unwrap());
}
out
},
PushdownEligibility::NoPushdown => {
let out = acc_predicates.values().copied().collect();
acc_predicates.clear();
out
},
};
if let Some(predicate) = acc_predicates.remove(&tmp_key) {
insert_and_combine_predicate(&mut acc_predicates, predicate, expr_arena);
}
let alp = lp_arena.take(input);
let new_input = self.push_down(alp, acc_predicates, lp_arena, expr_arena)?;
// TODO!
// If a predicates result would be influenced by earlier applied
// predicates, we simply don't pushdown this one passed this node
// However, we can do better and let it pass but store the order of the predicates
// so that we can apply them in correct order at the deepest level
Ok(self.optional_apply_predicate(new_input, local_predicates, lp_arena, expr_arena))
}
DataFrameScan {
df,
schema,
output_schema,
projection,
selection,
} => {
let selection = predicate_at_scan(acc_predicates, selection, expr_arena);
let lp = DataFrameScan {
df,
schema,
output_schema,
projection,
selection,
};
Ok(lp)
}
Scan {
mut paths,
mut file_info,
predicate,
mut scan_type,
file_options: options,
output_schema
} => {
for node in acc_predicates.values() {
debug_assert_aexpr_allows_predicate_pushdown(*node, expr_arena);
}
let local_predicates = match &scan_type {
#[cfg(feature = "parquet")]
FileScan::Parquet { .. } => vec![],
#[cfg(feature = "ipc")]
FileScan::Ipc { .. } => vec![],
_ => {
// Disallow row index pushdown of other scans as they may
// not update the row index properly before applying the
// predicate (e.g. FileScan::Csv doesn't).
if let Some(ref row_index) = options.row_index {
let row_index_predicates = transfer_to_local_by_name(expr_arena, &mut acc_predicates, |name| {
name.as_ref() == row_index.name
});
row_index_predicates
} else {
vec![]
}
}
};
let predicate = predicate_at_scan(acc_predicates, predicate, expr_arena);
if let (true, Some(predicate)) = (file_info.hive_parts.is_some(), predicate) {
if let Some(io_expr) = self.hive_partition_eval.unwrap()(predicate, expr_arena) {
if let Some(stats_evaluator) = io_expr.as_stats_evaluator() {
let mut new_paths = Vec::with_capacity(paths.len());
for path in paths.as_ref().iter() {
file_info.update_hive_partitions(path)?;
let hive_part_stats = file_info.hive_parts.as_deref().ok_or_else(|| polars_err!(ComputeError: "cannot combine hive partitioned directories with non-hive partitioned ones"))?;
if stats_evaluator.should_read(hive_part_stats.get_statistics())? {
new_paths.push(path.clone());
}
}
if paths.len() != new_paths.len() {
if self.verbose {
eprintln!("hive partitioning: skipped {} files, first file : {}", paths.len() - new_paths.len(), paths[0].display())
}
scan_type.remove_metadata();
}
if paths.is_empty() {
let schema = output_schema.as_ref().unwrap_or(&file_info.schema);
let df = DataFrame::from(schema.as_ref());
return Ok(DataFrameScan {
df: Arc::new(df),
schema: schema.clone(),
output_schema: None,
projection: None,
selection: None
})
} else {
paths = Arc::from(new_paths)
}
}
}
}
let mut do_optimization = match &scan_type {
#[cfg(feature = "csv")]
FileScan::Csv {..} => options.n_rows.is_none(),
FileScan::Anonymous {function, ..} => function.allows_predicate_pushdown(),
#[allow(unreachable_patterns)]
_ => true
};
do_optimization &= predicate.is_some();
let lp = if do_optimization {
Scan {
paths,
file_info,
predicate,
file_options: options,
output_schema,
scan_type
}
} else {
let lp = Scan {
paths,
file_info,
predicate: None,
file_options: options,
output_schema,
scan_type
};
if let Some(predicate) = predicate {
let input = lp_arena.add(lp);
Selection {
input,
predicate
}
} else {
lp
}
};
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
Distinct {
input,
options
} => {
if let Some(ref subset) = options.subset {
// Predicates on the subset can pass.
let subset = subset.clone();
let mut names_set = PlHashSet::<&str>::with_capacity(subset.len());
for name in subset.iter() {
names_set.insert(name.as_str());
};
let condition = |name: Arc<str>| !names_set.contains(name.as_ref());
let local_predicates =
transfer_to_local_by_name(expr_arena, &mut acc_predicates, condition);
self.pushdown_and_assign(input, acc_predicates, lp_arena, expr_arena)?;
let lp = Distinct {
input,
options
};
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
} else {
let lp = Distinct {
input,
options
};
self.no_pushdown_restart_opt(lp, acc_predicates, lp_arena, expr_arena)
}
}
Join {
input_left,
input_right,
left_on,
right_on,
schema,
options,
} => {
process_join(
self,
lp_arena,
expr_arena,
input_left,
input_right,
left_on,
right_on,
schema,
options,
acc_predicates
)
}
MapFunction { ref function, .. } => {
if function.allow_predicate_pd()
{
match function {
FunctionNode::Rename {
existing,
new,
..
} => {
let local_predicates = process_rename(&mut acc_predicates,
expr_arena,
existing,
new,
)?;
let lp = self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)?;
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
},
FunctionNode::Explode {columns, ..} => {
let condition = |name: Arc<str>| columns.iter().any(|s| s.as_ref() == &*name);
// first columns that refer to the exploded columns should be done here
let local_predicates =
transfer_to_local_by_name(expr_arena, &mut acc_predicates, condition);
let lp = self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)?;
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
FunctionNode::Melt {
args,
..
} => {
let variable_name = args.variable_name.as_deref().unwrap_or("variable");
let value_name = args.value_name.as_deref().unwrap_or("value");
// predicates that will be done at this level
let condition = |name: Arc<str>| {
let name = &*name;
name == variable_name
|| name == value_name
|| args.value_vars.iter().any(|s| s.as_str() == name)
};
let local_predicates =
transfer_to_local_by_name(expr_arena, &mut acc_predicates, condition);
let lp = self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)?;
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
_ => {
self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)
}
}
} else {
self.no_pushdown_restart_opt(lp, acc_predicates, lp_arena, expr_arena)
}
}
Aggregate {input, keys, aggs, schema, apply, maintain_order, options, } => {
process_group_by(self, lp_arena, expr_arena, input, keys, aggs, schema, maintain_order, apply, options, acc_predicates)
},
lp @ Union {..} => {
let mut local_predicates = vec![];
// a count is influenced by a Union/Vstack
acc_predicates.retain(|_, predicate| {
if has_aexpr(*predicate, expr_arena, |ae| matches!(ae, AExpr::Len)) {
local_predicates.push(*predicate);
false
} else {
true
}
});
let lp = self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)?;
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
lp @ Sort{..} => {
let mut local_predicates = vec![];
acc_predicates.retain(|_, predicate| {
if predicate_is_sort_boundary(*predicate, expr_arena) {
local_predicates.push(*predicate);
false
} else {
true
}
});
let lp = self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)?;
Ok(self.optional_apply_predicate(lp, local_predicates, lp_arena, expr_arena))
}
// Pushed down passed these nodes
lp@ Sink {..} => {
self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, false)
}
lp @ HStack {..} | lp @ Projection {..} | lp @ ExtContext {..} => {
self.pushdown_and_continue(lp, acc_predicates, lp_arena, expr_arena, true)
}
// NOT Pushed down passed these nodes
// predicates influence slice sizes
lp @ Slice { .. }
// caches will be different
| lp @ Cache { .. }
=> {
self.no_pushdown_restart_opt(lp, acc_predicates, lp_arena, expr_arena)
}
lp @ HConcat { .. }
=> {
self.no_pushdown_restart_opt(lp, acc_predicates, lp_arena, expr_arena)
}
#[cfg(feature = "python")]
PythonScan {mut options, predicate} => {
if options.pyarrow {
let predicate = predicate_at_scan(acc_predicates, predicate, expr_arena);
if let Some(predicate) = predicate {
// simplify expressions before we translate them to pyarrow
let lp = PythonScan {options: options.clone(), predicate: Some(predicate)};
let lp_top = lp_arena.add(lp);
let stack_opt = StackOptimizer{};
let lp_top = stack_opt.optimize_loop(&mut [Box::new(SimplifyExprRule{})], expr_arena, lp_arena, lp_top).unwrap();
let PythonScan {options: _, predicate: Some(predicate)} = lp_arena.take(lp_top) else {unreachable!()};
match super::super::pyarrow::predicate_to_pa(predicate, expr_arena, Default::default()) {
// we we able to create a pyarrow string, mutate the options
Some(eval_str) => {
options.predicate = Some(eval_str)
},
// we were not able to translate the predicate
// apply here
None => {
let lp = PythonScan { options, predicate: None };
return Ok(self.optional_apply_predicate(lp, vec![predicate], lp_arena, expr_arena))
}
}
}
Ok(PythonScan {options, predicate})
} else {
self.no_pushdown_restart_opt(PythonScan {options, predicate}, acc_predicates, lp_arena, expr_arena)
}
}
}
}
pub fn optimize(
&self,
logical_plan: ALogicalPlan,
lp_arena: &mut Arena<ALogicalPlan>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<ALogicalPlan> {
let acc_predicates = PlHashMap::new();
self.push_down(logical_plan, acc_predicates, lp_arena, expr_arena)
}
}