|
| 1 | +# Copyright (c) QuantCo 2025-2025 |
| 2 | +# SPDX-License-Identifier: BSD-3-Clause |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from functools import partial |
| 6 | +from typing import TYPE_CHECKING, Literal, TypeVar, get_args, get_origin, overload |
| 7 | + |
| 8 | +import polars as pl |
| 9 | + |
| 10 | +from ._base_schema import BaseSchema |
| 11 | +from ._compat import pydantic, pydantic_core_schema |
| 12 | +from .exc import ValidationError |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from ._typing import DataFrame, LazyFrame |
| 16 | + |
| 17 | + |
| 18 | +_S = TypeVar("_S", bound=BaseSchema) |
| 19 | + |
| 20 | + |
| 21 | +def _dict_to_df(schema_type: type[BaseSchema], data: dict) -> pl.DataFrame: |
| 22 | + return pl.from_dict( |
| 23 | + data, |
| 24 | + schema=schema_type.polars_schema(), |
| 25 | + ) |
| 26 | + |
| 27 | + |
| 28 | +def _validate_df_schema(schema_type: type[_S], df: pl.DataFrame) -> DataFrame[_S]: |
| 29 | + try: |
| 30 | + return schema_type.validate(df, cast=False) |
| 31 | + except ValidationError as e: |
| 32 | + raise ValueError("DataFrame violates schema") from e |
| 33 | + |
| 34 | + |
| 35 | +def _serialize_df(df: pl.DataFrame) -> dict: |
| 36 | + return df.to_dict(as_series=False) |
| 37 | + |
| 38 | + |
| 39 | +@overload |
| 40 | +def get_pydantic_core_schema( |
| 41 | + source_type: type[DataFrame], |
| 42 | + _handler: pydantic.GetCoreSchemaHandler, |
| 43 | + lazy: Literal[False], |
| 44 | +) -> pydantic_core_schema.CoreSchema: ... |
| 45 | + |
| 46 | + |
| 47 | +@overload |
| 48 | +def get_pydantic_core_schema( |
| 49 | + source_type: type[LazyFrame], |
| 50 | + _handler: pydantic.GetCoreSchemaHandler, |
| 51 | + lazy: Literal[True], |
| 52 | +) -> pydantic_core_schema.CoreSchema: ... |
| 53 | + |
| 54 | + |
| 55 | +def get_pydantic_core_schema( |
| 56 | + source_type: type[DataFrame | LazyFrame], |
| 57 | + _handler: pydantic.GetCoreSchemaHandler, |
| 58 | + lazy: bool, |
| 59 | +) -> pydantic_core_schema.CoreSchema: |
| 60 | + # https://docs.pydantic.dev/2.11/concepts/types/#handling-custom-generic-classes |
| 61 | + origin = get_origin(source_type) |
| 62 | + if origin is None: |
| 63 | + # used as `x: dy.DataFrame` without schema |
| 64 | + raise TypeError("DataFrame must be parametrized with a schema") |
| 65 | + |
| 66 | + schema_type: type[BaseSchema] = get_args(source_type)[0] |
| 67 | + |
| 68 | + # accept a DataFrame, a LazyFrame, or a dict that is converted to a DataFrame |
| 69 | + # (-> output: DataFrame or LazyFrame) |
| 70 | + polars_schema = pydantic_core_schema.union_schema( |
| 71 | + [ |
| 72 | + pydantic_core_schema.is_instance_schema(pl.DataFrame), |
| 73 | + pydantic_core_schema.is_instance_schema(pl.LazyFrame), |
| 74 | + pydantic_core_schema.chain_schema( |
| 75 | + [ |
| 76 | + pydantic_core_schema.dict_schema(), |
| 77 | + pydantic_core_schema.no_info_plain_validator_function( |
| 78 | + partial(_dict_to_df, schema_type) |
| 79 | + ), |
| 80 | + ] |
| 81 | + ), |
| 82 | + ] |
| 83 | + ) |
| 84 | + |
| 85 | + to_lazy_schema = [] |
| 86 | + if lazy: |
| 87 | + # If the Pydantic field type is LazyFrame, add a step to convert |
| 88 | + # the model back to a LazyFrame. |
| 89 | + to_lazy_schema.append( |
| 90 | + pydantic_core_schema.no_info_plain_validator_function( |
| 91 | + lambda df: df.lazy(), |
| 92 | + ) |
| 93 | + ) |
| 94 | + |
| 95 | + return pydantic_core_schema.chain_schema( |
| 96 | + [ |
| 97 | + polars_schema, |
| 98 | + pydantic_core_schema.no_info_plain_validator_function( |
| 99 | + partial(_validate_df_schema, schema_type) |
| 100 | + ), |
| 101 | + *to_lazy_schema, |
| 102 | + ], |
| 103 | + serialization=pydantic_core_schema.plain_serializer_function_ser_schema( |
| 104 | + _serialize_df |
| 105 | + ), |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def get_pydantic_json_schema( |
| 110 | + handler: pydantic.GetJsonSchemaHandler, |
| 111 | +) -> pydantic.json_schema.JsonSchemaValue: |
| 112 | + from pydantic_core import core_schema |
| 113 | + |
| 114 | + # This could be made more sophisticated by actually reflecting the schema. |
| 115 | + return handler(core_schema.dict_schema()) |
0 commit comments