-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
mod.rs
2107 lines (1937 loc) · 70.3 KB
/
mod.rs
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Lazy variant of a [DataFrame].
#[cfg(feature = "python")]
mod python;
mod cached_arenas;
mod err;
#[cfg(not(target_arch = "wasm32"))]
mod exitable;
#[cfg(feature = "pivot")]
pub mod pivot;
#[cfg(any(
feature = "parquet",
feature = "ipc",
feature = "csv",
feature = "json"
))]
use std::path::Path;
use std::sync::{Arc, Mutex};
pub use anonymous_scan::*;
#[cfg(feature = "csv")]
pub use csv::*;
#[cfg(not(target_arch = "wasm32"))]
pub use exitable::*;
pub use file_list_reader::*;
#[cfg(feature = "ipc")]
pub use ipc::*;
#[cfg(feature = "json")]
pub use ndjson::*;
#[cfg(feature = "parquet")]
pub use parquet::*;
use polars_core::prelude::*;
use polars_expr::{create_physical_expr, ExpressionConversionState};
use polars_io::RowIndex;
use polars_mem_engine::{create_physical_plan, Executor};
use polars_ops::frame::JoinCoalesce;
pub use polars_plan::frame::{AllowedOptimizations, OptFlags};
use polars_plan::global::FETCH_ROWS;
use polars_utils::pl_str::PlSmallStr;
use crate::frame::cached_arenas::CachedArena;
#[cfg(feature = "streaming")]
use crate::physical_plan::streaming::insert_streaming_nodes;
use crate::prelude::*;
pub trait IntoLazy {
fn lazy(self) -> LazyFrame;
}
impl IntoLazy for DataFrame {
/// Convert the `DataFrame` into a `LazyFrame`
fn lazy(self) -> LazyFrame {
let lp = DslBuilder::from_existing_df(self).build();
LazyFrame {
logical_plan: lp,
opt_state: Default::default(),
cached_arena: Default::default(),
}
}
}
impl IntoLazy for LazyFrame {
fn lazy(self) -> LazyFrame {
self
}
}
/// Lazy abstraction over an eager `DataFrame`.
///
/// It really is an abstraction over a logical plan. The methods of this struct will incrementally
/// modify a logical plan until output is requested (via [`collect`](crate::frame::LazyFrame::collect)).
#[derive(Clone, Default)]
#[must_use]
pub struct LazyFrame {
pub logical_plan: DslPlan,
pub(crate) opt_state: OptFlags,
pub(crate) cached_arena: Arc<Mutex<Option<CachedArena>>>,
}
impl From<DslPlan> for LazyFrame {
fn from(plan: DslPlan) -> Self {
Self {
logical_plan: plan,
opt_state: OptFlags::default() | OptFlags::FILE_CACHING,
cached_arena: Default::default(),
}
}
}
impl LazyFrame {
pub(crate) fn from_inner(
logical_plan: DslPlan,
opt_state: OptFlags,
cached_arena: Arc<Mutex<Option<CachedArena>>>,
) -> Self {
Self {
logical_plan,
opt_state,
cached_arena,
}
}
pub(crate) fn get_plan_builder(self) -> DslBuilder {
DslBuilder::from(self.logical_plan)
}
fn get_opt_state(&self) -> OptFlags {
self.opt_state
}
fn from_logical_plan(logical_plan: DslPlan, opt_state: OptFlags) -> Self {
LazyFrame {
logical_plan,
opt_state,
cached_arena: Default::default(),
}
}
/// Get current optimizations.
pub fn get_current_optimizations(&self) -> OptFlags {
self.opt_state
}
/// Set allowed optimizations.
pub fn with_optimizations(mut self, opt_state: OptFlags) -> Self {
self.opt_state = opt_state;
self
}
/// Turn off all optimizations.
pub fn without_optimizations(self) -> Self {
self.with_optimizations(OptFlags::from_bits_truncate(0) | OptFlags::TYPE_COERCION)
}
/// Toggle projection pushdown optimization.
pub fn with_projection_pushdown(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::PROJECTION_PUSHDOWN, toggle);
self
}
/// Toggle cluster with columns optimization.
pub fn with_cluster_with_columns(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::CLUSTER_WITH_COLUMNS, toggle);
self
}
/// Toggle predicate pushdown optimization.
pub fn with_predicate_pushdown(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::PREDICATE_PUSHDOWN, toggle);
self
}
/// Toggle type coercion optimization.
pub fn with_type_coercion(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::TYPE_COERCION, toggle);
self
}
/// Toggle expression simplification optimization on or off.
pub fn with_simplify_expr(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::SIMPLIFY_EXPR, toggle);
self
}
/// Toggle common subplan elimination optimization on or off
#[cfg(feature = "cse")]
pub fn with_comm_subplan_elim(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::COMM_SUBPLAN_ELIM, toggle);
self
}
/// Toggle common subexpression elimination optimization on or off
#[cfg(feature = "cse")]
pub fn with_comm_subexpr_elim(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::COMM_SUBEXPR_ELIM, toggle);
self
}
/// Toggle slice pushdown optimization.
pub fn with_slice_pushdown(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::SLICE_PUSHDOWN, toggle);
self
}
/// Run nodes that are capably of doing so on the streaming engine.
pub fn with_streaming(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::STREAMING, toggle);
self
}
pub fn with_new_streaming(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::NEW_STREAMING, toggle);
self
}
/// Try to estimate the number of rows so that joins can determine which side to keep in memory.
pub fn with_row_estimate(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::ROW_ESTIMATE, toggle);
self
}
/// Run every node eagerly. This turns off multi-node optimizations.
pub fn _with_eager(mut self, toggle: bool) -> Self {
self.opt_state.set(OptFlags::EAGER, toggle);
self
}
/// Return a String describing the naive (un-optimized) logical plan.
pub fn describe_plan(&self) -> PolarsResult<String> {
Ok(self.clone().to_alp()?.describe())
}
/// Return a String describing the naive (un-optimized) logical plan in tree format.
pub fn describe_plan_tree(&self) -> PolarsResult<String> {
Ok(self.clone().to_alp()?.describe_tree_format())
}
// @NOTE: this is used because we want to set the `enable_fmt` flag of `optimize_with_scratch`
// to `true` for describe.
fn _describe_to_alp_optimized(mut self) -> PolarsResult<IRPlan> {
let (mut lp_arena, mut expr_arena) = self.get_arenas();
let node = self.optimize_with_scratch(&mut lp_arena, &mut expr_arena, &mut vec![], true)?;
Ok(IRPlan::new(node, lp_arena, expr_arena))
}
/// Return a String describing the optimized logical plan.
///
/// Returns `Err` if optimizing the logical plan fails.
pub fn describe_optimized_plan(&self) -> PolarsResult<String> {
Ok(self.clone()._describe_to_alp_optimized()?.describe())
}
/// Return a String describing the optimized logical plan in tree format.
///
/// Returns `Err` if optimizing the logical plan fails.
pub fn describe_optimized_plan_tree(&self) -> PolarsResult<String> {
Ok(self
.clone()
._describe_to_alp_optimized()?
.describe_tree_format())
}
/// Return a String describing the logical plan.
///
/// If `optimized` is `true`, explains the optimized plan. If `optimized` is `false,
/// explains the naive, un-optimized plan.
pub fn explain(&self, optimized: bool) -> PolarsResult<String> {
if optimized {
self.describe_optimized_plan()
} else {
self.describe_plan()
}
}
/// Add a sort operation to the logical plan.
///
/// Sorts the LazyFrame by the column name specified using the provided options.
///
/// # Example
///
/// Sort DataFrame by 'sepal_width' column:
/// ```rust
/// # use polars_core::prelude::*;
/// # use polars_lazy::prelude::*;
/// fn sort_by_a(df: DataFrame) -> LazyFrame {
/// df.lazy().sort(["sepal_width"], Default::default())
/// }
/// ```
/// Sort by a single column with specific order:
/// ```
/// # use polars_core::prelude::*;
/// # use polars_lazy::prelude::*;
/// fn sort_with_specific_order(df: DataFrame, descending: bool) -> LazyFrame {
/// df.lazy().sort(
/// ["sepal_width"],
/// SortMultipleOptions::new()
/// .with_order_descending(descending)
/// )
/// }
/// ```
/// Sort by multiple columns with specifying order for each column:
/// ```
/// # use polars_core::prelude::*;
/// # use polars_lazy::prelude::*;
/// fn sort_by_multiple_columns_with_specific_order(df: DataFrame) -> LazyFrame {
/// df.lazy().sort(
/// ["sepal_width", "sepal_length"],
/// SortMultipleOptions::new()
/// .with_order_descending_multi([false, true])
/// )
/// }
/// ```
/// See [`SortMultipleOptions`] for more options.
pub fn sort(self, by: impl IntoVec<PlSmallStr>, sort_options: SortMultipleOptions) -> Self {
let opt_state = self.get_opt_state();
let lp = self
.get_plan_builder()
.sort(by.into_vec().into_iter().map(col).collect(), sort_options)
.build();
Self::from_logical_plan(lp, opt_state)
}
/// Add a sort operation to the logical plan.
///
/// Sorts the LazyFrame by the provided list of expressions, which will be turned into
/// concrete columns before sorting.
///
/// See [`SortMultipleOptions`] for more options.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
///
/// /// Sort DataFrame by 'sepal_width' column
/// fn example(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .sort_by_exprs(vec![col("sepal_width")], Default::default())
/// }
/// ```
pub fn sort_by_exprs<E: AsRef<[Expr]>>(
self,
by_exprs: E,
sort_options: SortMultipleOptions,
) -> Self {
let by_exprs = by_exprs.as_ref().to_vec();
if by_exprs.is_empty() {
self
} else {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().sort(by_exprs, sort_options).build();
Self::from_logical_plan(lp, opt_state)
}
}
pub fn top_k<E: AsRef<[Expr]>>(
self,
k: IdxSize,
by_exprs: E,
sort_options: SortMultipleOptions,
) -> Self {
// this will optimize to top-k
self.sort_by_exprs(
by_exprs,
sort_options.with_order_reversed().with_nulls_last(true),
)
.slice(0, k)
}
pub fn bottom_k<E: AsRef<[Expr]>>(
self,
k: IdxSize,
by_exprs: E,
sort_options: SortMultipleOptions,
) -> Self {
// this will optimize to bottom-k
self.sort_by_exprs(by_exprs, sort_options.with_nulls_last(true))
.slice(0, k)
}
/// Reverse the `DataFrame` from top to bottom.
///
/// Row `i` becomes row `number_of_rows - i - 1`.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
///
/// fn example(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .reverse()
/// }
/// ```
pub fn reverse(self) -> Self {
self.select(vec![col(PlSmallStr::from_static("*")).reverse()])
}
/// Rename columns in the DataFrame.
///
/// `existing` and `new` are iterables of the same length containing the old and
/// corresponding new column names. Renaming happens to all `existing` columns
/// simultaneously, not iteratively. (In particular, all columns in `existing` must
/// already exist in the `LazyFrame` when `rename` is called.)
pub fn rename<I, J, T, S>(self, existing: I, new: J) -> Self
where
I: IntoIterator<Item = T>,
J: IntoIterator<Item = S>,
T: AsRef<str>,
S: AsRef<str>,
{
let iter = existing.into_iter();
let cap = iter.size_hint().0;
let mut existing_vec: Vec<PlSmallStr> = Vec::with_capacity(cap);
let mut new_vec: Vec<PlSmallStr> = Vec::with_capacity(cap);
// TODO! should this error if `existing` and `new` have different lengths?
// Currently, the longer of the two is truncated.
for (existing, new) in iter.zip(new) {
let existing = existing.as_ref();
let new = new.as_ref();
if new != existing {
existing_vec.push(existing.into());
new_vec.push(new.into());
}
}
self.map_private(DslFunction::Rename {
existing: existing_vec.into(),
new: new_vec.into(),
})
}
/// Removes columns from the DataFrame.
/// Note that it's better to only select the columns you need
/// and let the projection pushdown optimize away the unneeded columns.
///
/// If `strict` is `true`, then any given columns that are not in the schema will
/// give a [`PolarsError::ColumnNotFound`] error while materializing the [`LazyFrame`].
fn _drop<I, T>(self, columns: I, strict: bool) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Selector>,
{
let to_drop = columns.into_iter().map(|c| c.into()).collect();
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().drop(to_drop, strict).build();
Self::from_logical_plan(lp, opt_state)
}
/// Removes columns from the DataFrame.
/// Note that it's better to only select the columns you need
/// and let the projection pushdown optimize away the unneeded columns.
///
/// Any given columns that are not in the schema will give a [`PolarsError::ColumnNotFound`]
/// error while materializing the [`LazyFrame`].
pub fn drop<I, T>(self, columns: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Selector>,
{
self._drop(columns, true)
}
/// Removes columns from the DataFrame.
/// Note that it's better to only select the columns you need
/// and let the projection pushdown optimize away the unneeded columns.
///
/// If a column name does not exist in the schema, it will quietly be ignored.
pub fn drop_no_validate<I, T>(self, columns: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Selector>,
{
self._drop(columns, false)
}
/// Shift the values by a given period and fill the parts that will be empty due to this operation
/// with `Nones`.
///
/// See the method on [Series](polars_core::series::SeriesTrait::shift) for more info on the `shift` operation.
pub fn shift<E: Into<Expr>>(self, n: E) -> Self {
self.select(vec![col(PlSmallStr::from_static("*")).shift(n.into())])
}
/// Shift the values by a given period and fill the parts that will be empty due to this operation
/// with the result of the `fill_value` expression.
///
/// See the method on [Series](polars_core::series::SeriesTrait::shift) for more info on the `shift` operation.
pub fn shift_and_fill<E: Into<Expr>, IE: Into<Expr>>(self, n: E, fill_value: IE) -> Self {
self.select(vec![
col(PlSmallStr::from_static("*")).shift_and_fill(n.into(), fill_value.into())
])
}
/// Fill None values in the DataFrame with an expression.
pub fn fill_null<E: Into<Expr>>(self, fill_value: E) -> LazyFrame {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().fill_null(fill_value.into()).build();
Self::from_logical_plan(lp, opt_state)
}
/// Fill NaN values in the DataFrame with an expression.
pub fn fill_nan<E: Into<Expr>>(self, fill_value: E) -> LazyFrame {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().fill_nan(fill_value.into()).build();
Self::from_logical_plan(lp, opt_state)
}
/// Caches the result into a new LazyFrame.
///
/// This should be used to prevent computations running multiple times.
pub fn cache(self) -> Self {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().cache().build();
Self::from_logical_plan(lp, opt_state)
}
/// Cast named frame columns, resulting in a new LazyFrame with updated dtypes
pub fn cast(self, dtypes: PlHashMap<&str, DataType>, strict: bool) -> Self {
let cast_cols: Vec<Expr> = dtypes
.into_iter()
.map(|(name, dt)| {
let name = PlSmallStr::from_str(name);
if strict {
col(name).strict_cast(dt)
} else {
col(name).cast(dt)
}
})
.collect();
if cast_cols.is_empty() {
self.clone()
} else {
self.with_columns(cast_cols)
}
}
/// Cast all frame columns to the given dtype, resulting in a new LazyFrame
pub fn cast_all(self, dtype: DataType, strict: bool) -> Self {
self.with_columns(vec![if strict {
col(PlSmallStr::from_static("*")).strict_cast(dtype)
} else {
col(PlSmallStr::from_static("*")).cast(dtype)
}])
}
/// Fetch is like a collect operation, but it overwrites the number of rows read by every scan
/// operation. This is a utility that helps debug a query on a smaller number of rows.
///
/// Note that the fetch does not guarantee the final number of rows in the DataFrame.
/// Filter, join operations and a lower number of rows available in the scanned file influence
/// the final number of rows.
pub fn fetch(self, n_rows: usize) -> PolarsResult<DataFrame> {
FETCH_ROWS.with(|fetch_rows| fetch_rows.set(Some(n_rows)));
let res = self.collect();
FETCH_ROWS.with(|fetch_rows| fetch_rows.set(None));
res
}
pub fn optimize(
self,
lp_arena: &mut Arena<IR>,
expr_arena: &mut Arena<AExpr>,
) -> PolarsResult<Node> {
self.optimize_with_scratch(lp_arena, expr_arena, &mut vec![], false)
}
pub fn to_alp_optimized(mut self) -> PolarsResult<IRPlan> {
let (mut lp_arena, mut expr_arena) = self.get_arenas();
let node =
self.optimize_with_scratch(&mut lp_arena, &mut expr_arena, &mut vec![], false)?;
Ok(IRPlan::new(node, lp_arena, expr_arena))
}
pub fn to_alp(mut self) -> PolarsResult<IRPlan> {
let (mut lp_arena, mut expr_arena) = self.get_arenas();
let node = to_alp(
self.logical_plan,
&mut expr_arena,
&mut lp_arena,
&mut self.opt_state,
)?;
let plan = IRPlan::new(node, lp_arena, expr_arena);
Ok(plan)
}
pub(crate) fn optimize_with_scratch(
self,
lp_arena: &mut Arena<IR>,
expr_arena: &mut Arena<AExpr>,
scratch: &mut Vec<Node>,
enable_fmt: bool,
) -> PolarsResult<Node> {
#[allow(unused_mut)]
let mut opt_state = self.opt_state;
let streaming = self.opt_state.contains(OptFlags::STREAMING);
let new_streaming = self.opt_state.contains(OptFlags::NEW_STREAMING);
#[cfg(feature = "cse")]
if streaming && !new_streaming {
opt_state &= !OptFlags::COMM_SUBPLAN_ELIM;
}
// The new streaming engine can't deal with the way the common
// subexpression elimination adds length-incorrect with_columns.
#[cfg(feature = "cse")]
if new_streaming {
opt_state &= !OptFlags::COMM_SUBEXPR_ELIM;
}
let lp_top = optimize(
self.logical_plan,
opt_state,
lp_arena,
expr_arena,
scratch,
Some(&|expr, expr_arena| {
let phys_expr = create_physical_expr(
expr,
Context::Default,
expr_arena,
None,
&mut ExpressionConversionState::new(true, 0),
)
.ok()?;
let io_expr = phys_expr_to_io_expr(phys_expr);
Some(io_expr)
}),
)?;
if streaming {
#[cfg(feature = "streaming")]
{
insert_streaming_nodes(
lp_top,
lp_arena,
expr_arena,
scratch,
enable_fmt,
true,
opt_state.contains(OptFlags::ROW_ESTIMATE),
)?;
}
#[cfg(not(feature = "streaming"))]
{
_ = enable_fmt;
panic!("activate feature 'streaming'")
}
}
Ok(lp_top)
}
fn prepare_collect_post_opt<P>(
mut self,
check_sink: bool,
post_opt: P,
) -> PolarsResult<(ExecutionState, Box<dyn Executor>, bool)>
where
P: Fn(Node, &mut Arena<IR>, &mut Arena<AExpr>) -> PolarsResult<()>,
{
let (mut lp_arena, mut expr_arena) = self.get_arenas();
let mut scratch = vec![];
let lp_top =
self.optimize_with_scratch(&mut lp_arena, &mut expr_arena, &mut scratch, false)?;
post_opt(lp_top, &mut lp_arena, &mut expr_arena)?;
// sink should be replaced
let no_file_sink = if check_sink {
!matches!(lp_arena.get(lp_top), IR::Sink { .. })
} else {
true
};
let physical_plan = create_physical_plan(lp_top, &mut lp_arena, &expr_arena)?;
let state = ExecutionState::new();
Ok((state, physical_plan, no_file_sink))
}
// post_opt: A function that is called after optimization. This can be used to modify the IR jit.
pub fn _collect_post_opt<P>(self, post_opt: P) -> PolarsResult<DataFrame>
where
P: Fn(Node, &mut Arena<IR>, &mut Arena<AExpr>) -> PolarsResult<()>,
{
let (mut state, mut physical_plan, _) = self.prepare_collect_post_opt(false, post_opt)?;
physical_plan.execute(&mut state)
}
#[allow(unused_mut)]
fn prepare_collect(
self,
check_sink: bool,
) -> PolarsResult<(ExecutionState, Box<dyn Executor>, bool)> {
self.prepare_collect_post_opt(check_sink, |_, _, _| Ok(()))
}
/// Execute all the lazy operations and collect them into a [`DataFrame`].
///
/// The query is optimized prior to execution.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
///
/// fn example(df: DataFrame) -> PolarsResult<DataFrame> {
/// df.lazy()
/// .group_by([col("foo")])
/// .agg([col("bar").sum(), col("ham").mean().alias("avg_ham")])
/// .collect()
/// }
/// ```
pub fn collect(self) -> PolarsResult<DataFrame> {
#[cfg(feature = "new_streaming")]
{
let auto_new_streaming =
std::env::var("POLARS_AUTO_NEW_STREAMING").as_deref() == Ok("1");
if self.opt_state.contains(OptFlags::NEW_STREAMING) || auto_new_streaming {
// Try to run using the new streaming engine, falling back
// if it fails in a todo!() error if auto_new_streaming is set.
let mut new_stream_lazy = self.clone();
new_stream_lazy.opt_state |= OptFlags::NEW_STREAMING;
new_stream_lazy.opt_state &= !OptFlags::STREAMING;
let mut alp_plan = new_stream_lazy.to_alp_optimized()?;
let stream_lp_top = alp_plan.lp_arena.add(IR::Sink {
input: alp_plan.lp_top,
payload: SinkType::Memory,
});
let f = || {
polars_stream::run_query(
stream_lp_top,
alp_plan.lp_arena,
&mut alp_plan.expr_arena,
)
};
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(r) => return r,
Err(e) => {
// Fallback to normal engine if error is due to not being implemented
// and auto_new_streaming is set, otherwise propagate error.
if auto_new_streaming
&& e.downcast_ref::<&str>() == Some(&"not yet implemented")
{
if polars_core::config::verbose() {
eprintln!("caught unimplemented error in new streaming engine, falling back to normal engine");
}
} else {
std::panic::resume_unwind(e);
}
},
}
}
let mut alp_plan = self.to_alp_optimized()?;
let mut physical_plan = create_physical_plan(
alp_plan.lp_top,
&mut alp_plan.lp_arena,
&alp_plan.expr_arena,
)?;
let mut state = ExecutionState::new();
physical_plan.execute(&mut state)
}
#[cfg(not(feature = "new_streaming"))]
self._collect_post_opt(|_, _, _| Ok(()))
}
/// Profile a LazyFrame.
///
/// This will run the query and return a tuple
/// containing the materialized DataFrame and a DataFrame that contains profiling information
/// of each node that is executed.
///
/// The units of the timings are microseconds.
pub fn profile(self) -> PolarsResult<(DataFrame, DataFrame)> {
let (mut state, mut physical_plan, _) = self.prepare_collect(false)?;
state.time_nodes();
let out = physical_plan.execute(&mut state)?;
let timer_df = state.finish_timer()?;
Ok((out, timer_df))
}
/// Stream a query result into a parquet file. This is useful if the final result doesn't fit
/// into memory. This methods will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(feature = "parquet")]
pub fn sink_parquet(
self,
path: impl AsRef<Path>,
options: ParquetWriteOptions,
) -> PolarsResult<()> {
self.sink(
SinkType::File {
path: Arc::new(path.as_ref().to_path_buf()),
file_type: FileType::Parquet(options),
},
"collect().write_parquet()",
)
}
/// Stream a query result into a parquet file on an ObjectStore-compatible cloud service. This is useful if the final result doesn't fit
/// into memory, and where you do not want to write to a local file but to a location in the cloud.
/// This method will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(all(feature = "cloud_write", feature = "parquet"))]
pub fn sink_parquet_cloud(
self,
uri: String,
cloud_options: Option<polars_io::cloud::CloudOptions>,
parquet_options: ParquetWriteOptions,
) -> PolarsResult<()> {
self.sink(
SinkType::Cloud {
uri: Arc::new(uri),
cloud_options,
file_type: FileType::Parquet(parquet_options),
},
"collect().write_parquet()",
)
}
/// Stream a query result into an ipc/arrow file. This is useful if the final result doesn't fit
/// into memory. This methods will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(feature = "ipc")]
pub fn sink_ipc(self, path: impl AsRef<Path>, options: IpcWriterOptions) -> PolarsResult<()> {
self.sink(
SinkType::File {
path: Arc::new(path.as_ref().to_path_buf()),
file_type: FileType::Ipc(options),
},
"collect().write_ipc()",
)
}
/// Stream a query result into an ipc/arrow file on an ObjectStore-compatible cloud service.
/// This is useful if the final result doesn't fit
/// into memory, and where you do not want to write to a local file but to a location in the cloud.
/// This method will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(all(feature = "cloud_write", feature = "ipc"))]
pub fn sink_ipc_cloud(
mut self,
uri: String,
cloud_options: Option<polars_io::cloud::CloudOptions>,
ipc_options: IpcWriterOptions,
) -> PolarsResult<()> {
self.opt_state |= OptFlags::STREAMING;
self.logical_plan = DslPlan::Sink {
input: Arc::new(self.logical_plan),
payload: SinkType::Cloud {
uri: Arc::new(uri),
cloud_options,
file_type: FileType::Ipc(ipc_options),
},
};
let (mut state, mut physical_plan, is_streaming) = self.prepare_collect(true)?;
polars_ensure!(
is_streaming,
ComputeError: "cannot run the whole query in a streaming order; \
use `collect().write_ipc()` instead"
);
let _ = physical_plan.execute(&mut state)?;
Ok(())
}
/// Stream a query result into an csv file. This is useful if the final result doesn't fit
/// into memory. This methods will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(feature = "csv")]
pub fn sink_csv(self, path: impl AsRef<Path>, options: CsvWriterOptions) -> PolarsResult<()> {
self.sink(
SinkType::File {
path: Arc::new(path.as_ref().to_path_buf()),
file_type: FileType::Csv(options),
},
"collect().write_csv()",
)
}
/// Stream a query result into a json file. This is useful if the final result doesn't fit
/// into memory. This methods will return an error if the query cannot be completely done in a
/// streaming fashion.
#[cfg(feature = "json")]
pub fn sink_json(self, path: impl AsRef<Path>, options: JsonWriterOptions) -> PolarsResult<()> {
self.sink(
SinkType::File {
path: Arc::new(path.as_ref().to_path_buf()),
file_type: FileType::Json(options),
},
"collect().write_ndjson()` or `collect().write_json()",
)
}
#[cfg(any(
feature = "ipc",
feature = "parquet",
feature = "cloud_write",
feature = "csv",
feature = "json",
))]
fn sink(mut self, payload: SinkType, msg_alternative: &str) -> Result<(), PolarsError> {
self.opt_state |= OptFlags::STREAMING;
self.logical_plan = DslPlan::Sink {
input: Arc::new(self.logical_plan),
payload,
};
let (mut state, mut physical_plan, is_streaming) = self.prepare_collect(true)?;
polars_ensure!(
is_streaming,
ComputeError: format!("cannot run the whole query in a streaming order; \
use `{msg_alternative}` instead", msg_alternative=msg_alternative)
);
let _ = physical_plan.execute(&mut state)?;
Ok(())
}
/// Filter by some predicate expression.
///
/// The expression must yield boolean values.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
///
/// fn example(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .filter(col("sepal_width").is_not_null())
/// .select([col("sepal_width"), col("sepal_length")])
/// }
/// ```
pub fn filter(self, predicate: Expr) -> Self {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().filter(predicate).build();
Self::from_logical_plan(lp, opt_state)
}
/// Select (and optionally rename, with [`alias`](crate::dsl::Expr::alias)) columns from the query.
///
/// Columns can be selected with [`col`];
/// If you want to select all columns use `col(PlSmallStr::from_static("*"))`.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
///
/// /// This function selects column "foo" and column "bar".
/// /// Column "bar" is renamed to "ham".
/// fn example(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .select([col("foo"),
/// col("bar").alias("ham")])
/// }
///
/// /// This function selects all columns except "foo"
/// fn exclude_a_column(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .select([col(PlSmallStr::from_static("*")).exclude(["foo"])])
/// }
/// ```
pub fn select<E: AsRef<[Expr]>>(self, exprs: E) -> Self {
let exprs = exprs.as_ref().to_vec();
self.select_impl(
exprs,
ProjectionOptions {
run_parallel: true,
duplicate_check: true,
should_broadcast: true,
},
)
}
pub fn select_seq<E: AsRef<[Expr]>>(self, exprs: E) -> Self {
let exprs = exprs.as_ref().to_vec();
self.select_impl(
exprs,
ProjectionOptions {
run_parallel: false,
duplicate_check: true,
should_broadcast: true,
},
)
}
fn select_impl(self, exprs: Vec<Expr>, options: ProjectionOptions) -> Self {
let opt_state = self.get_opt_state();
let lp = self.get_plan_builder().project(exprs, options).build();
Self::from_logical_plan(lp, opt_state)
}
/// Performs a "group-by" on a `LazyFrame`, producing a [`LazyGroupBy`], which can subsequently be aggregated.
///
/// Takes a list of expressions to group on.
///
/// # Example
///
/// ```rust
/// use polars_core::prelude::*;
/// use polars_lazy::prelude::*;
/// use arrow::legacy::prelude::QuantileInterpolOptions;
///
/// fn example(df: DataFrame) -> LazyFrame {
/// df.lazy()
/// .group_by([col("date")])
/// .agg([