Skip to content

Commit 360f7fd

Browse files
amassoudiamassoudi-dynabuyjschoedl
authored
feat: export logicalTypeOptions as pydantic.Field constraints (#1678)
* feat: export logicalTypeOptions as pydantic.Field constraints * shorten comments, inline variables, make example consistent --------- Co-authored-by: Ayoub Massoudi <amassoudi@dynabuy.fr> Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent c88ffac commit 360f7fd

5 files changed

Lines changed: 246 additions & 12 deletions

File tree

‎CHANGELOG.md‎

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

88
## [Unreleased]
99

10+
### Added
11+
- `datacontract export pydantic-model`: export `logicalTypeOptions` as `pydantic.Field` constraints (#1679)
12+
13+
### Changed
14+
- `datacontract export pydantic-model`: optional fields default to `None` (#1679)
15+
1016
### Fixed
1117
- `datacontract export html`: add schema and property anchors (`#<schema name>.<property name>`) and nested objects in array `items` back (#1677 @dmaresma)
1218
- `datacontract export sodacl`: date and timestamp `minimum`/`maximum` no longer fail in soda-core (#1662)

‎datacontract/export/pydantic_exporter.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,38 @@ def product_of(nodes: list[typing.Any]) -> ast.Subscript:
7474
type_annotation_type = typing.Union[ast.Name, ast.Attribute, ast.Constant, ast.Subscript]
7575

7676

77+
def field_value(prop: SchemaProperty) -> ast.expr | None:
78+
"""None means a bare annotation with no assignment."""
79+
match prop.logicalType:
80+
case "string":
81+
constraints = (("pattern", "pattern"), ("minLength", "min_length"), ("maxLength", "max_length"))
82+
case "integer" | "number" | "date" | "timestamp" | "time":
83+
constraints = (
84+
("minimum", "ge"),
85+
("maximum", "le"),
86+
("exclusiveMinimum", "gt"),
87+
("exclusiveMaximum", "lt"),
88+
)
89+
case _:
90+
constraints = ()
91+
options = prop.logicalTypeOptions or {}
92+
keywords = []
93+
for option, keyword in constraints:
94+
value = options.get(option)
95+
# Draft-04 JSON Schema had boolean exclusive bounds, and an empty pattern does not import back.
96+
if isinstance(value, (int, float, str)) and not isinstance(value, bool) and value != "":
97+
keywords.append(ast.keyword(arg=keyword, value=ast.Constant(value)))
98+
if not keywords:
99+
return None if prop.required else ast.Constant(None)
100+
if not prop.required:
101+
keywords.insert(0, ast.keyword(arg="default", value=ast.Constant(None)))
102+
return ast.Call(
103+
func=ast.Attribute(value=ast.Name(id="pydantic", ctx=ast.Load()), attr="Field", ctx=ast.Load()),
104+
args=[],
105+
keywords=keywords,
106+
)
107+
108+
77109
def _get_type(prop: SchemaProperty) -> Optional[str]:
78110
"""Get the logical type from a schema property."""
79111
return prop.logicalType
@@ -198,7 +230,11 @@ def field_definitions(properties: list[SchemaProperty]) -> tuple[list[ast.Expr],
198230
classes = []
199231
for prop in properties:
200232
(ann, new_class) = type_annotation(prop.name, prop)
201-
annotations.append(ast.AnnAssign(target=ast.Name(id=prop.name, ctx=ast.Store()), annotation=ann, simple=1))
233+
annotations.append(
234+
ast.AnnAssign(
235+
target=ast.Name(id=prop.name, ctx=ast.Store()), annotation=ann, value=field_value(prop), simple=1
236+
)
237+
)
202238
if prop.description and is_simple_field(prop):
203239
annotations.append(ast.Expr(ast.Constant(prop.description)))
204240
if new_class:

‎docs/docs/exports/pydantic-model.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,20 @@ class Line_items(pydantic.BaseModel):
4747

4848
{/* END AUTOGENERATED EXAMPLE */}
4949

50+
## Defaults and constraints
51+
52+
Fields that are not `required` are typed `typing.Optional[...]` and default to `None`.
53+
54+
`logicalTypeOptions` become `pydantic.Field` constraints, so the generated model rejects what `datacontract test` would flag:
55+
56+
| logicalType | logicalTypeOptions | `pydantic.Field` keyword |
57+
|---|---|---|
58+
| string | `pattern`, `minLength`, `maxLength` | `pattern`, `min_length`, `max_length` |
59+
| integer, number, date, timestamp, time | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum` | `ge`, `le`, `gt`, `lt` |
60+
61+
```python
62+
label: typing.Optional[str] = pydantic.Field(default=None, pattern='^[^,]+(,\\s*[^,]+)*$')
63+
order_total: float = pydantic.Field(ge=0)
64+
```
65+
5066
All options: **[`datacontract export pydantic-model`](../commands/export/pydantic-model.md)**.

‎tests/test_export_pydantic.py‎

Lines changed: 181 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import ast
22
from textwrap import dedent
33

4+
import pydantic
5+
import pytest
46
from open_data_contract_standard.model import Description, OpenDataContractStandard, SchemaObject, SchemaProperty
57

68
import datacontract.export.pydantic_exporter as conv
@@ -16,7 +18,7 @@ def test_simple_model_export():
1618
== dedent(
1719
"""
1820
class Test(pydantic.BaseModel):
19-
f: typing.Optional[str]
21+
f: typing.Optional[str] = None
2022
"""
2123
).strip()
2224
)
@@ -39,7 +41,7 @@ def test_array_model_export():
3941
== dedent(
4042
"""
4143
class Test(pydantic.BaseModel):
42-
f: typing.Optional[list[str]]
44+
f: typing.Optional[list[str]] = None
4345
"""
4446
).strip()
4547
)
@@ -65,7 +67,7 @@ class Test(pydantic.BaseModel):
6567
6668
class F(pydantic.BaseModel):
6769
f1: str
68-
f: typing.Optional[F]
70+
f: typing.Optional[F] = None
6971
"""
7072
).strip()
7173
)
@@ -86,7 +88,7 @@ class Test(pydantic.BaseModel):
8688
8789
class F(pydantic.BaseModel):
8890
pass
89-
f: typing.Optional[F]
91+
f: typing.Optional[F] = None
9092
"""
9193
).strip()
9294
)
@@ -117,7 +119,7 @@ class Test(pydantic.BaseModel):
117119
class F(pydantic.BaseModel):
118120
\"\"\"A test field\"\"\"
119121
f1: str
120-
f: typing.Optional[F]
122+
f: typing.Optional[F] = None
121123
"""
122124
).strip()
123125
)
@@ -144,7 +146,7 @@ class Test(pydantic.BaseModel):
144146
class F(pydantic.BaseModel):
145147
f1: str
146148
'A test field'
147-
f: typing.Optional[F]
149+
f: typing.Optional[F] = None
148150
"""
149151
).strip()
150152
)
@@ -166,7 +168,7 @@ def test_model_description_export():
166168
'Contract description'
167169
168170
class Test_model(pydantic.BaseModel):
169-
f: typing.Optional[str]
171+
f: typing.Optional[str] = None
170172
"""
171173
).strip()
172174
)
@@ -182,7 +184,178 @@ def test_decimal_model_export():
182184
== dedent(
183185
"""
184186
class Test(pydantic.BaseModel):
185-
f: typing.Optional[decimal.Decimal]
187+
f: typing.Optional[decimal.Decimal] = None
186188
"""
187189
).strip()
188190
)
191+
192+
193+
def test_string_constraints_export():
194+
schema = SchemaObject(
195+
name="Test",
196+
properties=[
197+
SchemaProperty(
198+
name="f",
199+
logicalType="string",
200+
required=True,
201+
logicalTypeOptions={"pattern": "^[^,]+(,\\s*[^,]+)*$", "minLength": 1, "maxLength": 64},
202+
)
203+
],
204+
)
205+
ast_class = conv.generate_model_class("Test", schema)
206+
assert (
207+
ast.unparse(ast_class)
208+
== dedent(
209+
r"""
210+
class Test(pydantic.BaseModel):
211+
f: str = pydantic.Field(pattern='^[^,]+(,\\s*[^,]+)*$', min_length=1, max_length=64)
212+
"""
213+
).strip()
214+
)
215+
216+
217+
def test_optional_constrained_field_defaults_to_none():
218+
schema = SchemaObject(
219+
name="Test",
220+
properties=[
221+
SchemaProperty(
222+
name="f",
223+
logicalType="string",
224+
description="A labelled field",
225+
logicalTypeOptions={"pattern": "^a$"},
226+
)
227+
],
228+
)
229+
ast_class = conv.generate_model_class("Test", schema)
230+
assert (
231+
ast.unparse(ast_class)
232+
== dedent(
233+
"""
234+
class Test(pydantic.BaseModel):
235+
f: typing.Optional[str] = pydantic.Field(default=None, pattern='^a$')
236+
'A labelled field'
237+
"""
238+
).strip()
239+
)
240+
241+
242+
def test_numeric_bounds_export():
243+
schema = SchemaObject(
244+
name="Test",
245+
properties=[
246+
SchemaProperty(
247+
name="f",
248+
logicalType="integer",
249+
required=True,
250+
logicalTypeOptions={"minimum": 0, "maximum": 100, "exclusiveMinimum": -1, "exclusiveMaximum": 101.5},
251+
)
252+
],
253+
)
254+
ast_class = conv.generate_model_class("Test", schema)
255+
assert (
256+
ast.unparse(ast_class)
257+
== dedent(
258+
"""
259+
class Test(pydantic.BaseModel):
260+
f: int = pydantic.Field(ge=0, le=100, gt=-1, lt=101.5)
261+
"""
262+
).strip()
263+
)
264+
265+
266+
def test_date_bounds_export_as_strings():
267+
schema = SchemaObject(
268+
name="Test",
269+
properties=[
270+
SchemaProperty(name="f", logicalType="date", required=True, logicalTypeOptions={"minimum": "2020-01-01"})
271+
],
272+
)
273+
ast_class = conv.generate_model_class("Test", schema)
274+
assert (
275+
ast.unparse(ast_class)
276+
== dedent(
277+
"""
278+
class Test(pydantic.BaseModel):
279+
f: datetime.date = pydantic.Field(ge='2020-01-01')
280+
"""
281+
).strip()
282+
)
283+
284+
285+
def test_options_outside_the_logical_type_are_ignored():
286+
"""`maxLength` on an integer, a boolean bound, and an empty pattern have no Pydantic counterpart."""
287+
schema = SchemaObject(
288+
name="Test",
289+
properties=[
290+
SchemaProperty(name="f", logicalType="integer", required=True, logicalTypeOptions={"maxLength": 10}),
291+
SchemaProperty(
292+
name="g", logicalType="string", required=True, logicalTypeOptions={"pattern": "", "maxLength": True}
293+
),
294+
],
295+
)
296+
ast_class = conv.generate_model_class("Test", schema)
297+
assert (
298+
ast.unparse(ast_class)
299+
== dedent(
300+
"""
301+
class Test(pydantic.BaseModel):
302+
f: int
303+
g: str
304+
"""
305+
).strip()
306+
)
307+
308+
309+
def test_enum_field_keeps_its_constraints():
310+
schema = SchemaObject(
311+
name="Test",
312+
properties=[
313+
SchemaProperty(
314+
name="f",
315+
logicalType="string",
316+
required=True,
317+
logicalTypeOptions={"enum": ["ab", "cd"], "maxLength": 2},
318+
)
319+
],
320+
)
321+
ast_class = conv.generate_model_class("Test", schema)
322+
assert (
323+
ast.unparse(ast_class)
324+
== dedent(
325+
"""
326+
class Test(pydantic.BaseModel):
327+
f: typing.Literal['ab', 'cd'] = pydantic.Field(max_length=2)
328+
"""
329+
).strip()
330+
)
331+
332+
333+
def test_generated_model_enforces_the_constraints():
334+
"""What the contract constrains, the model rejects: the string tests cannot prove Pydantic accepts the output."""
335+
contract = OpenDataContractStandard(
336+
apiVersion="v3.1.0",
337+
kind="DataContract",
338+
schema=[
339+
SchemaObject(
340+
name="orders",
341+
properties=[
342+
SchemaProperty(
343+
name="label", logicalType="string", logicalTypeOptions={"pattern": "^[^,]+(,\\s*[^,]+)*$"}
344+
),
345+
SchemaProperty(
346+
name="total", logicalType="integer", required=True, logicalTypeOptions={"minimum": 0}
347+
),
348+
],
349+
)
350+
],
351+
)
352+
namespace = {}
353+
exec(conv.to_pydantic_model_str(contract), namespace)
354+
orders = namespace["Orders"]
355+
356+
assert orders(total=1, label="a, b").label == "a, b"
357+
assert orders(total=0).label is None
358+
with pytest.raises(pydantic.ValidationError):
359+
orders(total=1, label="a,,b")
360+
with pytest.raises(pydantic.ValidationError):
361+
orders(total=-1)

‎tests/test_roundtrip_pydantic_model.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@
77
column shapes than a hand-written fixture would.
88
99
What a Python annotation cannot carry does not survive, and is not asserted here:
10-
`physicalType` is database specific, and constraints, quality rules and examples
11-
have no place in a bare annotation. Name, logical type, requiredness, description
12-
and nesting do survive, and that is what a round trip has to preserve.
10+
`physicalType` is database specific, and quality rules and examples have no place
11+
in a bare annotation. Name, logical type, requiredness, description, nesting and
12+
the constraints a `pydantic.Field` can express do survive, and that is what a
13+
round trip has to preserve.
1314
"""
1415

1516
import ast
@@ -21,6 +22,7 @@
2122
from datacontract.lint import resolve
2223

2324
EXAMPLES = sorted((Path(__file__).resolve().parents[1] / "examples").rglob("*.odcs.yaml"))
25+
CONSTRAINTS = {"pattern", "minLength", "maxLength", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"}
2426

2527

2628
def shape(properties):
@@ -31,6 +33,7 @@ def shape(properties):
3133
prop.logicalType,
3234
bool(prop.required),
3335
prop.description,
36+
{key: value for key, value in (prop.logicalTypeOptions or {}).items() if key in CONSTRAINTS},
3437
shape(prop.properties or []),
3538
shape([prop.items] if prop.items else []),
3639
)

0 commit comments

Comments
 (0)