Path: blob/main/crates/polars-mem-engine/src/executors/sort.rs
6940 views
use polars_utils::format_pl_smallstr;12use super::*;34pub(crate) struct SortExec {5pub(crate) input: Box<dyn Executor>,6pub(crate) by_column: Vec<Arc<dyn PhysicalExpr>>,7pub(crate) slice: Option<(i64, usize)>,8pub(crate) sort_options: SortMultipleOptions,9}1011impl SortExec {12fn execute_impl(13&mut self,14state: &ExecutionState,15mut df: DataFrame,16) -> PolarsResult<DataFrame> {17state.should_stop()?;18df.as_single_chunk_par();1920let height = df.height();2122let by_columns = self23.by_column24.iter()25.enumerate()26.map(|(i, e)| {27let mut s = e.evaluate(&df, state)?.into_column();28// Polars core will try to set the sorted columns as sorted.29// This should only be done with simple col("foo") expressions,30// therefore we rename more complex expressions so that31// polars core does not match these.32if !matches!(e.as_expression(), Some(&Expr::Column(_))) {33s.rename(format_pl_smallstr!("_POLARS_SORT_BY_{i}"));34}35polars_ensure!(36s.len() == height,37ShapeMismatch: "sort expressions must have same \38length as DataFrame, got DataFrame height: {} and Series length: {}",39height, s.len()40);41Ok(s)42})43.collect::<PolarsResult<Vec<_>>>()?;4445df.sort_impl(by_columns, self.sort_options.clone(), self.slice)46}47}4849impl Executor for SortExec {50fn execute(&mut self, state: &mut ExecutionState) -> PolarsResult<DataFrame> {51#[cfg(debug_assertions)]52{53if state.verbose() {54eprintln!("run SortExec")55}56}57let df = self.input.execute(state)?;5859let profile_name = if state.has_node_timer() {60let by = self61.by_column62.iter()63.map(|s| Ok(s.to_field(df.schema())?.name))64.collect::<PolarsResult<Vec<_>>>()?;65let name = comma_delimited("sort".to_string(), &by);66Cow::Owned(name)67} else {68Cow::Borrowed("")69};7071if state.has_node_timer() {72let new_state = state.clone();73new_state.record(|| self.execute_impl(state, df), profile_name)74} else {75self.execute_impl(state, df)76}77}78}798081