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,196 @@
|
|
|
1
|
+
"""Store reference keys and resolve models when a relationship is used."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Generator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Any, ForwardRef, Generic, TypeVar, get_type_hints
|
|
7
|
+
from weakref import WeakValueDictionary
|
|
8
|
+
|
|
9
|
+
from ..database import Database, database_for
|
|
10
|
+
from ..fields import Ref, describe
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
T = TypeVar("T")
|
|
14
|
+
K = TypeVar("K")
|
|
15
|
+
_models = WeakValueDictionary()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def register_model(model):
|
|
19
|
+
_models[model.__module__, model.__qualname__] = model
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def model_namespace(model):
|
|
23
|
+
prefix, _, name = model.__qualname__.rpartition(".")
|
|
24
|
+
namespace = {
|
|
25
|
+
qualified.rpartition(".")[2]: target
|
|
26
|
+
for (module, qualified), target in _models.items()
|
|
27
|
+
if module == model.__module__ and qualified.rpartition(".")[0] == prefix
|
|
28
|
+
}
|
|
29
|
+
namespace.update(vars(model))
|
|
30
|
+
namespace[name] = model
|
|
31
|
+
return namespace
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def model_fields(model):
|
|
35
|
+
namespace = model_namespace(model)
|
|
36
|
+
pending = set()
|
|
37
|
+
while True:
|
|
38
|
+
try:
|
|
39
|
+
hints = get_type_hints(model, localns=namespace)
|
|
40
|
+
break
|
|
41
|
+
except NameError as error:
|
|
42
|
+
if error.name is None or error.name in pending:
|
|
43
|
+
raise
|
|
44
|
+
pending.add(error.name)
|
|
45
|
+
namespace[error.name] = ForwardRef(error.name)
|
|
46
|
+
metadata = {name: describe(hint) for name, hint in hints.items()}
|
|
47
|
+
for name, annotation in vars(model).get("__annotations__", {}).items():
|
|
48
|
+
declared = describe(annotation)
|
|
49
|
+
if (Ref,) in declared.markers and isinstance(declared.type, ForwardRef):
|
|
50
|
+
# Keep quoted targets deferred even if get_type_hints found a
|
|
51
|
+
# same-named model left over from an earlier factory invocation.
|
|
52
|
+
metadata[name] = declared
|
|
53
|
+
for name, field in metadata.items():
|
|
54
|
+
if (Ref,) not in field.markers and isinstance(field.type, ForwardRef):
|
|
55
|
+
raise TypeError(f"Unresolved type for {model.__qualname__}.{name}: {field.type.__forward_arg__}")
|
|
56
|
+
return metadata
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Reference(Generic[T, K]):
|
|
60
|
+
"""An awaitable reference whose key is available without a query."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, instance, field):
|
|
63
|
+
self._instance = instance
|
|
64
|
+
self._field = field
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def id(self) -> K:
|
|
68
|
+
return self._field.read(self._instance)
|
|
69
|
+
|
|
70
|
+
async def _fetch(self) -> T:
|
|
71
|
+
key = self.id
|
|
72
|
+
if key is None:
|
|
73
|
+
if self._field.info.nullable:
|
|
74
|
+
return None
|
|
75
|
+
raise LookupError(f"Missing reference: {self._field.name}")
|
|
76
|
+
database = database_for(getattr(self._instance, "_record_state", None), None)
|
|
77
|
+
target = self._field.target()
|
|
78
|
+
cached = cached_relationship(self._instance, self._field, key, database)
|
|
79
|
+
if cached is not None:
|
|
80
|
+
if cached.value is None and not self._field.info.nullable:
|
|
81
|
+
raise LookupError(f"No {target.__name__} record found")
|
|
82
|
+
return cached.value
|
|
83
|
+
require_lazy_loading(self._instance, self._field.name)
|
|
84
|
+
if self._field.info.nullable:
|
|
85
|
+
return await target.find(key, db=database)
|
|
86
|
+
return await target.require(key, db=database)
|
|
87
|
+
|
|
88
|
+
def __await__(self) -> Generator[Any, None, T]:
|
|
89
|
+
return self._fetch().__await__()
|
|
90
|
+
|
|
91
|
+
def __repr__(self) -> str:
|
|
92
|
+
return repr(self.id)
|
|
93
|
+
|
|
94
|
+
def __eq__(self, other: object) -> bool:
|
|
95
|
+
return isinstance(other, Reference) and self._field is other._field and self.id == other.id
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class ReferenceField:
|
|
99
|
+
def __init__(self, owner, name, info):
|
|
100
|
+
self.owner = owner
|
|
101
|
+
self.name = name
|
|
102
|
+
self.info = info
|
|
103
|
+
self._target = None
|
|
104
|
+
|
|
105
|
+
def target(self):
|
|
106
|
+
if self._target is not None:
|
|
107
|
+
return self._target
|
|
108
|
+
target = self.info.type
|
|
109
|
+
if isinstance(target, ForwardRef):
|
|
110
|
+
target = target.__forward_arg__
|
|
111
|
+
if isinstance(target, str):
|
|
112
|
+
try:
|
|
113
|
+
target = eval(target, vars(sys.modules[self.owner.__module__]), model_namespace(self.owner))
|
|
114
|
+
except NameError as error:
|
|
115
|
+
raise TypeError(f"Unresolved reference {self.owner.__qualname__}.{self.name}: {target}") from error
|
|
116
|
+
if not isinstance(target, type) or not hasattr(target, "_record_key"):
|
|
117
|
+
raise TypeError(f"{self.owner.__qualname__}.{self.name} must reference a table model")
|
|
118
|
+
self._target = target
|
|
119
|
+
return target
|
|
120
|
+
|
|
121
|
+
def key(self, value):
|
|
122
|
+
if isinstance(value, Reference):
|
|
123
|
+
if value._field.target() is not self.target():
|
|
124
|
+
raise TypeError(f"Invalid reference for {self.name}")
|
|
125
|
+
return value.id
|
|
126
|
+
if hasattr(type(value), "_record_key"):
|
|
127
|
+
target = self.target()
|
|
128
|
+
if not isinstance(value, target):
|
|
129
|
+
raise TypeError(f"{self.name} expects a {target.__name__} reference")
|
|
130
|
+
if not value.persisted:
|
|
131
|
+
raise ValueError(f"{self.name} expects a saved {target.__name__}")
|
|
132
|
+
return value._record_state.key
|
|
133
|
+
return value
|
|
134
|
+
|
|
135
|
+
def read(self, instance):
|
|
136
|
+
return vars(instance)[self.name]
|
|
137
|
+
|
|
138
|
+
def __get__(self, instance, owner):
|
|
139
|
+
return self if instance is None else Reference(instance, self)
|
|
140
|
+
|
|
141
|
+
def __set__(self, instance, value):
|
|
142
|
+
vars(instance)[self.name] = self.key(value)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def reference_for(model, name):
|
|
146
|
+
references = getattr(model, "_record_references", {})
|
|
147
|
+
if name in references:
|
|
148
|
+
return references[name]
|
|
149
|
+
if name.endswith("_id"):
|
|
150
|
+
return references.get(name[:-3])
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def field_value(instance, name, *default):
|
|
155
|
+
reference = getattr(type(instance), "_record_references", {}).get(name)
|
|
156
|
+
return reference.read(instance) if reference is not None else getattr(instance, name, *default)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class _LoadedRelationship:
|
|
161
|
+
key: object
|
|
162
|
+
database: Database
|
|
163
|
+
value: Any
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def cache_relationship(instance, relationship, key, database, value):
|
|
167
|
+
cache = vars(instance).setdefault("_record_loaded_relationships", {})
|
|
168
|
+
entry = _LoadedRelationship(key, database, value)
|
|
169
|
+
cache[relationship] = entry
|
|
170
|
+
|
|
171
|
+
def invalidate():
|
|
172
|
+
if cache.get(relationship) is entry:
|
|
173
|
+
del cache[relationship]
|
|
174
|
+
|
|
175
|
+
database._on_rollback(invalidate)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cached_relationship(instance, relationship, key, database):
|
|
179
|
+
cache = vars(instance).get("_record_loaded_relationships", {})
|
|
180
|
+
entry = cache.get(relationship)
|
|
181
|
+
if entry is not None and entry.key == key and entry.database is database:
|
|
182
|
+
return entry
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def clear_relationship_cache(instance):
|
|
187
|
+
vars(instance).pop("_record_loaded_relationships", None)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class StrictLoadingError(RuntimeError):
|
|
191
|
+
"""An association would require a query on a strict-loaded record."""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def require_lazy_loading(instance, name):
|
|
195
|
+
if getattr(instance, "_record_strict_loading", False):
|
|
196
|
+
raise StrictLoadingError(f"{type(instance).__qualname__}.{name} requires a relationship query")
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Link table models through relationship declarations."""
|
|
2
|
+
|
|
3
|
+
from functools import partial, wraps
|
|
4
|
+
from typing import get_args, get_origin, get_type_hints
|
|
5
|
+
|
|
6
|
+
from ..database import database_for
|
|
7
|
+
from .references import cached_relationship, field_value, model_namespace, reference_for, require_lazy_loading
|
|
8
|
+
from ..query.relation import Relation, _Association, _LINK, _Through
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def relationship_field(model, related):
|
|
12
|
+
table = model._record_table_name
|
|
13
|
+
if table.endswith("ies"):
|
|
14
|
+
singular = table[:-3] + "y"
|
|
15
|
+
elif table.endswith(("sses", "shes", "ches", "xes", "zes")):
|
|
16
|
+
singular = table[:-2]
|
|
17
|
+
elif table.endswith("s") and not table.endswith("ss"):
|
|
18
|
+
singular = table[:-1]
|
|
19
|
+
else:
|
|
20
|
+
singular = table
|
|
21
|
+
for prefix in (singular, table):
|
|
22
|
+
name = f"{prefix}_{model._record_key}"
|
|
23
|
+
if name in related._record_fields:
|
|
24
|
+
return name
|
|
25
|
+
raise ValueError(f"Could not find a field linking {related.__name__} to {model.__name__}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class HasMany:
|
|
29
|
+
def __init__(self, function, via, through):
|
|
30
|
+
self.function = function
|
|
31
|
+
self.via = via
|
|
32
|
+
self.through = through
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def name(self):
|
|
36
|
+
return self.function.__name__
|
|
37
|
+
|
|
38
|
+
def signature(self, owner):
|
|
39
|
+
try:
|
|
40
|
+
hint = get_type_hints(self.function, localns=model_namespace(owner)).get("return")
|
|
41
|
+
except NameError as error:
|
|
42
|
+
raise TypeError(f"Unresolved relationship {owner.__qualname__}.{self.function.__name__}") from error
|
|
43
|
+
origin = get_origin(hint)
|
|
44
|
+
targets = get_args(hint)
|
|
45
|
+
if origin not in (Relation, list) or len(targets) != 1 or not hasattr(targets[0], "_record_key"):
|
|
46
|
+
raise TypeError("A has_many declaration must return Relation[Model] or list[Model]")
|
|
47
|
+
return origin, targets[0]
|
|
48
|
+
|
|
49
|
+
def _field(self, owner, target):
|
|
50
|
+
if self.via is not None:
|
|
51
|
+
reference = reference_for(target, self.via)
|
|
52
|
+
if reference is not None and reference.target() is owner:
|
|
53
|
+
return reference.name
|
|
54
|
+
if reference is None and self.via in target._record_fields:
|
|
55
|
+
return self.via
|
|
56
|
+
raise ValueError(f"Invalid via={self.via!r} for {owner.__name__}.{self.function.__name__}")
|
|
57
|
+
links = [
|
|
58
|
+
name for name, reference in target._record_references.items()
|
|
59
|
+
if reference.target() is owner
|
|
60
|
+
]
|
|
61
|
+
if len(links) > 1:
|
|
62
|
+
raise ValueError(f"Specify via for {owner.__name__}.{self.function.__name__}")
|
|
63
|
+
return links[0] if links else relationship_field(owner, target)
|
|
64
|
+
|
|
65
|
+
def _link(self, owner, target):
|
|
66
|
+
link = self.through
|
|
67
|
+
if link is None:
|
|
68
|
+
return None
|
|
69
|
+
for name, expected in ((link.source, owner), (link.target, target)):
|
|
70
|
+
reference = link.model._record_references.get(name)
|
|
71
|
+
if reference is None or reference.target() is not expected:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"{link.model.__qualname__}.{name} must be a Ref to {expected.__qualname__}"
|
|
74
|
+
)
|
|
75
|
+
return link
|
|
76
|
+
|
|
77
|
+
async def __call__(self, instance, *, db=None):
|
|
78
|
+
owner = type(instance)
|
|
79
|
+
relation_type, target = self.signature(owner)
|
|
80
|
+
if relation_type is not list:
|
|
81
|
+
raise TypeError("Await this relationship property directly")
|
|
82
|
+
state = getattr(instance, "_record_state", None)
|
|
83
|
+
link = self._link(owner, target)
|
|
84
|
+
if link is not None and state is None:
|
|
85
|
+
return []
|
|
86
|
+
value = state.key if link is not None else getattr(instance, owner._record_key)
|
|
87
|
+
if value is None:
|
|
88
|
+
return []
|
|
89
|
+
database = database_for(state, db)
|
|
90
|
+
cached = cached_relationship(instance, self, value, database)
|
|
91
|
+
if cached is not None:
|
|
92
|
+
return list(cached.value)
|
|
93
|
+
require_lazy_loading(instance, self.name)
|
|
94
|
+
if link is not None:
|
|
95
|
+
return await Relation(target, database)._through(link).where(**{f"{_LINK}.{link.source}": value})
|
|
96
|
+
field = self._field(owner, target)
|
|
97
|
+
return await target.where(db=database, **{field: value})
|
|
98
|
+
|
|
99
|
+
def __get__(self, instance, owner):
|
|
100
|
+
if instance is None:
|
|
101
|
+
return self
|
|
102
|
+
relation_type, target = self.signature(owner)
|
|
103
|
+
if relation_type is list:
|
|
104
|
+
return partial(self, instance)
|
|
105
|
+
link = self._link(owner, target)
|
|
106
|
+
field = f"{_LINK}.{link.source}" if link is not None else self._field(owner, target)
|
|
107
|
+
state = getattr(instance, "_record_state", None)
|
|
108
|
+
key = state.key if state is not None else None
|
|
109
|
+
database = state.database if state is not None else None
|
|
110
|
+
relation = Relation(target, database, association=_Association(instance, self, field, key))
|
|
111
|
+
if link is not None:
|
|
112
|
+
relation = relation._through(link)
|
|
113
|
+
return relation.where(**{field: key})
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def has_many(method=None, *, via=None, through=None, source=None, target=None):
|
|
117
|
+
"""Declare a collection, optionally through a persistent link model."""
|
|
118
|
+
link = None
|
|
119
|
+
if through is not None:
|
|
120
|
+
if not isinstance(through, type) or "_record_key" not in vars(through):
|
|
121
|
+
raise TypeError("through must be a persistent model")
|
|
122
|
+
if via is not None or not all(isinstance(name, str) and name for name in (source, target)):
|
|
123
|
+
raise TypeError("through requires source and target reference names")
|
|
124
|
+
if source == target:
|
|
125
|
+
raise ValueError("source and target must name distinct references")
|
|
126
|
+
link = _Through(through, source, target)
|
|
127
|
+
elif source is not None or target is not None:
|
|
128
|
+
raise TypeError("source and target require through")
|
|
129
|
+
|
|
130
|
+
def decorate(function):
|
|
131
|
+
return HasMany(function, via, link)
|
|
132
|
+
|
|
133
|
+
return decorate if method is None else decorate(method)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def belongs_to(method=None, *, via=None):
|
|
137
|
+
"""Fill in an empty method annotated with its related record."""
|
|
138
|
+
|
|
139
|
+
def decorate(method):
|
|
140
|
+
def resolve(owner):
|
|
141
|
+
hint = get_type_hints(method, localns=model_namespace(owner))["return"]
|
|
142
|
+
targets = [target for target in get_args(hint) if target is not type(None)]
|
|
143
|
+
target = targets[0] if len(targets) == 1 else hint
|
|
144
|
+
if not hasattr(target, "_record_key"):
|
|
145
|
+
raise TypeError("A belongs_to method must return a record type")
|
|
146
|
+
return target, via or relationship_field(target, owner)
|
|
147
|
+
|
|
148
|
+
@wraps(method)
|
|
149
|
+
async def fetch(self, *, db=None):
|
|
150
|
+
target, field = resolve(type(self))
|
|
151
|
+
value = field_value(self, field)
|
|
152
|
+
if value is None:
|
|
153
|
+
return None
|
|
154
|
+
database = database_for(getattr(self, "_record_state", None), db)
|
|
155
|
+
cached = cached_relationship(self, fetch, value, database)
|
|
156
|
+
if cached is not None:
|
|
157
|
+
return cached.value
|
|
158
|
+
require_lazy_loading(self, method.__name__)
|
|
159
|
+
return await target.find(value, db=database)
|
|
160
|
+
|
|
161
|
+
fetch._record_relationship = True
|
|
162
|
+
fetch._record_join = resolve
|
|
163
|
+
return fetch
|
|
164
|
+
|
|
165
|
+
return decorate if method is None else decorate(method)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def describe_join(model, name):
|
|
169
|
+
"""Resolve the target and fields used to join an association."""
|
|
170
|
+
from inspect import getattr_static
|
|
171
|
+
|
|
172
|
+
descriptor = getattr_static(model, name, None)
|
|
173
|
+
reference = reference_for(model, name)
|
|
174
|
+
if reference is not None and descriptor is reference:
|
|
175
|
+
target = reference.target()
|
|
176
|
+
return target, reference.name, target._record_key, None
|
|
177
|
+
if isinstance(descriptor, HasMany):
|
|
178
|
+
_, target = descriptor.signature(model)
|
|
179
|
+
link = descriptor._link(model, target)
|
|
180
|
+
field = target._record_key if link is not None else descriptor._field(model, target)
|
|
181
|
+
return target, model._record_key, field, link
|
|
182
|
+
if resolver := getattr(descriptor, "_record_join", None):
|
|
183
|
+
target, field = resolver(model)
|
|
184
|
+
return target, field, target._record_key, None
|
|
185
|
+
raise ValueError(f"Unknown relationship {model.__name__}.{name}")
|
narabi/schema.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from graphlib import TopologicalSorter
|
|
3
|
+
from math import isfinite
|
|
4
|
+
|
|
5
|
+
from .database import identifier
|
|
6
|
+
from .models.timestamps import decode_datetime
|
|
7
|
+
|
|
8
|
+
_TYPES = {"integer": int, "text": str, "boolean": bool, "real": float, "datetime": datetime}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _name(definition):
|
|
12
|
+
name = definition["name"]
|
|
13
|
+
if not isinstance(name, str) or not name or "\0" in name:
|
|
14
|
+
raise ValueError("Expected a nonempty name")
|
|
15
|
+
return name
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _literal(value):
|
|
19
|
+
if isinstance(value, datetime):
|
|
20
|
+
value = decode_datetime(value).isoformat(timespec="microseconds")
|
|
21
|
+
if isinstance(value, str):
|
|
22
|
+
return "'" + value.replace("'", "''") + "'"
|
|
23
|
+
if isinstance(value, bool):
|
|
24
|
+
return "TRUE" if value else "FALSE"
|
|
25
|
+
return str(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _field_sql(field, dialect):
|
|
29
|
+
name = _name(field)
|
|
30
|
+
kind = field["type"]
|
|
31
|
+
expected = _TYPES[kind]
|
|
32
|
+
for option in ("primary", "auto_increment", "nullable", "unique"):
|
|
33
|
+
if option in field and type(field[option]) is not bool:
|
|
34
|
+
raise ValueError(f"{option} must be a boolean")
|
|
35
|
+
primary = field.get("primary", False)
|
|
36
|
+
automatic = field.get("auto_increment", False)
|
|
37
|
+
nullable = field.get("nullable", False)
|
|
38
|
+
if automatic and (kind != "integer" or not primary or "default" in field):
|
|
39
|
+
raise ValueError("Generated IDs require an integer primary field without a default")
|
|
40
|
+
if primary and nullable:
|
|
41
|
+
raise ValueError("Primary fields cannot be nullable")
|
|
42
|
+
sql_type = kind.upper()
|
|
43
|
+
if kind == "datetime":
|
|
44
|
+
sql_type = "TEXT" if dialect == "sqlite" else "TIMESTAMPTZ"
|
|
45
|
+
parts = [identifier(name), sql_type]
|
|
46
|
+
if automatic and dialect == "postgresql":
|
|
47
|
+
parts.append("GENERATED BY DEFAULT AS IDENTITY")
|
|
48
|
+
if primary:
|
|
49
|
+
parts.append("PRIMARY KEY")
|
|
50
|
+
if automatic and dialect == "sqlite":
|
|
51
|
+
parts.append("AUTOINCREMENT")
|
|
52
|
+
if not nullable:
|
|
53
|
+
parts.append("NOT NULL")
|
|
54
|
+
if field.get("unique", False):
|
|
55
|
+
parts.append("UNIQUE")
|
|
56
|
+
if "default" in field:
|
|
57
|
+
default = field["default"]
|
|
58
|
+
allowed = (int, float) if expected is float else (expected,)
|
|
59
|
+
if type(default) not in allowed:
|
|
60
|
+
raise ValueError(f"Default must match {kind}")
|
|
61
|
+
if isinstance(default, float) and not isfinite(default):
|
|
62
|
+
raise ValueError("Default must be finite")
|
|
63
|
+
parts.extend(("DEFAULT", _literal(default)))
|
|
64
|
+
if "references" in field:
|
|
65
|
+
target = field["references"]
|
|
66
|
+
parts.append(f"REFERENCES {identifier(target['table'])} ({identifier(target['field'])})")
|
|
67
|
+
return " ".join(parts)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def generate_sql(schema, dialect):
|
|
71
|
+
return "\n\n".join(schema_statements(schema, dialect))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def schema_statements(schema, dialect):
|
|
75
|
+
if dialect not in {"sqlite", "postgresql"}:
|
|
76
|
+
raise ValueError(f"Unsupported dialect: {dialect}")
|
|
77
|
+
tables = {}
|
|
78
|
+
fields = {}
|
|
79
|
+
for table in schema["tables"]:
|
|
80
|
+
name = _name(table)
|
|
81
|
+
if name in tables:
|
|
82
|
+
raise ValueError(f"Duplicate table: {name}")
|
|
83
|
+
tables[name] = table
|
|
84
|
+
by_name = {_name(field): field for field in table["fields"]}
|
|
85
|
+
if not by_name or len(by_name) != len(table["fields"]):
|
|
86
|
+
raise ValueError(f"{name}: fields must be nonempty and unique")
|
|
87
|
+
if sum(bool(field.get("primary")) for field in by_name.values()) > 1:
|
|
88
|
+
raise ValueError(f"{name}: only one primary field is supported")
|
|
89
|
+
fields[name] = by_name
|
|
90
|
+
|
|
91
|
+
definitions = {}
|
|
92
|
+
order = TopologicalSorter()
|
|
93
|
+
for name, table in tables.items():
|
|
94
|
+
order.add(name)
|
|
95
|
+
definitions[name] = []
|
|
96
|
+
for key, field in fields[name].items():
|
|
97
|
+
try:
|
|
98
|
+
if reference := field.get("references"):
|
|
99
|
+
target_table = reference["table"]
|
|
100
|
+
target = fields[target_table][reference["field"]]
|
|
101
|
+
if target["type"] != field["type"]:
|
|
102
|
+
raise ValueError("Referenced field must have the same type")
|
|
103
|
+
if not (target.get("primary") or target.get("unique")):
|
|
104
|
+
raise ValueError("Referenced field must be primary or unique")
|
|
105
|
+
if target_table != name:
|
|
106
|
+
order.add(name, target_table)
|
|
107
|
+
definitions[name].append(_field_sql(field, dialect))
|
|
108
|
+
except (KeyError, TypeError, ValueError) as error:
|
|
109
|
+
raise ValueError(f"{name}.{key}: {error}") from error
|
|
110
|
+
|
|
111
|
+
statements = []
|
|
112
|
+
for name in order.static_order():
|
|
113
|
+
checks = tables[name].get("checks", ())
|
|
114
|
+
if not isinstance(checks, (list, tuple)):
|
|
115
|
+
raise ValueError(f"{name}: checks must be a sequence of SQL expressions")
|
|
116
|
+
for check in checks:
|
|
117
|
+
if not isinstance(check, str) or not check.strip() or "\0" in check:
|
|
118
|
+
raise ValueError(f"{name}: check must be a nonempty SQL expression")
|
|
119
|
+
definitions[name].append(f"CHECK ({check})")
|
|
120
|
+
body = ",\n ".join(definitions[name])
|
|
121
|
+
statements.append(f"CREATE TABLE {identifier(name)} (\n {body}\n);")
|
|
122
|
+
for number, index in enumerate(tables[name].get("indexes", []), 1):
|
|
123
|
+
keys = index["fields"]
|
|
124
|
+
if not keys or any(key not in fields[name] for key in keys):
|
|
125
|
+
raise ValueError(f"{name}: index must name existing fields")
|
|
126
|
+
names = ", ".join(map(identifier, keys))
|
|
127
|
+
unique = "UNIQUE " if index.get("unique") else ""
|
|
128
|
+
index_name = identifier(index.get("name", f"{name}_idx_{number}"))
|
|
129
|
+
statements.append(
|
|
130
|
+
f"CREATE {unique}INDEX {index_name} ON {identifier(name)} ({names});"
|
|
131
|
+
)
|
|
132
|
+
return tuple(statements)
|