polars-plan 0.54.1

Lazy query engine for the Polars DataFrame library
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
use core::fmt;
use std::fmt::Write;

use polars_core::error::{PolarsResult, feature_gated, polars_bail, polars_ensure};
use polars_core::prelude::{DataType, Field};
use polars_core::schema::Schema;
use polars_utils::arena::Arena;
use polars_utils::pl_str::PlSmallStr;

use super::{
    ArrayDataTypeFunction, DataTypeFunction, DataTypeSelector, Expr, StructDataTypeFunction,
};
use crate::frame::OptFlags;
use crate::plans::{ExprToIRContext, ToFieldContext, expand_expression, to_expr_ir};

#[derive(Clone, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
pub enum DataTypeExpr {
    Literal(DataType),
    OfExpr(Box<Expr>),

    InnerDataType {
        input: Box<DataTypeExpr>,
        validation: Option<SequenceKind>,
    },

    Int(Box<DataTypeExpr>, IntDataTypeExpr),
    Struct(Box<DataTypeExpr>, StructDataTypeExpr),

    // Constructors for nested types
    WrapInList(Box<DataTypeExpr>),
    WrapInArray(Box<DataTypeExpr>, usize),
    StructWithFields(Vec<(PlSmallStr, DataTypeExpr)>),

    /// Invariant, must be directly materialized in `map_elements/map_batches`
    /// After materialization it becomes `OfExpr<self>`
    SelfDtype,
}

#[derive(Clone, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
pub enum SequenceKind {
    List,
    Array,
}

#[derive(PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
pub enum IntDataTypeExpr {
    ToUnsigned,
    ToSigned,
}

#[derive(PartialEq, Clone, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
pub enum StructDataTypeExpr {
    FieldDataTypeByIndex(i64),
    FieldDataTypeByName(PlSmallStr),
}

#[recursive::recursive]
fn into_datatype_impl(
    dt_expr: DataTypeExpr,
    schema: &Schema,
    self_dtype: Option<&DataType>,
) -> PolarsResult<DataType> {
    use DataTypeExpr as D;
    let dtype = match dt_expr {
        D::Literal(dt) => dt,
        D::OfExpr(expr) => {
            let mut out = Vec::with_capacity(1);
            expand_expression(
                expr.as_ref(),
                &Default::default(),
                schema,
                &mut out,
                &mut OptFlags::default(),
            )?;
            polars_ensure!(
                out.len() == 1,
                InvalidOperation: "DataType expression are not allowed to expand to more than 1 expression"
            );

            let expr = out.pop().unwrap();
            let mut arena = Arena::new();
            let mut ctx = ExprToIRContext::new(&mut arena, schema);
            let e = to_expr_ir(expr, &mut ctx)?;
            let dtype = arena
                .get(e.node())
                .to_dtype(&ToFieldContext::new(&arena, schema))?;
            let dtype = dtype.materialize_unknown(true)?;
            polars_ensure!(!dtype.contains_unknown(),InvalidOperation:"DataType expression is not allowed to instantiate to `unknown`");
            dtype
        },
        D::SelfDtype => match self_dtype {
            None => polars_bail!(
                InvalidOperation: "'self_dtype' cannot be used in this context",
            ),
            Some(self_dtype) => self_dtype.clone(),
        },
        D::InnerDataType { input, validation } => {
            let dt = into_datatype_impl(*input, schema, self_dtype)?;
            let Some(validation) = validation else {
                return dt.try_into_inner_dtype();
            };

            match (dt, validation) {
                #[cfg(feature = "dtype-array")]
                (DataType::Array(inner, _), SequenceKind::Array) => *inner,
                (DataType::List(inner), SequenceKind::List) => *inner,
                (dt, SequenceKind::Array) => {
                    polars_bail!(SchemaMismatch: "expected `arr` type but got `{dt}`")
                },
                (dt, SequenceKind::List) => {
                    polars_bail!(SchemaMismatch: "expected `list` type but got `{dt}`")
                },
            }
        },
        D::Int(dt_expr, f) => {
            use DataType as DT;
            let dt = into_datatype_impl(*dt_expr, schema, self_dtype)?;
            polars_ensure!(dt.is_integer(), InvalidOperation: "`{dt}` is not an integer type");
            match f {
                IntDataTypeExpr::ToUnsigned => match dt {
                    DT::UInt8 | DT::Int8 => DT::UInt8,
                    DT::UInt16 | DT::Int16 => DT::UInt16,
                    DT::UInt32 | DT::Int32 => DT::UInt32,
                    DT::UInt64 | DT::Int64 => DT::UInt64,
                    DT::Int128 => {
                        polars_bail!(InvalidOperation: "`int128` has no unsigned equivalent")
                    },
                    _ => unreachable!(),
                },
                IntDataTypeExpr::ToSigned => {
                    use DataType as DT;
                    match dt {
                        DT::UInt8 | DT::Int8 => DT::Int8,
                        DT::UInt16 | DT::Int16 => DT::Int16,
                        DT::UInt32 | DT::Int32 => DT::Int32,
                        DT::UInt64 | DT::Int64 => DT::Int64,
                        DT::Int128 => DT::Int128,
                        _ => unreachable!(),
                    }
                },
            }
        },
        D::Struct(dt_expr, f) => {
            let fields: Vec<Field> = match into_datatype_impl(*dt_expr, schema, self_dtype)? {
                #[cfg(feature = "dtype-struct")]
                DataType::Struct(fields) => fields,
                dt => polars_bail!(InvalidOperation: "`{dt}` is not a `struct`"),
            };
            match f {
                StructDataTypeExpr::FieldDataTypeByIndex(idx) => {
                    let offset = if idx < 0 {
                        let offset = usize::try_from(idx.abs_diff(0)).unwrap();
                        polars_ensure!(
                            offset <= fields.len(),
                            InvalidOperation: "`struct` has {} fields, but field {idx} was requested",
                            fields.len()
                        );
                        fields.len() - offset
                    } else {
                        let offset = usize::try_from(idx).unwrap();
                        polars_ensure!(
                            offset < fields.len(),
                            InvalidOperation: "`struct` has {} fields, but field {idx} was requested",
                            fields.len()
                        );
                        offset
                    };

                    fields.into_iter().nth(offset).unwrap().dtype
                },
                StructDataTypeExpr::FieldDataTypeByName(name) => {
                    let Some(field) = fields.into_iter().find(|f| f.name() == &name) else {
                        polars_bail!(
                            InvalidOperation: "`struct` does not have field '{name}'",
                        );
                    };
                    field.dtype
                },
            }
        },
        D::WrapInList(dt_expr) => {
            DataType::List(Box::new(into_datatype_impl(*dt_expr, schema, self_dtype)?))
        },
        D::WrapInArray(dt_expr, width) => feature_gated!("dtype-array", {
            DataType::Array(
                Box::new(into_datatype_impl(*dt_expr, schema, self_dtype)?),
                width,
            )
        }),
        D::StructWithFields(field_exprs) => feature_gated!("dtype-struct", {
            use polars_core::prelude::{Field, InitHashMaps, PlHashSet};
            let mut seen = PlHashSet::with_capacity(field_exprs.len());
            let mut fields = Vec::with_capacity(field_exprs.len());
            for (name, dt_expr) in field_exprs {
                let dt = into_datatype_impl(dt_expr, schema, self_dtype)?;
                if !seen.insert(name.clone()) {
                    polars_bail!(
                        InvalidOperation:
                        "`struct` cannot have duplicate field name `{name}`"
                    );
                }
                fields.push(Field::new(name, dt));
            }
            DataType::Struct(fields)
        }),
    };

    Ok(dtype)
}

