From 721e2efc05b30fa0d34df716c3e0910d06797a25 Mon Sep 17 00:00:00 2001 From: Oliver Borchert Date: Fri, 4 Dec 2026 13:29:43 -0800 Subject: [PATCH] refactor: Simplify codebase --- dataframely/_base_schema.py | 13 ++-- dataframely/_plugin.py | 2 +- dataframely/_polars.py | 9 +++ dataframely/_pydantic.py | 4 +- dataframely/collection/_base.py | 17 ++-- dataframely/collection/collection.py | 50 +++++------- dataframely/columns/_mixins.py | 29 ++++++- dataframely/columns/array.py | 23 +----- dataframely/columns/categorical.py | 2 - dataframely/columns/datetime.py | 108 ++++++++++++-------------- dataframely/columns/decimal.py | 2 - dataframely/columns/enum.py | 2 - dataframely/columns/float.py | 2 - dataframely/columns/integer.py | 2 - dataframely/columns/list.py | 23 +----- dataframely/columns/string.py | 2 - dataframely/columns/struct.py | 2 - dataframely/filter_result.py | 13 +--- dataframely/random.py | 10 +-- dataframely/schema.py | 14 ++-- src/polars_plugin/validation_error.rs | 4 +- 21 files changed, 139 insertions(+), 194 deletions(-) diff --git a/dataframely/_base_schema.py b/dataframely/_base_schema.py index 4fdc2a9f..8cd1dc5c 100644 --- a/dataframely/_base_schema.py +++ b/dataframely/_base_schema.py @@ -234,13 +234,13 @@ def _get_metadata_recursively(kls: type[object]) -> Metadata: @staticmethod def _get_metadata(source: Mapping[str, Any]) -> Metadata: result = Metadata() - for attr, value in { - k: v for k, v in source.items() if not k.startswith("__") - }.items(): + for attr, value in source.items(): + if attr.startswith("__"): + continue if isinstance(value, Column): if (col_name := value.alias or attr) in result.columns: raise ImplementationError(f"Column {col_name!r} is duplicated.") - result.columns[value.alias or attr] = value + result.columns[col_name] = value if isinstance(value, RuleFactory): # We must ensure that custom rules do not clash with internal rules. if attr == "primary_key": @@ -284,9 +284,10 @@ def column_names(cls) -> list[str]: def columns(cls) -> dict[str, Column]: """The column definitions of this schema.""" columns: dict[str, Column] = getattr(cls, _COLUMN_ATTR) - for name in columns.keys(): + schema_id = f"{cls.__module__}:{cls.__name__}" + for name, column in columns.items(): # Dynamically set the name and source schema of the columns. - columns[name]._bind(f"{cls.__module__}:{cls.__name__}", name) + column._bind(schema_id, name) return columns @classmethod diff --git a/dataframely/_plugin.py b/dataframely/_plugin.py index eb84f04a..3dd9cc8e 100644 --- a/dataframely/_plugin.py +++ b/dataframely/_plugin.py @@ -91,7 +91,7 @@ def all_rules_required( """ rules_list = [rules] if isinstance(rules, pl.Expr) else list(rules) num_rule_columns = len(rules_list) - data_columns_list = list(data_columns) if data_columns is not None else [] + data_columns_list = list(data_columns) return register_plugin_function( plugin_path=PLUGIN_PATH, function_name="all_rules_required", diff --git a/dataframely/_polars.py b/dataframely/_polars.py index e8c83ce3..99db53c7 100644 --- a/dataframely/_polars.py +++ b/dataframely/_polars.py @@ -41,6 +41,15 @@ def timedelta_matches_resolution(d: dt.timedelta, resolution: str) -> bool: return datetime_matches_resolution(EPOCH_DATETIME + d, resolution) +def read_parquet_metadata(source: Any, **kwargs: Any) -> dict[str, str]: + """Read parquet metadata, forwarding the relevant options of a read/scan call.""" + return pl.read_parquet_metadata( + source, + storage_options=kwargs.get("storage_options"), + credential_provider=kwargs.get("credential_provider"), + ) + + def collect_if(lf: pl.LazyFrame, condition: bool, **kwargs: Any) -> pl.LazyFrame: """Collect a lazy frame based on `condition`.""" if condition: diff --git a/dataframely/_pydantic.py b/dataframely/_pydantic.py index 7f8113f2..a2b885f5 100644 --- a/dataframely/_pydantic.py +++ b/dataframely/_pydantic.py @@ -104,7 +104,5 @@ def get_pydantic_core_schema( def get_pydantic_json_schema( handler: pydantic.GetJsonSchemaHandler, ) -> pydantic.json_schema.JsonSchemaValue: - from pydantic_core import core_schema - # This could be made more sophisticated by actually reflecting the schema. - return handler(core_schema.dict_schema()) + return handler(pydantic_core_schema.dict_schema()) diff --git a/dataframely/collection/_base.py b/dataframely/collection/_base.py index 61f3d672..09003155 100644 --- a/dataframely/collection/_base.py +++ b/dataframely/collection/_base.py @@ -209,7 +209,7 @@ def _get_metadata(source: dict[str, Any]) -> Metadata: annotate_func = source["__annotate_func__"] # __annotate_func__ can be None in Python 3.14 when a class # has no annotations or in certain metaclass scenarios - if annotate_func is not None and callable(annotate_func): + if callable(annotate_func): annotations = annotate_func(Format.VALUE) for attr, kls in annotations.items(): result.members[attr] = CollectionMeta._derive_member_info( @@ -217,10 +217,8 @@ def _get_metadata(source: dict[str, Any]) -> Metadata: ) # Get all filters by traversing the source - for attr, value in { - k: v for k, v in source.items() if not k.startswith("__") - }.items(): - if isinstance(value, Filter): + for attr, value in source.items(): + if not attr.startswith("__") and isinstance(value, Filter): result.filters[attr] = value return result @@ -375,14 +373,9 @@ def _failure_propagating_members(cls) -> set[str]: @classmethod def common_primary_key(cls) -> list[str]: """The primary keys shared by non ignored members of the collection.""" + schemas = cls.member_schemas() return sorted( - _common_primary_key( - [ - member.schema - for member in cls.members().values() - if not member.ignored_in_filters - ] - ) + _common_primary_key([schemas[name] for name in cls.non_ignored_members()]) ) @classmethod diff --git a/dataframely/collection/collection.py b/dataframely/collection/collection.py index a71a18e5..4efb52c2 100644 --- a/dataframely/collection/collection.py +++ b/dataframely/collection/collection.py @@ -13,10 +13,8 @@ import polars as pl -from dataframely._native import format_rule_failures from dataframely._plugin import all_rules_required -from dataframely._polars import FrameType, collect_all_if -from dataframely.config import Config +from dataframely._polars import FrameType, collect_all_if, read_parquet_metadata from dataframely.exc import ValidationError from dataframely.filter_result import FailureInfo from dataframely.random import Generator @@ -405,19 +403,12 @@ def validate( **kwargs, ) if any(len(failure) > 0 for failure in failures.values()): - errors: dict[str, str] = {} - for member, failure in failures.items(): - if len(failure) == 0: - continue - - counts = failure.counts() - errors[member] = format_rule_failures( - list(counts.items()), - failures_from=failure._df.select(counts.keys()), - examples_from=failure.invalid(), - primary_key_columns=cls.member_schemas()[member].primary_key(), - max_examples=Config.options["max_failure_examples"], - ) + member_schemas = cls.member_schemas() + errors = { + member: member_schemas[member]._format_failures(failure) + for member, failure in failures.items() + if len(failure) > 0 + } details = [ f" > Member '{member}' failed validation:\n" @@ -467,8 +458,8 @@ def validate( filter_names, null_is_valid=False, schema_name=name, - data_columns=cls.common_primary_key(), - primary_key_columns=cls.common_primary_key(), + data_columns=primary_key, + primary_key_columns=primary_key, ) ) .drop(filter_names) @@ -637,8 +628,6 @@ class HospitalInvoiceData(dy.Collection): name: filter.logic(result_cls).select(primary_key) for name, filter in filters.items() } - keep = collect_all_if(keep, not lazy, **kwargs) - drop: dict[str, pl.LazyFrame] = { f"{failure_propagating_member}|failure_propagation": ( failures[failure_propagating_member] @@ -647,7 +636,10 @@ class HospitalInvoiceData(dy.Collection): ) for failure_propagating_member in failure_propagating_members } - drop = collect_all_if(drop, not lazy, **kwargs) + # Keep and drop frames are independent: collect them together. + collected = collect_all_if({**keep, **drop}, not lazy, **kwargs) + keep = {name: collected[name] for name in keep} + drop = {name: collected[name] for name in drop} # Now we can iterate over the results and left-join onto each individual # filter to obtain independent boolean indicators of whether to keep the row. @@ -657,10 +649,10 @@ class HospitalInvoiceData(dy.Collection): if member_info.ignored_in_filters: continue - lf_with_eval = filtered.lazy() + lf_with_eval = filtered for name, filter_keep in keep.items(): lf_with_eval = lf_with_eval.join( - filter_keep.lazy().with_columns(pl.lit(True).alias(name)), + filter_keep.with_columns(pl.lit(True).alias(name)), on=primary_key, how="left", maintain_order="left", @@ -700,7 +692,7 @@ class HospitalInvoiceData(dy.Collection): failure = failures[member_name] filtered_failure = lf_with_eval.filter( ~pl.all_horizontal(all_filter_columns) - ).lazy() + ) # If we cast previously, `failure` and `filtered_failure` have different # dtypes for the source data: `failure` keeps the original dtypes while @@ -775,7 +767,7 @@ def join( may fail, especially if `primary_keys` does not contain all columns for all common primary keys. """ - if any(member.ignored_in_filters for member in self.members().values()): + if self.ignored_members(): raise ValueError( "The join operation is not supported for collections with members that are ignored in filters." ) @@ -995,11 +987,7 @@ def scan_parquet(cls, directory: str | Path, **kwargs: Any) -> Self: path = os.path.join(str(directory), f"{member}.parquet") if info.is_optional: try: - pl.read_parquet_metadata( - path, - storage_options=kwargs.get("storage_options"), - credential_provider=kwargs.get("credential_provider"), - ) + read_parquet_metadata(path, **kwargs) except FileNotFoundError: continue members[member] = pl.scan_parquet(path, **kwargs) @@ -1011,7 +999,7 @@ def scan_parquet(cls, directory: str | Path, **kwargs: Any) -> Self: @classmethod def _validate_lazy_param(cls, lazy: bool, /) -> None: - if lazy and any(not member.is_lazy for member in cls.members().values()): + if lazy and cls.eager_members(): raise ValueError( "Cannot use `lazy=True` on a collection with eager members." ) diff --git a/dataframely/columns/_mixins.py b/dataframely/columns/_mixins.py index 46305bb5..31a35d39 100644 --- a/dataframely/columns/_mixins.py +++ b/dataframely/columns/_mixins.py @@ -2,7 +2,8 @@ # SPDX-License-Identifier: BSD-3-Clause from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, Generic, Protocol, Self, TypeVar +from copy import copy +from typing import TYPE_CHECKING, Any, Generic, Protocol, Self, TypeVar, cast import polars as pl @@ -105,3 +106,29 @@ def validation_rules(self, expr: pl.Expr) -> dict[str, pl.Expr]: if self.is_in is not None: result["is_in"] = expr.is_in(self.is_in) return result + + +# -------------------------------- INNER COLUMN MIXIN -------------------------------- # + + +class InnerColumnMixin(Base): + """Mixin for container columns with a single ``inner`` column (lists, arrays).""" + + inner: "Column" + + def _bind(self, schema: str, name: str) -> None: + super()._bind(schema, name) + self.inner = copy(self.inner) + self.inner._bind(schema, f"{name}.inner") + + @property + def _python_type(self) -> Any: + inner_type = self.inner.pydantic_field() + return list[inner_type] # type: ignore + + def _attributes_match( + self, lhs: Any, rhs: Any, name: str, column_expr: pl.Expr + ) -> bool: + if name == "inner": + return cast("Column", lhs).matches(cast("Column", rhs), pl.element()) + return super()._attributes_match(lhs, rhs, name, column_expr) diff --git a/dataframely/columns/array.py b/dataframely/columns/array.py index 91e9e3ae..edfa5368 100644 --- a/dataframely/columns/array.py +++ b/dataframely/columns/array.py @@ -5,8 +5,7 @@ import math import warnings -from copy import copy -from typing import Any, cast +from typing import Any import polars as pl @@ -14,10 +13,11 @@ from dataframely.random import Generator from ._base import Check, Column +from ._mixins import InnerColumnMixin from .list import _list_primary_key_check -class Array(Column): +class Array(InnerColumnMixin, Column): """A fixed-shape array column.""" def __init__( @@ -77,11 +77,6 @@ def __init__( self.inner = inner self.shape = shape if isinstance(shape, tuple) else (shape,) - def _bind(self, schema: str, name: str) -> None: - super()._bind(schema, name) - self.inner = copy(self.inner) - self.inner._bind(schema, f"{name}.inner") - @property def dtype(self) -> pl.DataType: return pl.Array(self.inner.dtype, self.shape) @@ -138,11 +133,6 @@ def _arrow_nullability(self) -> tuple[bool, list[Any]]: nullability = (True, [nullability]) return (self.nullable, [nullability]) - @property - def _python_type(self) -> Any: - inner_type = self.inner.pydantic_field() - return list[inner_type] # type: ignore - def _pydantic_field_kwargs(self) -> dict[str, Any]: if len(self.shape) != 1: warnings.warn( @@ -165,10 +155,3 @@ def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series: all_elements.reshape((n, *self.shape)), null_probability=self._null_probability, ) - - def _attributes_match( - self, lhs: Any, rhs: Any, name: str, column_expr: pl.Expr - ) -> bool: - if name == "inner": - return cast(Column, lhs).matches(cast(Column, rhs), pl.element()) - return super()._attributes_match(lhs, rhs, name, column_expr) diff --git a/dataframely/columns/categorical.py b/dataframely/columns/categorical.py index b3ff00fa..16160547 100644 --- a/dataframely/columns/categorical.py +++ b/dataframely/columns/categorical.py @@ -45,8 +45,6 @@ def __init__( `items.inner.kind` for a field in a list of structs). nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, diff --git a/dataframely/columns/datetime.py b/dataframely/columns/datetime.py index 03831601..2f32755a 100644 --- a/dataframely/columns/datetime.py +++ b/dataframely/columns/datetime.py @@ -5,7 +5,8 @@ import datetime as dt import warnings -from typing import Any, cast +from collections.abc import Callable +from typing import Any, TypeVar, cast import polars as pl from polars._typing import TimeUnit @@ -24,6 +25,9 @@ from ._mixins import OrdinalMixin from ._utils import first_non_null, map_optional +T = TypeVar("T") + + # ------------------------------------------------------------------------------------ # @@ -51,8 +55,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, @@ -94,18 +96,15 @@ def __init__( offset_time = pl.Series([EPOCH_DATETIME]).dt.offset_by(resolution).dt.time() if offset_time.item() != dt.time(): raise ValueError("`resolution` is too fine for dates.") - if resolution is not None and min is not None: - if not date_matches_resolution(min, resolution): - raise ValueError("`min` does not match resolution.") - if resolution is not None and min_exclusive is not None: - if not date_matches_resolution(min_exclusive, resolution): - raise ValueError("`min_exclusive` does not match resolution.") - if resolution is not None and max is not None: - if not date_matches_resolution(max, resolution): - raise ValueError("`max` does not match resolution.") - if resolution is not None and max_exclusive is not None: - if not date_matches_resolution(max_exclusive, resolution): - raise ValueError("`max_exclusive` does not match resolution.") + if resolution is not None: + _check_bounds_match_resolution( + date_matches_resolution, + resolution, + min=min, + min_exclusive=min_exclusive, + max=max, + max_exclusive=max_exclusive, + ) super().__init__( nullable=nullable, @@ -192,8 +191,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, @@ -235,18 +232,15 @@ def __init__( offset_date = pl.Series([EPOCH_DATETIME]).dt.offset_by(resolution).dt.date() if offset_date.item() != EPOCH_DATETIME.date(): raise ValueError("`resolution` is too coarse for times.") - if resolution is not None and min is not None: - if not time_matches_resolution(min, resolution): - raise ValueError("`min` does not match resolution.") - if resolution is not None and min_exclusive is not None: - if not time_matches_resolution(min_exclusive, resolution): - raise ValueError("`min_exclusive` does not match resolution.") - if resolution is not None and max is not None: - if not time_matches_resolution(max, resolution): - raise ValueError("`max` does not match resolution.") - if resolution is not None and max_exclusive is not None: - if not time_matches_resolution(max_exclusive, resolution): - raise ValueError("`max_exclusive` does not match resolution.") + if resolution is not None: + _check_bounds_match_resolution( + time_matches_resolution, + resolution, + min=min, + min_exclusive=min_exclusive, + max=max, + max_exclusive=max_exclusive, + ) super().__init__( nullable=nullable, @@ -341,8 +335,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, @@ -384,18 +376,15 @@ def __init__( metadata: A dictionary of metadata to attach to the column. description: A human-readable description of the column. """ - if resolution is not None and min is not None: - if not datetime_matches_resolution(min, resolution): - raise ValueError("`min` does not match resolution.") - if resolution is not None and min_exclusive is not None: - if not datetime_matches_resolution(min_exclusive, resolution): - raise ValueError("`min_exclusive` does not match resolution.") - if resolution is not None and max is not None: - if not datetime_matches_resolution(max, resolution): - raise ValueError("`max` does not match resolution.") - if resolution is not None and max_exclusive is not None: - if not datetime_matches_resolution(max_exclusive, resolution): - raise ValueError("`max_exclusive` does not match resolution.") + if resolution is not None: + _check_bounds_match_resolution( + datetime_matches_resolution, + resolution, + min=min, + min_exclusive=min_exclusive, + max=max, + max_exclusive=max_exclusive, + ) super().__init__( nullable=nullable, @@ -506,8 +495,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, @@ -546,18 +533,15 @@ def __init__( metadata: A dictionary of metadata to attach to the column. description: A human-readable description of the column. """ - if resolution is not None and min is not None: - if not timedelta_matches_resolution(min, resolution): - raise ValueError("`min` does not match resolution.") - if resolution is not None and min_exclusive is not None: - if not timedelta_matches_resolution(min_exclusive, resolution): - raise ValueError("`min_exclusive` does not match resolution.") - if resolution is not None and max is not None: - if not timedelta_matches_resolution(max, resolution): - raise ValueError("`max` does not match resolution.") - if resolution is not None and max_exclusive is not None: - if not timedelta_matches_resolution(max_exclusive, resolution): - raise ValueError("`max_exclusive` does not match resolution.") + if resolution is not None: + _check_bounds_match_resolution( + timedelta_matches_resolution, + resolution, + min=min, + min_exclusive=min_exclusive, + max=max, + max_exclusive=max_exclusive, + ) super().__init__( nullable=nullable, @@ -629,6 +613,16 @@ def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series: # --------------------------------------- UTILS -------------------------------------- # +def _check_bounds_match_resolution( + matches_resolution: Callable[[T, str], bool], + resolution: str, + **bounds: T | None, +) -> None: + for name, bound in bounds.items(): + if bound is not None and not matches_resolution(bound, resolution): + raise ValueError(f"`{name}` does not match resolution.") + + def _next_date(t: dt.date, resolution: str | None) -> dt.date | None: result = _next_datetime(dt.datetime.combine(t, dt.time()), resolution) if result is None: diff --git a/dataframely/columns/decimal.py b/dataframely/columns/decimal.py index 52add35f..d82e28b9 100644 --- a/dataframely/columns/decimal.py +++ b/dataframely/columns/decimal.py @@ -44,8 +44,6 @@ def __init__( scale: Number of digits to the right of the decimal point in each number. nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, diff --git a/dataframely/columns/enum.py b/dataframely/columns/enum.py index 5fd8fbcd..713959a8 100644 --- a/dataframely/columns/enum.py +++ b/dataframely/columns/enum.py @@ -41,8 +41,6 @@ def __init__( string-valued enum. nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, diff --git a/dataframely/columns/float.py b/dataframely/columns/float.py index 33f5f1af..6448f298 100644 --- a/dataframely/columns/float.py +++ b/dataframely/columns/float.py @@ -45,8 +45,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, diff --git a/dataframely/columns/integer.py b/dataframely/columns/integer.py index 24c09190..f0ac511e 100644 --- a/dataframely/columns/integer.py +++ b/dataframely/columns/integer.py @@ -41,8 +41,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. If `True`, `nullable` is automatically set to `False`. unique: Whether this column must contain unique values. Unlike `primary_key`, diff --git a/dataframely/columns/list.py b/dataframely/columns/list.py index 637350e1..dce085d9 100644 --- a/dataframely/columns/list.py +++ b/dataframely/columns/list.py @@ -3,7 +3,6 @@ from __future__ import annotations -from copy import copy from itertools import chain from typing import Any, cast @@ -16,10 +15,11 @@ from dataframely.random import Generator from ._base import Check, Column +from ._mixins import InnerColumnMixin from .struct import Struct -class List(Column): +class List(InnerColumnMixin, Column): """A list column.""" def __init__( @@ -46,8 +46,6 @@ def __init__( `primary_key=True` set, the fields' settings do not take effect. nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. unique: Whether this column must contain unique values. Unlike `primary_key`, this checks uniqueness for this column independently. Multiple columns @@ -89,11 +87,6 @@ def __init__( self.min_length = min_length self.max_length = max_length - def _bind(self, schema: str, name: str) -> None: - super()._bind(schema, name) - self.inner = copy(self.inner) - self.inner._bind(schema, f"{name}.inner") - @property def dtype(self) -> pl.DataType: return pl.List(self.inner.dtype) @@ -148,11 +141,6 @@ def sqlalchemy_dtype(self, dialect: sa.Dialect) -> sa_TypeEngine: def _arrow_nullability(self) -> tuple[bool, list[Any]]: return (self.nullable, [self.inner._arrow_nullability()]) - @property - def _python_type(self) -> Any: - inner_type = self.inner.pydantic_field() - return list[inner_type] # type: ignore - def _pydantic_field_kwargs(self) -> dict[str, Any]: kwargs = super()._pydantic_field_kwargs() if self.min_length is not None: @@ -188,13 +176,6 @@ def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series: pl.Series(list_elements), null_probability=self._null_probability ) - def _attributes_match( - self, lhs: Any, rhs: Any, name: str, column_expr: pl.Expr - ) -> bool: - if name == "inner": - return cast(Column, lhs).matches(cast(Column, rhs), pl.element()) - return super()._attributes_match(lhs, rhs, name, column_expr) - def _list_primary_key_check( list_expr: ExprListNameSpace | ExprArrayNameSpace, inner: Column diff --git a/dataframely/columns/string.py b/dataframely/columns/string.py index a66d158a..99a39f54 100644 --- a/dataframely/columns/string.py +++ b/dataframely/columns/string.py @@ -38,8 +38,6 @@ def __init__( Args: nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. unique: Whether this column must contain unique values. Unlike `primary_key`, this checks uniqueness for this column independently. Multiple columns diff --git a/dataframely/columns/struct.py b/dataframely/columns/struct.py index 9dbfd328..39a5fcb6 100644 --- a/dataframely/columns/struct.py +++ b/dataframely/columns/struct.py @@ -39,8 +39,6 @@ def __init__( unique wrt. the struct fields that have `primary_key=True` set. nullable: Whether this column may contain null values. Explicitly set `nullable=True` if you want your column to be nullable. - In a future release, `nullable=False` will be the default if `nullable` - is not specified. primary_key: Whether this column is part of the primary key of the schema. unique: Whether this column must contain unique values. Unlike `primary_key`, this checks uniqueness for this column independently. Multiple columns diff --git a/dataframely/filter_result.py b/dataframely/filter_result.py index eab4c4da..10c45d26 100644 --- a/dataframely/filter_result.py +++ b/dataframely/filter_result.py @@ -11,6 +11,7 @@ import polars as pl from dataframely._base_schema import BaseSchema +from dataframely._polars import read_parquet_metadata from ._typing import DataFrame, LazyFrame @@ -232,11 +233,7 @@ def read_parquet(cls, source: str | Path | IO[bytes], **kwargs: Any) -> FailureI Returns: The failure info object. """ - metadata = pl.read_parquet_metadata( - source, - storage_options=kwargs.get("storage_options"), - credential_provider=kwargs.get("credential_provider"), - ) + metadata = read_parquet_metadata(source, **kwargs) return cls( pl.read_parquet(source, **kwargs).lazy(), rule_columns=json.loads(metadata["rule_columns"]), @@ -260,11 +257,7 @@ def scan_parquet(cls, source: str | Path | IO[bytes], **kwargs: Any) -> FailureI Raises: ValueError: If no appropriate metadata can be found. """ - metadata = pl.read_parquet_metadata( - source, - storage_options=kwargs.get("storage_options"), - credential_provider=kwargs.get("credential_provider"), - ) + metadata = read_parquet_metadata(source, **kwargs) if "rule_columns" not in metadata: raise ValueError( "The parquet metadata does not provide the `rule_columns` key." diff --git a/dataframely/random.py b/dataframely/random.py index ed4b1898..58ce032b 100644 --- a/dataframely/random.py +++ b/dataframely/random.py @@ -396,17 +396,11 @@ def sample_duration( if not timedelta_matches_resolution(max, resolution): raise ValueError("`max` does not match resolution.") - min_microseconds = ( - min.microseconds + (min.seconds + min.days * SECONDS_PER_DAY) * 10**6 - ) - max_microseconds = ( - max.microseconds + (max.seconds + max.days * SECONDS_PER_DAY) * 10**6 - ) result = ( self.sample_int( n, - min=min_microseconds, - max=max_microseconds, + min=min // dt.timedelta(microseconds=1), + max=max // dt.timedelta(microseconds=1), null_probability=null_probability, ) ).cast(pl.Duration(time_unit=time_unit)) diff --git a/dataframely/schema.py b/dataframely/schema.py index 8d8d8e82..27f34664 100644 --- a/dataframely/schema.py +++ b/dataframely/schema.py @@ -420,13 +420,14 @@ def _sample_filter( # If we have missing value indices, we need to sample new values for the # indices that overlap with indices in the remaining values and replace them # in the sampled data frame. + row_index_map = remaining_values.select("__row_index__").with_row_index( + "__row_index_loop__" + ) for name, indices in missing_value_indices.items(): remapped_indices = ( indices.to_frame("idx") .join( - remaining_values.select("__row_index__").with_row_index( - "__row_index_loop__" - ), + row_index_map, left_on="idx", right_on="__row_index__", ) @@ -460,14 +461,13 @@ def _sample_filter( ) evaluated = combined_dataframe.lazy().pipe(cls._with_evaluated_rules, rules) - filtered = evaluated.filter(_COLUMN_VALID).select(cls.column_names()) concat_values = pl.concat([used_values, remaining_values]) if concat_values.height == 0: # If we didn't provide any values, we can simply return empty data frames # with the right schema for used and remaining values return ( - filtered.collect(), + evaluated.filter(_COLUMN_VALID).select(cls.column_names()).collect(), concat_values, concat_values, cls._failure_info(evaluated, rules), @@ -477,9 +477,9 @@ def _sample_filter( # operation as the ordering of the custom values is guaranteed to be the # same: `previous_result` and `used_values` contain the same values. Similarly, # `sampled` and `remaining_values` have the same values. - filtered_df, evaluated_df = pl.collect_all([filtered, evaluated]) + evaluated_df = evaluated.collect() return ( - filtered_df, + evaluated_df.filter(_COLUMN_VALID).select(cls.column_names()), concat_values.filter(evaluated_df.get_column(_COLUMN_VALID)), concat_values.filter(~evaluated_df.get_column(_COLUMN_VALID)), cls._failure_info(evaluated_df.lazy(), rules), diff --git a/src/polars_plugin/validation_error.rs b/src/polars_plugin/validation_error.rs index e13bdbc8..e7e93bdd 100644 --- a/src/polars_plugin/validation_error.rs +++ b/src/polars_plugin/validation_error.rs @@ -3,13 +3,11 @@ use std::ops::Not; use itertools::Itertools; use num_format::{Locale, ToFormattedString}; use polars::prelude::*; -use pyo3::{create_exception, exceptions::PyException, prelude::*}; +use pyo3::prelude::*; use pyo3_polars::PyDataFrame; use super::RuleFailure; -create_exception!(exc, PyRuleValidationError, PyException); - /* -------------------------------------- VALIDATION ERROR ------------------------------------- */ pub struct RuleValidationError<'a> {