narabi-orm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- narabi/__init__.py +27 -0
- narabi/__main__.py +5 -0
- narabi/cli.py +338 -0
- narabi/console.py +102 -0
- narabi/database.py +310 -0
- narabi/fields/__init__.py +13 -0
- narabi/fields/defaults.py +59 -0
- narabi/fields/markers.py +74 -0
- narabi/migrations/__init__.py +22 -0
- narabi/migrations/bootstrap.py +30 -0
- narabi/migrations/decorators.py +22 -0
- narabi/migrations/diff.py +96 -0
- narabi/migrations/dsl.py +255 -0
- narabi/migrations/errors.py +5 -0
- narabi/migrations/executor.py +299 -0
- narabi/migrations/generate.py +149 -0
- narabi/migrations/historical.py +158 -0
- narabi/migrations/history.py +160 -0
- narabi/migrations/models.py +57 -0
- narabi/migrations/postgres_executor.py +239 -0
- narabi/migrations/postgresql.py +268 -0
- narabi/migrations/preview.py +150 -0
- narabi/migrations/replay.py +40 -0
- narabi/migrations/reverse.py +127 -0
- narabi/migrations/schema.py +169 -0
- narabi/migrations/snapshot.py +52 -0
- narabi/migrations/sqlite.py +131 -0
- narabi/models/__init__.py +1 -0
- narabi/models/bulk.py +123 -0
- narabi/models/core.py +440 -0
- narabi/models/inflection.py +37 -0
- narabi/models/lifecycle.py +125 -0
- narabi/models/privacy.py +19 -0
- narabi/models/serialization.py +145 -0
- narabi/models/soft_delete.py +59 -0
- narabi/models/timestamps.py +47 -0
- narabi/models/validation.py +149 -0
- narabi/models/values.py +167 -0
- narabi/project.py +108 -0
- narabi/py.typed +0 -0
- narabi/pytest.py +11 -0
- narabi/query/__init__.py +7 -0
- narabi/query/expressions.py +180 -0
- narabi/query/relation.py +562 -0
- narabi/query/scopes.py +36 -0
- narabi/relations/__init__.py +6 -0
- narabi/relations/prefetch.py +66 -0
- narabi/relations/references.py +196 -0
- narabi/relations/relationships.py +185 -0
- narabi/schema.py +132 -0
- narabi/stubs.py +275 -0
- narabi_orm-0.1.0.dist-info/METADATA +104 -0
- narabi_orm-0.1.0.dist-info/RECORD +56 -0
- narabi_orm-0.1.0.dist-info/WHEEL +4 -0
- narabi_orm-0.1.0.dist-info/entry_points.txt +2 -0
- narabi_orm-0.1.0.dist-info/licenses/LICENSE +29 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Map record fields to and from JSON-compatible data."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Any, TypeVar, get_args
|
|
7
|
+
|
|
8
|
+
import attrs
|
|
9
|
+
from cattrs.preconf.json import make_converter
|
|
10
|
+
|
|
11
|
+
from ..fields import Private
|
|
12
|
+
from .lifecycle import assign_fields
|
|
13
|
+
from ..relations.references import field_value
|
|
14
|
+
from .timestamps import decode_datetime
|
|
15
|
+
from .validation import FieldError, ValidationError, prefix_errors
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_converter = make_converter()
|
|
19
|
+
_missing = object()
|
|
20
|
+
_include_private = ContextVar("record_include_private", default=False)
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def from_values(target: type[T], values: Mapping[str, object]) -> T:
|
|
25
|
+
token = _include_private.set(True)
|
|
26
|
+
try:
|
|
27
|
+
data = {
|
|
28
|
+
name: value if hasattr(type(value), "_value_components") else _converter.unstructure(value)
|
|
29
|
+
for name, value in values.items()
|
|
30
|
+
}
|
|
31
|
+
return _converter.structure(data, target)
|
|
32
|
+
finally:
|
|
33
|
+
_include_private.reset(token)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def configure_serialization(cls, metadata, *, automatic_key=None, value_object=False):
|
|
37
|
+
managed_fields = getattr(cls, "_record_managed_fields", ())
|
|
38
|
+
fields = {
|
|
39
|
+
field.name: field for field in attrs.fields(cls) if field.init or field.name in managed_fields
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private = {name for name in fields if (Private,) in metadata[name].markers}
|
|
43
|
+
|
|
44
|
+
def unstructure(instance):
|
|
45
|
+
include_private = _include_private.get()
|
|
46
|
+
return {
|
|
47
|
+
name: _converter.unstructure(field_value(instance, name))
|
|
48
|
+
for name in fields if include_private or name not in private
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
def structure(data, target):
|
|
52
|
+
if not isinstance(data, Mapping):
|
|
53
|
+
if value_object:
|
|
54
|
+
raise ValidationError((FieldError(None, "type", "Expected a component mapping"),))
|
|
55
|
+
raise TypeError(f"{target.__name__}.from_dict expects a mapping")
|
|
56
|
+
if data.keys() - fields.keys():
|
|
57
|
+
if value_object:
|
|
58
|
+
raise ValidationError((FieldError(None, "fields", "Unexpected value components"),))
|
|
59
|
+
raise ValueError(f"Unexpected fields for {target.__name__}")
|
|
60
|
+
|
|
61
|
+
values = {}
|
|
62
|
+
managed = {}
|
|
63
|
+
for name, attribute in fields.items():
|
|
64
|
+
value = data.get(name, _missing)
|
|
65
|
+
if value is _missing:
|
|
66
|
+
if attribute.default is attrs.NOTHING:
|
|
67
|
+
if value_object:
|
|
68
|
+
raise ValidationError((FieldError(name, "required", "Component is required"),))
|
|
69
|
+
raise ValueError(f"Missing field {target.__name__}.{name}")
|
|
70
|
+
continue
|
|
71
|
+
field = metadata[name]
|
|
72
|
+
try:
|
|
73
|
+
if name in managed_fields:
|
|
74
|
+
managed[name] = decode_datetime(value)
|
|
75
|
+
elif value_object:
|
|
76
|
+
values[attribute.alias] = _converter.structure(value, field.type) if (
|
|
77
|
+
field.type is datetime and isinstance(value, str)
|
|
78
|
+
) else value
|
|
79
|
+
elif value is None and (
|
|
80
|
+
field.nullable or field.type in (Any, type(None))
|
|
81
|
+
or type(None) in get_args(field.type) or name == automatic_key
|
|
82
|
+
):
|
|
83
|
+
values[attribute.alias] = None
|
|
84
|
+
elif value is None:
|
|
85
|
+
if hasattr(field.type, "_value_components"):
|
|
86
|
+
raise ValidationError((FieldError(None, "required", "Value is required"),))
|
|
87
|
+
raise TypeError("Field does not accept null")
|
|
88
|
+
else:
|
|
89
|
+
reference = getattr(target, "_record_references", {}).get(name)
|
|
90
|
+
value_type = field.type
|
|
91
|
+
if reference is not None:
|
|
92
|
+
related = reference.target()
|
|
93
|
+
value_type = related._record_metadata[related._record_key].type
|
|
94
|
+
if hasattr(value_type, "_value_components") and isinstance(value, value_type):
|
|
95
|
+
values[attribute.alias] = value
|
|
96
|
+
else:
|
|
97
|
+
values[attribute.alias] = _converter.structure(value, value_type)
|
|
98
|
+
except ValidationError as error:
|
|
99
|
+
raise prefix_errors(name, error) from error
|
|
100
|
+
except (TypeError, ValueError, KeyError, OverflowError, ExceptionGroup) as error:
|
|
101
|
+
if value_object:
|
|
102
|
+
raise ValidationError((FieldError(name, "type", "Invalid value component"),)) from error
|
|
103
|
+
raise ValueError(f"Invalid field {target.__name__}.{name}") from error
|
|
104
|
+
instance = target(**values)
|
|
105
|
+
assign_fields(instance, managed)
|
|
106
|
+
return instance
|
|
107
|
+
|
|
108
|
+
# Dispatch explicitly so cattrs does not resolve model annotations at import time.
|
|
109
|
+
def matches(target):
|
|
110
|
+
return target is cls
|
|
111
|
+
|
|
112
|
+
_converter.register_unstructure_hook_func(matches, unstructure)
|
|
113
|
+
_converter.register_structure_hook_func(matches, structure)
|
|
114
|
+
|
|
115
|
+
def to_dict(self, *, include_private=False):
|
|
116
|
+
token = _include_private.set(include_private)
|
|
117
|
+
try:
|
|
118
|
+
return _converter.unstructure(self)
|
|
119
|
+
finally:
|
|
120
|
+
_include_private.reset(token)
|
|
121
|
+
|
|
122
|
+
def to_json(self, *, include_private=False):
|
|
123
|
+
token = _include_private.set(include_private)
|
|
124
|
+
try:
|
|
125
|
+
return _converter.dumps(self)
|
|
126
|
+
finally:
|
|
127
|
+
_include_private.reset(token)
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def from_dict(cls, data):
|
|
131
|
+
return _converter.structure(data, cls)
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def from_record(cls, source):
|
|
135
|
+
data = {}
|
|
136
|
+
for name in fields:
|
|
137
|
+
value = field_value(source, name, _missing)
|
|
138
|
+
if value is not _missing:
|
|
139
|
+
data[name] = value
|
|
140
|
+
return from_values(cls, data)
|
|
141
|
+
|
|
142
|
+
cls.to_dict = to_dict
|
|
143
|
+
cls.to_json = to_json
|
|
144
|
+
cls.from_dict = from_dict
|
|
145
|
+
cls.from_record = from_record
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Storage operations for tables with logical deletion."""
|
|
2
|
+
|
|
3
|
+
import attrs
|
|
4
|
+
|
|
5
|
+
from ..database import database_for, identifier
|
|
6
|
+
from .lifecycle import assign_fields
|
|
7
|
+
from ..relations.references import clear_relationship_cache
|
|
8
|
+
from ..query.relation import Relation
|
|
9
|
+
from .timestamps import encode_datetime, utc_now
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
DELETED_AT = "deleted_at"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class WithDeleted:
|
|
16
|
+
def __get__(self, instance, owner):
|
|
17
|
+
return Relation(owner).with_deleted
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def set_deleted(instance, deleted: bool, *, db=None) -> bool:
|
|
21
|
+
"""Change the stored deletion state while preserving pending field edits."""
|
|
22
|
+
state = getattr(instance, "_record_state", None)
|
|
23
|
+
if state is None:
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
database = database_for(state, db)
|
|
27
|
+
model = type(instance)
|
|
28
|
+
placeholder = database.placeholder
|
|
29
|
+
now = utc_now()
|
|
30
|
+
values = {DELETED_AT: now if deleted else None}
|
|
31
|
+
if "updated_at" in model._record_managed_fields:
|
|
32
|
+
values["updated_at"] = now
|
|
33
|
+
assignments = ", ".join(
|
|
34
|
+
f"{identifier(model._record_columns[name])} = {placeholder}" for name in values
|
|
35
|
+
)
|
|
36
|
+
primary = identifier(model._record_columns[model._record_key])
|
|
37
|
+
deleted_column = identifier(model._record_columns[DELETED_AT])
|
|
38
|
+
condition = f"{deleted_column} IS NULL" if deleted else f"{deleted_column} IS NOT NULL"
|
|
39
|
+
params = tuple(encode_datetime(value, database.backend) for value in values.values())
|
|
40
|
+
affected = await database.execute(
|
|
41
|
+
f"UPDATE {model._record_table} SET {assignments} "
|
|
42
|
+
f"WHERE {primary} = {placeholder} AND {condition}",
|
|
43
|
+
(*params, state.key),
|
|
44
|
+
)
|
|
45
|
+
if not affected:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
previous = {name: getattr(instance, name) for name in values}
|
|
49
|
+
|
|
50
|
+
def restore():
|
|
51
|
+
assign_fields(instance, previous)
|
|
52
|
+
instance._record_state = state
|
|
53
|
+
clear_relationship_cache(instance)
|
|
54
|
+
|
|
55
|
+
database._on_rollback(restore)
|
|
56
|
+
assign_fields(instance, values)
|
|
57
|
+
instance._record_state = attrs.evolve(state, original={**state.original, **values})
|
|
58
|
+
clear_relationship_cache(instance)
|
|
59
|
+
return True
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Managed UTC datetime fields and their database representation."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
|
|
5
|
+
import attrs
|
|
6
|
+
|
|
7
|
+
from ..fields import Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
PERSISTENCE_TIMESTAMPS = ("created_at", "updated_at")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def utc_now() -> datetime:
|
|
14
|
+
return datetime.now(UTC)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def add_managed_datetimes(cls, metadata, names):
|
|
18
|
+
inherited = getattr(cls, "_record_managed_fields", ())
|
|
19
|
+
annotations = dict(vars(cls).get("__annotations__", {}))
|
|
20
|
+
for name in names:
|
|
21
|
+
if name in vars(cls) or name in annotations or (name in metadata and name not in inherited):
|
|
22
|
+
raise TypeError(f"{cls.__qualname__}.{name} is managed by Narabi")
|
|
23
|
+
if name not in inherited:
|
|
24
|
+
annotations[name] = datetime | None
|
|
25
|
+
setattr(cls, name, attrs.field(init=False, default=None))
|
|
26
|
+
metadata[name] = Field(datetime, nullable=True)
|
|
27
|
+
if names:
|
|
28
|
+
cls.__annotations__ = annotations
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def decode_datetime(value):
|
|
32
|
+
if value is None:
|
|
33
|
+
return None
|
|
34
|
+
if isinstance(value, str):
|
|
35
|
+
value = datetime.fromisoformat(value)
|
|
36
|
+
if not isinstance(value, datetime):
|
|
37
|
+
raise TypeError("Expected a datetime or ISO datetime string")
|
|
38
|
+
if value.utcoffset() is None:
|
|
39
|
+
return value.replace(tzinfo=UTC)
|
|
40
|
+
return value.astimezone(UTC)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def encode_datetime(value, backend):
|
|
44
|
+
if value is None:
|
|
45
|
+
return None
|
|
46
|
+
value = decode_datetime(value)
|
|
47
|
+
return value.isoformat(timespec="microseconds") if backend == "sqlite" else value
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Shared validation for data records and persistent tables."""
|
|
2
|
+
|
|
3
|
+
from copy import copy
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from inspect import isawaitable, iscoroutinefunction
|
|
6
|
+
from typing import Any, get_origin
|
|
7
|
+
|
|
8
|
+
import attrs
|
|
9
|
+
|
|
10
|
+
from ..fields import Length, Range, Ref
|
|
11
|
+
from .lifecycle import assign_fields
|
|
12
|
+
from ..relations.references import field_value
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class FieldError:
|
|
17
|
+
field: str | None
|
|
18
|
+
code: str
|
|
19
|
+
message: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ValidationResult:
|
|
24
|
+
errors: tuple[FieldError, ...]
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def valid(self) -> bool:
|
|
28
|
+
return not self.errors
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ValidationError(ValueError):
|
|
32
|
+
def __init__(self, errors: tuple[FieldError, ...]):
|
|
33
|
+
self.errors = errors
|
|
34
|
+
super().__init__("Record validation failed")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def prefix_errors(path, error):
|
|
38
|
+
return ValidationError(tuple(
|
|
39
|
+
replace(item, field=f"{path}.{item.field}" if item.field is not None else path)
|
|
40
|
+
for item in error.errors
|
|
41
|
+
))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _rule(stage, field, message=None):
|
|
45
|
+
def decorate(method):
|
|
46
|
+
if stage != "validate" and iscoroutinefunction(method):
|
|
47
|
+
raise TypeError(f"@{stage} requires a synchronous function")
|
|
48
|
+
method._record_rules = (*getattr(method, "_record_rules", ()), (stage, field, message))
|
|
49
|
+
return method
|
|
50
|
+
|
|
51
|
+
return decorate
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def convert(field):
|
|
55
|
+
return _rule("convert", field)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def normalize(field):
|
|
59
|
+
return _rule("normalize", field)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def validate(field=None, *, message="Validation failed"):
|
|
63
|
+
return _rule("validate", field, message)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _constraint_error(name, field, value):
|
|
67
|
+
if value is None and (Ref,) in field.markers:
|
|
68
|
+
return FieldError(name, "required", "Reference is required")
|
|
69
|
+
for marker in field.markers:
|
|
70
|
+
kind = marker[0]
|
|
71
|
+
if kind not in (Length, Range):
|
|
72
|
+
continue
|
|
73
|
+
_, minimum, maximum = marker
|
|
74
|
+
try:
|
|
75
|
+
measured = len(value) if kind is Length else value
|
|
76
|
+
value_type = get_origin(field.type) or field.type
|
|
77
|
+
if (value_type is Any or isinstance(value, value_type)) and minimum <= measured <= maximum:
|
|
78
|
+
continue
|
|
79
|
+
except TypeError:
|
|
80
|
+
pass
|
|
81
|
+
label = "Length" if kind is Length else "Value"
|
|
82
|
+
return FieldError(name, kind.__name__.lower(), f"{label} must be between {minimum} and {maximum}")
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def validation_rules(cls, fields):
|
|
87
|
+
members = {}
|
|
88
|
+
for base in reversed(cls.__mro__):
|
|
89
|
+
members.update(vars(base))
|
|
90
|
+
rules = {"convert": [], "normalize": [], "validate": []}
|
|
91
|
+
for method in members.values():
|
|
92
|
+
for stage, name, message in getattr(method, "_record_rules", ()):
|
|
93
|
+
if (stage != "validate" or name is not None) and name not in fields:
|
|
94
|
+
raise TypeError(f"Unknown field {name!r} in @{stage} on {cls.__name__}")
|
|
95
|
+
rules[stage].append((name, method, message))
|
|
96
|
+
return rules
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def configure_validation(cls, metadata, *, automatic_key=None):
|
|
100
|
+
fields = {field.name: metadata[field.name] for field in attrs.fields(cls) if field.init}
|
|
101
|
+
rules = validation_rules(cls, fields)
|
|
102
|
+
|
|
103
|
+
async def prepare(self, *, prepared=None):
|
|
104
|
+
values = {name: field_value(self, name) for name in fields}
|
|
105
|
+
unchanged = {name for name in values if prepared is not None and values[name] == prepared[name]}
|
|
106
|
+
errors = []
|
|
107
|
+
failed = set()
|
|
108
|
+
for stage in ("convert", "normalize"):
|
|
109
|
+
for name, method, _ in rules[stage]:
|
|
110
|
+
if name in unchanged or name in failed or (
|
|
111
|
+
values[name] is None and (fields[name].nullable or name == automatic_key)
|
|
112
|
+
):
|
|
113
|
+
continue
|
|
114
|
+
try:
|
|
115
|
+
values[name] = method(values[name])
|
|
116
|
+
except (ValueError, TypeError, ArithmeticError):
|
|
117
|
+
errors.append(FieldError(name, stage, f"Could not {stage} value"))
|
|
118
|
+
failed.add(name)
|
|
119
|
+
|
|
120
|
+
for name, field in fields.items():
|
|
121
|
+
value = values[name]
|
|
122
|
+
if name in failed or (value is None and (field.nullable or name == automatic_key)):
|
|
123
|
+
continue
|
|
124
|
+
error = _constraint_error(name, field, value)
|
|
125
|
+
if hasattr(field.type, "_value_components") and not isinstance(value, field.type):
|
|
126
|
+
error = FieldError(name, "type", f"Expected {field.type.__name__}")
|
|
127
|
+
if error is not None:
|
|
128
|
+
errors.append(error)
|
|
129
|
+
failed.add(name)
|
|
130
|
+
|
|
131
|
+
if rules["validate"]:
|
|
132
|
+
candidate = copy(self)
|
|
133
|
+
assign_fields(candidate, values)
|
|
134
|
+
for name, method, message in rules["validate"]:
|
|
135
|
+
if name in failed or (name is None and failed):
|
|
136
|
+
continue
|
|
137
|
+
result = method(candidate)
|
|
138
|
+
if isawaitable(result):
|
|
139
|
+
result = await result
|
|
140
|
+
if not result:
|
|
141
|
+
errors.append(FieldError(name, "custom", message))
|
|
142
|
+
return values, ValidationResult(tuple(errors))
|
|
143
|
+
|
|
144
|
+
async def validate_instance(self):
|
|
145
|
+
_, result = await prepare(self)
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
cls.validate = validate_instance
|
|
149
|
+
return prepare
|
narabi/models/values.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Immutable values and their mapping to table columns."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from inspect import isawaitable, iscoroutinefunction
|
|
7
|
+
from typing import ClassVar, TypeVar, dataclass_transform, get_origin
|
|
8
|
+
|
|
9
|
+
import attrs
|
|
10
|
+
|
|
11
|
+
from ..database import identifier
|
|
12
|
+
from ..fields import CLASSIFICATIONS, Indexed, Length, Range, Unique
|
|
13
|
+
from ..fields.defaults import configure_defaults
|
|
14
|
+
from ..relations.references import model_fields, register_model
|
|
15
|
+
from ..schema import _TYPES
|
|
16
|
+
from .privacy import redact_fields
|
|
17
|
+
from .serialization import configure_serialization
|
|
18
|
+
from .timestamps import decode_datetime, encode_datetime
|
|
19
|
+
from .validation import FieldError, ValidationError, _constraint_error, prefix_errors, validation_rules
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
VALUE_CHECK_PREFIX = "/* narabi:value */ "
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass_transform(frozen_default=True)
|
|
27
|
+
def value(cls: type[T]) -> type[T]:
|
|
28
|
+
"""Declare an immutable value with synchronous constructor validation."""
|
|
29
|
+
components = {
|
|
30
|
+
name: field for name, field in model_fields(cls).items() if get_origin(field.type) is not ClassVar
|
|
31
|
+
}
|
|
32
|
+
if not components:
|
|
33
|
+
raise TypeError(f"{cls.__qualname__} must declare at least one component")
|
|
34
|
+
for name, field in components.items():
|
|
35
|
+
if field.nullable or field.type not in _TYPES.values() or any(
|
|
36
|
+
marker[0] not in (Length, Range, *CLASSIFICATIONS) for marker in field.markers
|
|
37
|
+
):
|
|
38
|
+
raise TypeError(f"{cls.__qualname__}.{name}: unsupported value component")
|
|
39
|
+
rules = validation_rules(cls, components)
|
|
40
|
+
if rules["convert"] or rules["normalize"] or any(iscoroutinefunction(rule) for _, rule, _ in rules["validate"]):
|
|
41
|
+
raise TypeError("Value objects require synchronous @validate rules")
|
|
42
|
+
post_init = getattr(cls, "__attrs_post_init__", None)
|
|
43
|
+
|
|
44
|
+
def validate_components(self):
|
|
45
|
+
if post_init is not None:
|
|
46
|
+
post_init(self)
|
|
47
|
+
errors = []
|
|
48
|
+
failed = set()
|
|
49
|
+
for name, field in components.items():
|
|
50
|
+
component = getattr(self, name)
|
|
51
|
+
if field.type is float and type(component) is int:
|
|
52
|
+
component = float(component)
|
|
53
|
+
object.__setattr__(self, name, component)
|
|
54
|
+
if not isinstance(component, field.type) or (type(component) is bool and field.type is not bool):
|
|
55
|
+
error = FieldError(name, "type", f"Expected {field.type.__name__}")
|
|
56
|
+
else:
|
|
57
|
+
error = _constraint_error(name, field, component)
|
|
58
|
+
if error is not None:
|
|
59
|
+
errors.append(error)
|
|
60
|
+
failed.add(name)
|
|
61
|
+
for name, rule, message in rules["validate"]:
|
|
62
|
+
if name in failed or (name is None and failed):
|
|
63
|
+
continue
|
|
64
|
+
result = rule(self)
|
|
65
|
+
if isawaitable(result):
|
|
66
|
+
if hasattr(result, "close"):
|
|
67
|
+
result.close()
|
|
68
|
+
raise TypeError("Value validators must return synchronously")
|
|
69
|
+
if not result:
|
|
70
|
+
errors.append(FieldError(name, "custom", message))
|
|
71
|
+
if errors:
|
|
72
|
+
raise ValidationError(tuple(errors))
|
|
73
|
+
|
|
74
|
+
cls.__attrs_post_init__ = validate_components
|
|
75
|
+
configure_defaults(cls, components)
|
|
76
|
+
cls = attrs.frozen(cls, slots=False, init=True, eq=True, field_transformer=redact_fields(components))
|
|
77
|
+
attributes = attrs.fields(cls)
|
|
78
|
+
if {field.name for field in attributes} != components.keys() or any(not field.init for field in attributes):
|
|
79
|
+
raise TypeError("All value components must be constructor fields")
|
|
80
|
+
cls._value_components = {field.name: components[field.name] for field in attributes}
|
|
81
|
+
configure_serialization(cls, components, value_object=True)
|
|
82
|
+
register_model(cls)
|
|
83
|
+
return cls
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class ValueColumns:
|
|
88
|
+
name: str
|
|
89
|
+
type: type
|
|
90
|
+
nullable: bool
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def paths(self):
|
|
94
|
+
return tuple(f"{self.name}.{name}" for name in self.type._value_components)
|
|
95
|
+
|
|
96
|
+
def unpack(self, instance, backend):
|
|
97
|
+
if instance is None and self.nullable:
|
|
98
|
+
return dict.fromkeys(self.paths)
|
|
99
|
+
if not isinstance(instance, self.type):
|
|
100
|
+
raise ValidationError((FieldError(self.name, "type", f"Expected {self.type.__name__}"),))
|
|
101
|
+
return dict(zip(self.paths, (
|
|
102
|
+
self.unpack_component(name, getattr(instance, name), backend)
|
|
103
|
+
for name in self.type._value_components
|
|
104
|
+
)))
|
|
105
|
+
|
|
106
|
+
def unpack_component(self, name, component, backend):
|
|
107
|
+
field = self.type._value_components[name]
|
|
108
|
+
return encode_datetime(component, backend) if field.type is datetime else component
|
|
109
|
+
|
|
110
|
+
def load(self, values):
|
|
111
|
+
components = [values[path] for path in self.paths]
|
|
112
|
+
if self.nullable and all(component is None for component in components):
|
|
113
|
+
return None
|
|
114
|
+
if any(component is None for component in components):
|
|
115
|
+
raise ValidationError(tuple(
|
|
116
|
+
FieldError(path, "null", "Stored value component is null")
|
|
117
|
+
for path, component in zip(self.paths, components) if component is None
|
|
118
|
+
))
|
|
119
|
+
try:
|
|
120
|
+
decoded = {}
|
|
121
|
+
for attr, component in zip(attrs.fields(self.type), components):
|
|
122
|
+
field = self.type._value_components[attr.name]
|
|
123
|
+
if field.type is bool and type(component) is int and component in (0, 1):
|
|
124
|
+
component = bool(component)
|
|
125
|
+
if field.type is datetime:
|
|
126
|
+
try:
|
|
127
|
+
component = decode_datetime(component)
|
|
128
|
+
except (TypeError, ValueError) as error:
|
|
129
|
+
raise ValidationError((FieldError(attr.name, "type", "Expected a datetime"),)) from error
|
|
130
|
+
decoded[attr.alias] = component
|
|
131
|
+
return self.type(**decoded)
|
|
132
|
+
except ValidationError as error:
|
|
133
|
+
raise prefix_errors(self.name, error) from error
|
|
134
|
+
|
|
135
|
+
def null_check(self, columns):
|
|
136
|
+
names = [identifier(columns[path]) for path in self.paths]
|
|
137
|
+
missing = " AND ".join(f"({name} IS NULL)" for name in names)
|
|
138
|
+
present = " AND ".join(f"({name} IS NOT NULL)" for name in names)
|
|
139
|
+
return f"{VALUE_CHECK_PREFIX}({missing}) OR ({present})"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def table_columns(cls, names, metadata, references, overrides):
|
|
143
|
+
if overrides is None:
|
|
144
|
+
overrides = {}
|
|
145
|
+
if not isinstance(overrides, Mapping):
|
|
146
|
+
raise TypeError("columns must be a mapping")
|
|
147
|
+
columns = {}
|
|
148
|
+
values = {}
|
|
149
|
+
for name in names:
|
|
150
|
+
field = metadata[name]
|
|
151
|
+
if not hasattr(field.type, "_value_components"):
|
|
152
|
+
columns[name] = f"{name}_id" if name in references else name
|
|
153
|
+
continue
|
|
154
|
+
if any(marker[0] not in (Indexed, Unique, *CLASSIFICATIONS) for marker in field.markers):
|
|
155
|
+
raise TypeError(f"{cls.__qualname__}.{name}: unsupported marker on value field")
|
|
156
|
+
mapping = values[name] = ValueColumns(name, field.type, field.nullable)
|
|
157
|
+
paths = mapping.paths
|
|
158
|
+
for path, component in zip(paths, field.type._value_components):
|
|
159
|
+
columns[path] = name if len(paths) == 1 else f"{name}_{component}"
|
|
160
|
+
if unknown := overrides.keys() - columns.keys():
|
|
161
|
+
raise ValueError(f"Unknown column override: {next(iter(unknown))!r}")
|
|
162
|
+
columns.update(overrides)
|
|
163
|
+
if any(not isinstance(column, str) or not column or "\0" in column for column in columns.values()):
|
|
164
|
+
raise ValueError("Column names must be nonempty strings without null characters")
|
|
165
|
+
if len(set(columns.values())) != len(columns):
|
|
166
|
+
raise TypeError(f"Conflicting physical columns on {cls.__qualname__}")
|
|
167
|
+
return columns, values
|
narabi/project.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Project configuration shared by the application and CLI."""
|
|
2
|
+
|
|
3
|
+
from contextvars import ContextVar
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from importlib import import_module
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
import tomllib
|
|
10
|
+
|
|
11
|
+
from .database import Database
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_model_project = ContextVar("narabi_model_project", default=None)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Project:
|
|
19
|
+
root: Path
|
|
20
|
+
settings: dict
|
|
21
|
+
default_sqlite_path: str = "narabi.sqlite3"
|
|
22
|
+
profile: str | None = None
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def load(cls, path=None):
|
|
26
|
+
root = Path.cwd()
|
|
27
|
+
paths = (
|
|
28
|
+
(Path(path).resolve(),) if path is not None
|
|
29
|
+
else (directory / name for directory in (root, *root.parents)
|
|
30
|
+
for name in ("narabi.toml", "pyproject.toml"))
|
|
31
|
+
)
|
|
32
|
+
for candidate in paths:
|
|
33
|
+
if path is not None or candidate.is_file():
|
|
34
|
+
config = tomllib.loads(candidate.read_text(encoding="utf-8"))
|
|
35
|
+
if candidate.name != "pyproject.toml":
|
|
36
|
+
return cls(candidate.parent, config)
|
|
37
|
+
settings = config.get("tool", {}).get("narabi")
|
|
38
|
+
if settings is not None:
|
|
39
|
+
return cls(candidate.parent, settings)
|
|
40
|
+
raise FileNotFoundError("No Narabi configuration found. Run narabi init from your project root.")
|
|
41
|
+
|
|
42
|
+
def database_config(self, profile=None):
|
|
43
|
+
profile = profile or self.profile
|
|
44
|
+
base = self.settings.get("database", {})
|
|
45
|
+
profiles = self.settings.get("profiles", {})
|
|
46
|
+
if not profiles and not base:
|
|
47
|
+
profiles = {
|
|
48
|
+
name: entry for name, entry in self.settings.items()
|
|
49
|
+
if isinstance(entry, dict) and ("database" in entry or "database_env" in entry)
|
|
50
|
+
}
|
|
51
|
+
selected = profile or os.getenv("NARABI_ENV") or ("dev" if "dev" in profiles else None)
|
|
52
|
+
return {**base, **profiles[selected]} if selected and (profiles or profile) else base
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def backend(self):
|
|
56
|
+
return self.database_config().get("backend", "sqlite")
|
|
57
|
+
|
|
58
|
+
def database(self, *, profile=None, allow_pool=False):
|
|
59
|
+
settings = self.database_config(profile)
|
|
60
|
+
pool = settings.get("pool", False)
|
|
61
|
+
backend, target = self.database_settings(profile)
|
|
62
|
+
if type(pool) is not bool or (pool and backend != "postgresql"):
|
|
63
|
+
raise ValueError("pool must be a boolean and requires PostgreSQL when enabled")
|
|
64
|
+
return Database(backend, target, pool=pool and allow_pool)
|
|
65
|
+
|
|
66
|
+
def database_settings(self, profile=None):
|
|
67
|
+
settings = self.database_config(profile)
|
|
68
|
+
backend = settings.get("backend", "sqlite")
|
|
69
|
+
if variable := settings.get("url_env", settings.get("database_env")):
|
|
70
|
+
target = os.getenv(variable)
|
|
71
|
+
if not target:
|
|
72
|
+
raise ValueError(f"Set the {variable} environment variable to connect.")
|
|
73
|
+
else:
|
|
74
|
+
target = settings.get("path", settings.get("database", self.default_sqlite_path))
|
|
75
|
+
if backend != "sqlite":
|
|
76
|
+
raise ValueError("Configure database.url_env for PostgreSQL.")
|
|
77
|
+
if backend == "sqlite":
|
|
78
|
+
target = self.root / target
|
|
79
|
+
return backend, target
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def migration_dir(self):
|
|
83
|
+
return self.root / self.settings.get("migrations", "migrations")
|
|
84
|
+
|
|
85
|
+
def migrations(self):
|
|
86
|
+
baseline = tuple(self.root / path for path in self.settings.get("migration_baseline", []))
|
|
87
|
+
return baseline + tuple(sorted(
|
|
88
|
+
path for path in self.migration_dir.glob("*.py")
|
|
89
|
+
if path.is_file() and not path.name.startswith("_")
|
|
90
|
+
))
|
|
91
|
+
|
|
92
|
+
def models(self):
|
|
93
|
+
token = _model_project.set(self)
|
|
94
|
+
sys.path.insert(0, str(self.root))
|
|
95
|
+
try:
|
|
96
|
+
result = {}
|
|
97
|
+
for name in self.settings.get("models", []):
|
|
98
|
+
module = import_module(name)
|
|
99
|
+
for model in vars(module).values():
|
|
100
|
+
if (
|
|
101
|
+
isinstance(model, type) and model.__module__ == name
|
|
102
|
+
and "_record_metadata" in vars(model)
|
|
103
|
+
):
|
|
104
|
+
result[model] = None
|
|
105
|
+
return tuple(result)
|
|
106
|
+
finally:
|
|
107
|
+
sys.path.remove(str(self.root))
|
|
108
|
+
_model_project.reset(token)
|
narabi/py.typed
ADDED
|
File without changes
|
narabi/pytest.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Opt-in pytest fixtures for isolated Narabi databases."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from .database import Database
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.fixture
|
|
9
|
+
def narabi_db(tmp_path):
|
|
10
|
+
"""Return a fresh SQLite database path for each test."""
|
|
11
|
+
return Database("sqlite", tmp_path / "narabi.sqlite3")
|