impl DataTypeExpr {
    pub fn into_datatype(self, schema: &Schema) -> PolarsResult<DataType> {
        self.into_datatype_with_opt_self(schema, None)
    }

    pub fn into_datatype_with_self(
        self,
        schema: &Schema,
        self_dtype: &DataType,
    ) -> PolarsResult<DataType> {
        self.into_datatype_with_opt_self(schema, Some(self_dtype))
    }

    pub fn into_datatype_with_opt_self(
        self,
        schema: &Schema,
        self_dtype: Option<&DataType>,
    ) -> PolarsResult<DataType> {
        into_datatype_impl(self, schema, self_dtype)
    }

    pub fn as_literal(&self) -> Option<&DataType> {
        match self {
            Self::Literal(dt) => Some(dt),
            _ => None,
        }
    }

    pub fn into_literal(self) -> Option<DataType> {
        match self {
            Self::Literal(dt) => Some(dt),
            _ => None,
        }
    }

    pub fn inner_dtype(self) -> Self {
        Self::InnerDataType {
            input: Box::new(self),
            validation: None,
        }
    }

    pub fn equals(self, other: Self) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Eq(self, other))
    }

    pub fn display(self) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Display(self))
    }

    pub fn matches(self, selector: DataTypeSelector) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Matches(self, selector))
    }

    pub fn wrap_in_list(self) -> Self {
        Self::WrapInList(Box::new(self))
    }

    pub fn wrap_in_array(self, width: usize) -> Self {
        Self::WrapInArray(Box::new(self), width)
    }

    pub fn default_value(self, n: usize, numeric_to_one: bool, num_list_values: usize) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::DefaultValue {
            dt_expr: self,
            n,
            numeric_to_one,
            num_list_values,
        })
    }

    pub fn int(self) -> DataTypeExprIntNameSpace {
        DataTypeExprIntNameSpace(self)
    }

    pub fn list(self) -> DataTypeExprListNameSpace {
        DataTypeExprListNameSpace(self)
    }

    pub fn arr(self) -> DataTypeExprArrNameSpace {
        DataTypeExprArrNameSpace(self)
    }

    pub fn struct_(self) -> DataTypeExprStructNameSpace {
        DataTypeExprStructNameSpace(self)
    }
}

