Skip to content

Commit c7e98f7

Browse files
DariusHQjschoedl
andauthored
Add the polars export format (#1727)
* Add the polars export format * Shorten the polars exporter docstrings * Name the schema in the polars decimal-precision error A decimal wider than 38 digits now fails with "Schema 'orders': Polars decimals hold at most 38 digits, but 'amount' has a precision of 40.", so the field can be found when several schemas share a field name. * Use the Polars logo on the polars export docs * Let the logical type decide the width of platform-dependent polars types tinyint, smallint, int, integer, float, float4 and real no longer map to a fixed width, since BigQuery and Snowflake read them differently: they now export as Int64 or Float64 from the logical type, as int8 already did. --------- Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent 14fc3fa commit c7e98f7

22 files changed

Lines changed: 822 additions & 9 deletions

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
- - `datacontract dbt sync` inlines the definitions a contract's properties link to, like `lint`, `test` and `export` (#1765)
1111

12+
### Added
13+
- `datacontract export polars`: export the schemas as Polars `pl.Schema` definitions (#1552)
14+
1215
## [1.2.9] - 2026-10-30
1316

1417
### Added

‎datacontract/command_export.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,24 @@ def export_spark(
537537
_export(ExportFormat.spark, location, output, server, schema_name, schema, inline_references=inline_references)
538538

539539

540+
@export_app.command(
541+
name="polars",
542+
epilog="Example: datacontract export polars datacontract.yaml --output schema.py",
543+
)
544+
def export_polars(
545+
location: location_arg = "datacontract.yaml",
546+
output: output_option = None,
547+
server: server_option = None,
548+
schema_name: schema_name_option = "all",
549+
schema: schema_option = None,
550+
inline_references: inline_references_option = True,
551+
debug: debug_option = None,
552+
):
553+
"""Export a data contract to Polars schemas."""
554+
enable_debug_logging(debug)
555+
_export(ExportFormat.polars, location, output, server, schema_name, schema, inline_references=inline_references)
556+
557+
540558
@export_app.command(
541559
name="sqlalchemy",
542560
epilog="Example: datacontract export sqlalchemy datacontract.yaml --output models.py",

‎datacontract/export/exporter.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ class ExportFormat(str, Enum):
7272
bigquery = "bigquery"
7373
dbml = "dbml"
7474
spark = "spark"
75+
polars = "polars"
7576
sqlalchemy = "sqlalchemy"
7677
data_caterer = "data-caterer"
7778
dcs = "dcs"

‎datacontract/export/exporter_factory.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,12 @@ def load_module_class(module_path, class_name):
173173
class_name="SparkExporter",
174174
)
175175

176+
exporter_factory.register_lazy_exporter(
177+
name=ExportFormat.polars,
178+
module_path="datacontract.export.polars_exporter",
179+
class_name="PolarsExporter",
180+
)
181+
176182
exporter_factory.register_lazy_exporter(
177183
name=ExportFormat.sqlalchemy,
178184
module_path="datacontract.export.sqlalchemy_exporter",
Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
"""Export a data contract as a Python module of Polars schemas, as text, so polars need not be installed."""
2+
3+
import json
4+
import keyword
5+
import re
6+
from dataclasses import dataclass
7+
from typing import List, Optional, Tuple
8+
9+
from open_data_contract_standard.model import OpenDataContractStandard, SchemaProperty
10+
11+
from datacontract.export.exporter import Exporter
12+
from datacontract.model.map_type import get_map_key, get_map_value, is_map
13+
from datacontract.model.vector_type import is_vector, vector_dimensions, vector_element_type
14+
15+
# Polars decimals are 128-bit integers with a scale, so they hold at most 38 digits.
16+
_MAX_DECIMAL_PRECISION = 38
17+
18+
_INTEGER_FORMATS = {
19+
"i8": "Int8",
20+
"i16": "Int16",
21+
"i32": "Int32",
22+
"i64": "Int64",
23+
"i128": "Int128",
24+
"u8": "UInt8",
25+
"u16": "UInt16",
26+
"u32": "UInt32",
27+
"u64": "UInt64",
28+
"u128": "UInt128",
29+
}
30+
31+
_NUMBER_FORMATS = {
32+
"f32": "Float32",
33+
"f64": "Float64",
34+
}
35+
36+
# Polars has no bfloat16; Float32 holds every bfloat16 value exactly. A binary
37+
# vector has one bit per element.
38+
_VECTOR_ELEMENT_TYPES = {
39+
"bfloat16": "Float32",
40+
"binary": "Boolean",
41+
"float16": "Float16",
42+
"float32": "Float32",
43+
"float64": "Float64",
44+
"int8": "Int8",
45+
"uint8": "UInt8",
46+
}
47+
48+
# Physical type names, without their parameters, that mean the same width on every
49+
# platform. Left out: `int8`, 64 bits in Postgres and DuckDB but 8 in ClickHouse;
50+
# `tinyint`, `smallint`, `int` and `integer`, INT64 in BigQuery and NUMBER(38,0) in
51+
# Snowflake; and `float`, `float4` and `real`, 64 bits in Snowflake.
52+
_PHYSICAL_TYPES = {
53+
"string": "String",
54+
"varchar": "String",
55+
"text": "String",
56+
"char": "String",
57+
"nvarchar": "String",
58+
"nchar": "String",
59+
"character varying": "String",
60+
"boolean": "Boolean",
61+
"bool": "Boolean",
62+
"int1": "Int8",
63+
"int2": "Int16",
64+
"int16": "Int16",
65+
"short": "Int16",
66+
"int4": "Int32",
67+
"int32": "Int32",
68+
"mediumint": "Int32",
69+
"bigint": "Int64",
70+
"long": "Int64",
71+
"int64": "Int64",
72+
"int128": "Int128",
73+
"hugeint": "Int128",
74+
"uint8": "UInt8",
75+
"utinyint": "UInt8",
76+
"tinyint unsigned": "UInt8",
77+
"uint16": "UInt16",
78+
"usmallint": "UInt16",
79+
"smallint unsigned": "UInt16",
80+
"uint32": "UInt32",
81+
"uinteger": "UInt32",
82+
"mediumint unsigned": "UInt32",
83+
"int unsigned": "UInt32",
84+
"integer unsigned": "UInt32",
85+
"uint64": "UInt64",
86+
"ubigint": "UInt64",
87+
"bigint unsigned": "UInt64",
88+
"uint128": "UInt128",
89+
"uhugeint": "UInt128",
90+
"float16": "Float16",
91+
"float32": "Float32",
92+
"double": "Float64",
93+
"double precision": "Float64",
94+
"float8": "Float64",
95+
"float64": "Float64",
96+
"date": "Date",
97+
"time": "Time",
98+
"binary": "Binary",
99+
"varbinary": "Binary",
100+
"bytes": "Binary",
101+
"bytea": "Binary",
102+
"blob": "Binary",
103+
}
104+
105+
_ZONED_TIMESTAMPS = {
106+
"timestamp_tz",
107+
"timestamptz",
108+
"timestamp_ltz",
109+
"timestamp with time zone",
110+
"timestamp with local time zone",
111+
}
112+
_NAIVE_TIMESTAMPS = {"timestamp_ntz", "timestamp without time zone", "datetime", "datetime2"}
113+
114+
115+
@dataclass(frozen=True)
116+
class PolarsType:
117+
"""A Polars data type, held as the expression that builds it, such as ``pl.Int32``."""
118+
119+
expression: str
120+
121+
122+
@dataclass(frozen=True)
123+
class PolarsList(PolarsType):
124+
expression: str = "pl.List"
125+
inner: PolarsType = PolarsType("pl.String")
126+
127+
128+
@dataclass(frozen=True)
129+
class PolarsStruct(PolarsType):
130+
expression: str = "pl.Struct"
131+
fields: Tuple[Tuple[str, PolarsType], ...] = ()
132+
133+
134+
class PolarsExporter(Exporter):
135+
def export(
136+
self,
137+
data_contract: OpenDataContractStandard,
138+
schema_name,
139+
server,
140+
sql_server_type,
141+
export_args,
142+
) -> str:
143+
return to_polars(data_contract, schema_name)
144+
145+
146+
def to_polars(contract: OpenDataContractStandard, schema_name: str = "all") -> str:
147+
schemas = contract.schema_ or []
148+
if schema_name != "all":
149+
schemas = [schema_obj for schema_obj in schemas if schema_obj.name == schema_name]
150+
if not schemas:
151+
raise RuntimeError(
152+
f"Schema '{schema_name}' not found in the data contract. "
153+
f"Available schemas: {[schema_obj.name for schema_obj in contract.schema_ or []]}"
154+
)
155+
156+
blocks = ["import polars as pl"]
157+
used = {"pl"}
158+
for schema_obj in schemas:
159+
name = "".join(c if ("_" + c).isidentifier() else "_" for c in (schema_obj.name or "schema"))
160+
if not name.isidentifier():
161+
name = "_" + name
162+
if keyword.iskeyword(name):
163+
name += "_"
164+
variable = name
165+
suffix = 2
166+
while variable in used:
167+
variable = f"{name}_{suffix}"
168+
suffix += 1
169+
used.add(variable)
170+
171+
try:
172+
fields = _to_struct(schema_obj.properties or []).fields
173+
except RuntimeError as e:
174+
raise RuntimeError(f"Schema '{schema_obj.name}': {e}") from e
175+
if fields:
176+
blocks.append(f"{variable} = pl.Schema(\n {_render_fields(fields, ' ')}\n)")
177+
else:
178+
blocks.append(f"{variable} = pl.Schema({{}})")
179+
return "\n\n".join(blocks)
180+
181+
182+
def to_polars_type(prop: SchemaProperty) -> PolarsType:
183+
logical_type = prop.logicalType.lower() if prop.logicalType else None
184+
physical_type = " ".join(prop.physicalType.lower().split()) if prop.physicalType else None
185+
186+
if (logical_type is None and physical_type is None) or physical_type == "null":
187+
return PolarsType("pl.Null")
188+
189+
if logical_type == "array":
190+
return PolarsList(inner=to_polars_type(prop.items) if prop.items else PolarsType("pl.String"))
191+
192+
if is_vector(prop):
193+
element = PolarsType("pl." + _VECTOR_ELEMENT_TYPES.get(vector_element_type(prop), "Float32"))
194+
dimensions = vector_dimensions(prop)
195+
if dimensions is None:
196+
return PolarsList(inner=element)
197+
return PolarsType(f"pl.Array({element.expression}, {dimensions})")
198+
199+
# Polars has no map type: like an Arrow map read into Polars, a map is a list of key-value structs.
200+
if is_map(prop):
201+
key = get_map_key(prop)
202+
value = get_map_value(prop)
203+
return PolarsList(
204+
inner=PolarsStruct(
205+
fields=(
206+
("key", to_polars_type(key) if key is not None else PolarsType("pl.String")),
207+
("value", to_polars_type(value) if value is not None else PolarsType("pl.String")),
208+
)
209+
)
210+
)
211+
212+
# The physical type without its parameters: `timestamp(6) with time zone` is `timestamp with time zone`.
213+
base_type = " ".join(re.sub(r"\([^)]*\)", " ", physical_type).split()) if physical_type else None
214+
if logical_type == "object" or base_type in ["object", "record", "struct"]:
215+
return _to_struct(prop.properties or [])
216+
217+
# A physical type naming a width or precision the logical type leaves open wins, then `format`, then the logical type.
218+
if physical_type:
219+
parameters = []
220+
parenthesized = re.search(r"\(([^)]*)\)", physical_type)
221+
if parenthesized and all(part.strip().isdigit() for part in parenthesized.group(1).split(",")):
222+
parameters = [int(part) for part in parenthesized.group(1).split(",")]
223+
if base_type in ["decimal", "numeric"] or (base_type == "number" and parameters):
224+
precision, scale = _custom_precision_scale(prop)
225+
if precision is None and scale is None and parameters:
226+
precision = parameters[0]
227+
scale = parameters[1] if len(parameters) > 1 else 0
228+
return _decimal_type(prop, precision, scale)
229+
if base_type == "timestamp":
230+
return _datetime_type(prop, None, parameters)
231+
if base_type in _ZONED_TIMESTAMPS:
232+
return _datetime_type(prop, True, parameters)
233+
if base_type in _NAIVE_TIMESTAMPS:
234+
return _datetime_type(prop, False, parameters)
235+
if base_type in _PHYSICAL_TYPES:
236+
return PolarsType("pl." + _PHYSICAL_TYPES[base_type])
237+
238+
format_option = _logical_type_option(prop, "format")
239+
format_name = str(format_option).lower() if format_option is not None else None
240+
if logical_type == "integer" and format_name in _INTEGER_FORMATS:
241+
return PolarsType("pl." + _INTEGER_FORMATS[format_name])
242+
if logical_type == "number" and format_name in _NUMBER_FORMATS:
243+
return PolarsType("pl." + _NUMBER_FORMATS[format_name])
244+
245+
match logical_type:
246+
case "string":
247+
return PolarsType("pl.String")
248+
case "integer":
249+
return PolarsType("pl.Int64")
250+
case "number":
251+
precision, scale = _custom_precision_scale(prop)
252+
if precision is not None or scale is not None:
253+
return _decimal_type(prop, precision, scale)
254+
return PolarsType("pl.Float64")
255+
case "boolean":
256+
return PolarsType("pl.Boolean")
257+
case "date":
258+
return PolarsType("pl.Date")
259+
case "timestamp":
260+
return _datetime_type(prop, None, [])
261+
case "time":
262+
return PolarsType("pl.Time")
263+
case _:
264+
return PolarsType("pl.String")
265+
266+
267+
def _to_struct(properties: List[SchemaProperty]) -> PolarsStruct:
268+
return PolarsStruct(fields=tuple((prop.name, to_polars_type(prop)) for prop in properties))
269+
270+
271+
def _decimal_type(prop: SchemaProperty, precision: Optional[int], scale: Optional[int]) -> PolarsType:
272+
"""A decimal; without a precision, Polars chooses it, and without a scale it is 0, as in SQL."""
273+
if precision is not None and precision > _MAX_DECIMAL_PRECISION:
274+
raise RuntimeError(
275+
f"Polars decimals hold at most {_MAX_DECIMAL_PRECISION} digits, "
276+
f"but '{prop.name}' has a precision of {precision}."
277+
)
278+
if precision is None and not scale:
279+
return PolarsType("pl.Decimal()")
280+
if precision is None:
281+
return PolarsType(f"pl.Decimal(scale={scale})")
282+
return PolarsType(f"pl.Decimal(precision={precision}, scale={scale or 0})")
283+
284+
285+
def _datetime_type(prop: SchemaProperty, zoned: Optional[bool], parameters: List[int]) -> PolarsType:
286+
"""`zoned` comes from the physical type; when that doesn't say, the `timezone` option decides."""
287+
if zoned is None:
288+
zoned = _logical_type_option(prop, "timezone") is True
289+
time_unit = "us"
290+
if parameters:
291+
time_unit = "ms" if parameters[0] <= 3 else "us" if parameters[0] <= 6 else "ns"
292+
if not zoned:
293+
return PolarsType(f'pl.Datetime(time_unit="{time_unit}")')
294+
time_zone = _logical_type_option(prop, "defaultTimezone") or "UTC"
295+
return PolarsType(f'pl.Datetime(time_unit="{time_unit}", time_zone={_string_literal(str(time_zone))})')
296+
297+
298+
def _logical_type_option(prop: SchemaProperty, key: str):
299+
if prop.logicalTypeOptions is None:
300+
return None
301+
return prop.logicalTypeOptions.get(key)
302+
303+
304+
def _custom_precision_scale(prop: SchemaProperty) -> Tuple[Optional[int], Optional[int]]:
305+
"""The `precision` and `scale` custom properties, which DCS contracts converted to ODCS carry."""
306+
values = {"precision": None, "scale": None}
307+
for custom_property in prop.customProperties or []:
308+
if custom_property.property in values and str(custom_property.value).strip().isdigit():
309+
values[custom_property.property] = int(str(custom_property.value).strip())
310+
return values["precision"], values["scale"]
311+
312+
313+
def _string_literal(value: str) -> str:
314+
"""A double-quoted Python string literal for `value`."""
315+
return json.dumps(value, ensure_ascii=False)
316+
317+
318+
def _render(data_type: PolarsType, indent: str) -> str:
319+
"""The expression building `data_type`; a trailing comma after every struct field keeps `ruff format` from folding it."""
320+
if isinstance(data_type, PolarsStruct):
321+
if not data_type.fields:
322+
return "pl.Struct({})"
323+
return f"pl.Struct(\n{indent} {_render_fields(data_type.fields, indent + ' ')}\n{indent})"
324+
if isinstance(data_type, PolarsList):
325+
inner = _render(data_type.inner, indent + " ")
326+
if "\n" not in inner:
327+
return f"pl.List({inner})"
328+
return f"pl.List(\n{indent} {inner}\n{indent})"
329+
return data_type.expression
330+
331+
332+
def _render_fields(fields: Tuple[Tuple[str, PolarsType], ...], indent: str) -> str:
333+
"""A dict literal from field name to type, whose opening brace sits on a line indented by `indent`."""
334+
lines = [
335+
f"{indent} {_string_literal(name)}: {_render(data_type, indent + ' ')}," for name, data_type in fields
336+
]
337+
return "{\n" + "\n".join(lines) + f"\n{indent}}}"

0 commit comments

Comments
 (0)