impl fmt::Debug for DataTypeExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Literal(data_type) => data_type.fmt(f),
            Self::OfExpr(expr) => write!(f, "dtype_of({expr:?})"),
            Self::SelfDtype => write!(f, "self_dtype()"),
            Self::InnerDataType { input, validation } => {
                fmt::Debug::fmt(input.as_ref(), f)?;
                match validation {
                    None => {},
                    Some(SequenceKind::List) => f.write_str(".list")?,
                    Some(SequenceKind::Array) => f.write_str(".arr")?,
                }
                f.write_str(".inner()")
            },
            Self::Int(dt_expr, t) => {
                fmt::Debug::fmt(dt_expr.as_ref(), f)?;
                match t {
                    IntDataTypeExpr::ToUnsigned => f.write_str(".to_unsigned_integer()"),
                    IntDataTypeExpr::ToSigned => f.write_str(".to_signed_integer()"),
                }
            },
            Self::Struct(dt_expr, t) => {
                fmt::Debug::fmt(dt_expr.as_ref(), f)?;
                f.write_str(".struct")?;
                match t {
                    StructDataTypeExpr::FieldDataTypeByIndex(i) => {
                        write!(f, "[{i}]")
                    },
                    StructDataTypeExpr::FieldDataTypeByName(name) => {
                        write!(f, "[{name}]")
                    },
                }
            },
            Self::WrapInList(dt_expr) => {
                write!(f, "{dt_expr:?}.wrap_in_list()")
            },
            Self::WrapInArray(dt_expr, width) => {
                write!(f, "{dt_expr:?}.wrap_in_array(width={width})")
            },
            Self::StructWithFields(field_exprs) => {
                f.write_str("struct_with_fields({")?;
                if let Some((field_name, field_expr)) = field_exprs.first() {
                    write!(f, " {field_name}: {field_expr:?}")?;
                    for (field_name, field_expr) in &field_exprs[1..] {
                        write!(f, ", {field_name}: {field_expr:?}")?;
                    }
                    f.write_char(' ')?;
                }
                f.write_str("})")
            },
        }
    }
}

impl From<DataType> for DataTypeExpr {
    fn from(value: DataType) -> Self {
        Self::Literal(value)
    }
}

pub struct DataTypeExprIntNameSpace(DataTypeExpr);
pub struct DataTypeExprListNameSpace(DataTypeExpr);
pub struct DataTypeExprArrNameSpace(DataTypeExpr);
pub struct DataTypeExprStructNameSpace(DataTypeExpr);

impl DataTypeExprIntNameSpace {
    #[expect(clippy::wrong_self_convention)]
    pub fn to_unsigned(self) -> DataTypeExpr {
        DataTypeExpr::Int(Box::new(self.0), IntDataTypeExpr::ToUnsigned)
    }

    #[expect(clippy::wrong_self_convention)]
    pub fn to_signed(self) -> DataTypeExpr {
        DataTypeExpr::Int(Box::new(self.0), IntDataTypeExpr::ToSigned)
    }
}

impl DataTypeExprListNameSpace {
    pub fn inner_dtype(self) -> DataTypeExpr {
        DataTypeExpr::InnerDataType {
            input: Box::new(self.0),
            validation: Some(SequenceKind::List),
        }
    }
}

impl DataTypeExprArrNameSpace {
    pub fn inner_dtype(self) -> DataTypeExpr {
        DataTypeExpr::InnerDataType {
            input: Box::new(self.0),
            validation: Some(SequenceKind::Array),
        }
    }

    pub fn width(self) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Array(
            self.0,
            ArrayDataTypeFunction::Width,
        ))
    }

    pub fn shape(self) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Array(
            self.0,
            ArrayDataTypeFunction::Shape,
        ))
    }
}

impl DataTypeExprStructNameSpace {
    pub fn field_dtype_by_index(self, index: i64) -> DataTypeExpr {
        DataTypeExpr::Struct(
            Box::new(self.0),
            StructDataTypeExpr::FieldDataTypeByIndex(index),
        )
    }

    pub fn field_dtype_by_name(self, name: &str) -> DataTypeExpr {
        DataTypeExpr::Struct(
            Box::new(self.0),
            StructDataTypeExpr::FieldDataTypeByName(name.into()),
        )
    }

    pub fn field_names(self) -> Expr {
        Expr::DataTypeFunction(DataTypeFunction::Struct(
            self.0,
            StructDataTypeFunction::FieldNames,
        ))
    }
}