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
narabi/stubs.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Emit typing declarations for source modules containing Narabi models."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import inspect
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
from typing import get_args, get_origin
|
|
8
|
+
|
|
9
|
+
import attrs
|
|
10
|
+
|
|
11
|
+
from .query.relation import Relation
|
|
12
|
+
from .relations.relationships import HasMany
|
|
13
|
+
from .query.scopes import Scope
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_API = """
|
|
17
|
+
from decimal import Decimal as _RecordDecimal
|
|
18
|
+
from collections.abc import Iterable as _RecordIterable, Mapping as _RecordMapping
|
|
19
|
+
from typing import Any as _RecordAny, ClassVar as _RecordClassVar, Self as _RecordSelf
|
|
20
|
+
from typing import TypeVar as _RecordTypeVar
|
|
21
|
+
from narabi import Database as _RecordDatabase, Relation as _RecordRelation
|
|
22
|
+
from narabi import ValidationResult as _RecordValidation
|
|
23
|
+
from narabi.query.expressions import Descending as _RecordDescending, Field as _RecordField
|
|
24
|
+
from narabi.query.expressions import Predicate as _RecordPredicate
|
|
25
|
+
from narabi.relations.references import Reference as _RecordReference
|
|
26
|
+
from narabi.query.relation import _Scalar as _RecordScalar
|
|
27
|
+
|
|
28
|
+
_RecordProjection = _RecordTypeVar("_RecordProjection")
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
_RECORD_METHODS = """
|
|
32
|
+
async def validate(self) -> _RecordValidation: ...
|
|
33
|
+
def to_dict(self, *, include_private: bool = ...) -> dict[str, _RecordAny]: ...
|
|
34
|
+
def to_json(self, *, include_private: bool = ...) -> str: ...
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_dict(cls, data: _RecordMapping[str, _RecordAny]) -> _RecordSelf: ...
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_record(cls, source: object) -> _RecordSelf: ...
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
_TABLE_METHODS = """
|
|
42
|
+
all: _RecordClassVar[{class_relation}]
|
|
43
|
+
count: _RecordClassVar[_RecordScalar[int]]
|
|
44
|
+
exists: _RecordClassVar[_RecordScalar[bool]]
|
|
45
|
+
@classmethod
|
|
46
|
+
async def avg(cls, field: str | _RecordField, *, db: _RecordDatabase | None = None) -> float | _RecordDecimal | None: ...
|
|
47
|
+
@classmethod
|
|
48
|
+
async def sum(cls, field: str | _RecordField, *, db: _RecordDatabase | None = None) -> int | float | _RecordDecimal | None: ...
|
|
49
|
+
@classmethod
|
|
50
|
+
def where(cls, *predicates: _RecordPredicate, db: _RecordDatabase | None = None, **values: object) -> {method_relation}: ...
|
|
51
|
+
@classmethod
|
|
52
|
+
def order_by(cls, name: str | _RecordField | _RecordDescending, *, descending: bool = False, db: _RecordDatabase | None = None) -> {method_relation}: ...
|
|
53
|
+
@classmethod
|
|
54
|
+
async def select(cls, target: type[_RecordProjection], *, db: _RecordDatabase | None = None) -> list[_RecordProjection]: ...
|
|
55
|
+
@classmethod
|
|
56
|
+
async def find(cls, value: {key_type}, *, db: _RecordDatabase | None = None) -> _RecordSelf | None: ...
|
|
57
|
+
@classmethod
|
|
58
|
+
async def require(cls, value: {key_type}, *, db: _RecordDatabase | None = None) -> _RecordSelf: ...
|
|
59
|
+
@classmethod
|
|
60
|
+
async def find_by(cls, *, db: _RecordDatabase | None = None, **values: object) -> _RecordSelf | None: ...
|
|
61
|
+
@classmethod
|
|
62
|
+
async def create(cls, *, db: _RecordDatabase | None = None, **values: object) -> _RecordSelf: ...
|
|
63
|
+
@classmethod
|
|
64
|
+
async def bulk_insert(cls, rows: _RecordIterable[_RecordMapping[str, object]], *, db: _RecordDatabase | None = None) -> int: ...
|
|
65
|
+
@classmethod
|
|
66
|
+
async def bulk_upsert(cls, rows: _RecordIterable[_RecordMapping[str, object]], *, conflict: str | _RecordIterable[str], update: str | _RecordIterable[str], db: _RecordDatabase | None = None) -> int: ...
|
|
67
|
+
async def update(self, *, db: _RecordDatabase | None = None, **values: object) -> _RecordSelf: ...
|
|
68
|
+
async def save(self, *, db: _RecordDatabase | None = None) -> None: ...
|
|
69
|
+
async def delete(self, *, db: _RecordDatabase | None = None) -> bool: ...
|
|
70
|
+
@property
|
|
71
|
+
def persisted(self) -> bool: ...
|
|
72
|
+
@property
|
|
73
|
+
def changed(self) -> bool: ...
|
|
74
|
+
@property
|
|
75
|
+
def changes(self) -> dict[str, tuple[object, object]]: ...
|
|
76
|
+
def discard_changes(self) -> None: ...
|
|
77
|
+
async def refresh(self, *, db: _RecordDatabase | None = None) -> None: ...
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
_SOFT_DELETE_METHODS = """
|
|
82
|
+
with_deleted: _RecordClassVar[{class_relation}]
|
|
83
|
+
async def restore(self, *, db: _RecordDatabase | None = None) -> bool: ...
|
|
84
|
+
async def destroy(self, *, db: _RecordDatabase | None = None) -> bool: ...
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _Declarations(ast.NodeTransformer):
|
|
89
|
+
def visit_FunctionDef(self, node):
|
|
90
|
+
node.body = [ast.Expr(value=ast.Constant(value=Ellipsis))]
|
|
91
|
+
return node
|
|
92
|
+
|
|
93
|
+
visit_AsyncFunctionDef = visit_FunctionDef
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _annotation(field, render: Callable[[object], str], *, nullable=False) -> str:
|
|
97
|
+
annotation = render(field.type)
|
|
98
|
+
return f"{annotation} | None" if field.nullable or nullable else annotation
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _scope_method(member, relation, *, receiver, decorator):
|
|
102
|
+
result = deepcopy(member)
|
|
103
|
+
first = (result.args.posonlyargs or result.args.args)[0]
|
|
104
|
+
first.arg, first.annotation = receiver, None
|
|
105
|
+
result.returns = ast.Name(id=relation)
|
|
106
|
+
result.decorator_list = [ast.Name(id=decorator)] if decorator else []
|
|
107
|
+
result.args.defaults = [ast.Constant(value=Ellipsis) for value in result.args.defaults]
|
|
108
|
+
result.args.kw_defaults = [
|
|
109
|
+
None if value is None else ast.Constant(value=Ellipsis)
|
|
110
|
+
for value in result.args.kw_defaults
|
|
111
|
+
]
|
|
112
|
+
return result
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _model_body(node, cls, render, scope_declarations, relation_name):
|
|
116
|
+
metadata = cls._record_metadata
|
|
117
|
+
fields = {field.name: field for field in attrs.fields(cls) if field.init}
|
|
118
|
+
managed_fields = vars(cls).get("_record_managed_fields", ())
|
|
119
|
+
automatic_key = vars(cls).get("_record_automatic_key")
|
|
120
|
+
annotations = {}
|
|
121
|
+
declarations = [f"{name}: {_annotation(metadata[name], render)}" for name in managed_fields]
|
|
122
|
+
references = vars(cls).get("_record_references", {})
|
|
123
|
+
for name in fields:
|
|
124
|
+
reference = references.get(name)
|
|
125
|
+
if reference is None:
|
|
126
|
+
annotations[name] = _annotation(metadata[name], render, nullable=name == automatic_key)
|
|
127
|
+
declarations.append(f"{name}: {annotations[name]}")
|
|
128
|
+
continue
|
|
129
|
+
target = reference.target()
|
|
130
|
+
model_type = render(target)
|
|
131
|
+
key_type = render(target._record_metadata[target._record_key].type)
|
|
132
|
+
suffix = " | None" if metadata[name].nullable else ""
|
|
133
|
+
annotations[name] = f"{model_type} | {key_type}{suffix}"
|
|
134
|
+
declarations.extend([
|
|
135
|
+
"@property",
|
|
136
|
+
f"def {name}(self) -> _RecordReference[{model_type}{suffix}, {key_type}{suffix}]: ...",
|
|
137
|
+
f"@{name}.setter",
|
|
138
|
+
f"def {name}(self, value: {annotations[name]}) -> None: ...",
|
|
139
|
+
])
|
|
140
|
+
if not any(isinstance(member, ast.FunctionDef) and member.name == "__init__" for member in node.body):
|
|
141
|
+
aliases = {field.alias: field.name for field in fields.values()}
|
|
142
|
+
parameters = ["self"]
|
|
143
|
+
keyword_only = False
|
|
144
|
+
for name, parameter in inspect.signature(cls).parameters.items():
|
|
145
|
+
if parameter.kind is inspect.Parameter.KEYWORD_ONLY and not keyword_only:
|
|
146
|
+
parameters.append("*")
|
|
147
|
+
keyword_only = True
|
|
148
|
+
declaration = f"{name}: {annotations[aliases[name]]}"
|
|
149
|
+
if parameter.default is not inspect.Parameter.empty:
|
|
150
|
+
declaration += " = ..."
|
|
151
|
+
parameters.append(declaration)
|
|
152
|
+
declarations.append(f"def __init__({', '.join(parameters)}) -> None: ...")
|
|
153
|
+
generated = ast.parse("\n".join(declarations) + _RECORD_METHODS).body
|
|
154
|
+
if "_record_key" in vars(cls):
|
|
155
|
+
key_type = render(metadata[cls._record_key].type)
|
|
156
|
+
class_relation = relation_name or f"_RecordRelation[{cls.__name__}]"
|
|
157
|
+
generated.extend(ast.parse(_TABLE_METHODS.format(
|
|
158
|
+
key_type=key_type,
|
|
159
|
+
class_relation=class_relation,
|
|
160
|
+
method_relation=relation_name or "_RecordRelation[_RecordSelf]",
|
|
161
|
+
)).body)
|
|
162
|
+
if vars(cls).get("_record_soft_delete"):
|
|
163
|
+
generated.extend(ast.parse(_SOFT_DELETE_METHODS.format(class_relation=class_relation)).body)
|
|
164
|
+
for member, scope in scope_declarations:
|
|
165
|
+
if scope.is_property:
|
|
166
|
+
generated.extend(ast.parse(f"{member.name}: _RecordClassVar[{relation_name}]").body)
|
|
167
|
+
else:
|
|
168
|
+
generated.append(_scope_method(member, relation_name, receiver="cls", decorator="classmethod"))
|
|
169
|
+
replaced = {
|
|
170
|
+
member.name if isinstance(member, ast.FunctionDef | ast.AsyncFunctionDef) else member.target.id
|
|
171
|
+
for member in generated
|
|
172
|
+
}
|
|
173
|
+
for member in node.body:
|
|
174
|
+
if isinstance(member, ast.AnnAssign) and isinstance(member.target, ast.Name):
|
|
175
|
+
if member.target.id in replaced:
|
|
176
|
+
continue
|
|
177
|
+
if isinstance(member, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
178
|
+
actual = vars(cls).get(member.name)
|
|
179
|
+
if member.name in replaced or getattr(actual, "_record_rules", ()) or getattr(actual, "_record_hooks", ()):
|
|
180
|
+
continue
|
|
181
|
+
if isinstance(actual, HasMany):
|
|
182
|
+
kind, target = actual.signature(cls)
|
|
183
|
+
if kind is Relation:
|
|
184
|
+
if target.__module__ == cls.__module__ and any(
|
|
185
|
+
isinstance(value, Scope) for value in vars(target).values()
|
|
186
|
+
):
|
|
187
|
+
target_relation = f"_RecordRelationFor{target.__name__}"
|
|
188
|
+
else:
|
|
189
|
+
target_relation = f"_RecordRelation[{render(target)}]"
|
|
190
|
+
generated.extend(ast.parse(
|
|
191
|
+
f"@property\ndef {member.name}(self) -> {target_relation}: ...",
|
|
192
|
+
).body)
|
|
193
|
+
continue
|
|
194
|
+
# Existing relationship methods expose an optional explicit database.
|
|
195
|
+
if isinstance(actual, HasMany) or getattr(actual, "_record_relationship", False):
|
|
196
|
+
member.decorator_list = []
|
|
197
|
+
member.args.kwonlyargs.append(ast.arg(arg="db", annotation=ast.parse(
|
|
198
|
+
"_RecordDatabase | None", mode="eval",
|
|
199
|
+
).body))
|
|
200
|
+
member.args.kw_defaults.append(ast.Constant(value=None))
|
|
201
|
+
if isinstance(member, ast.FunctionDef):
|
|
202
|
+
member = ast.AsyncFunctionDef(**vars(member))
|
|
203
|
+
generated.append(member)
|
|
204
|
+
return generated
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def generate_stub(module) -> str:
|
|
208
|
+
"""Return a sibling .pyi declaration for a trusted, importable source module."""
|
|
209
|
+
tree = ast.parse(inspect.getsource(module))
|
|
210
|
+
imports = {}
|
|
211
|
+
|
|
212
|
+
class QualifiedTypes(ast.NodeTransformer):
|
|
213
|
+
def visit_Attribute(self, node):
|
|
214
|
+
owner = ast.unparse(node.value)
|
|
215
|
+
if owner == module.__name__:
|
|
216
|
+
return ast.Name(id=node.attr)
|
|
217
|
+
if owner in imports:
|
|
218
|
+
return ast.Attribute(value=ast.Name(id=imports[owner]), attr=node.attr)
|
|
219
|
+
return self.generic_visit(node)
|
|
220
|
+
|
|
221
|
+
def render(annotation):
|
|
222
|
+
def collect(item):
|
|
223
|
+
owner = getattr(get_origin(item) or item, "__module__", None)
|
|
224
|
+
if owner and owner not in ("builtins", "types", module.__name__):
|
|
225
|
+
if owner not in imports:
|
|
226
|
+
imports[owner] = f"_RecordType{len(imports)}"
|
|
227
|
+
for argument in get_args(item):
|
|
228
|
+
collect(argument)
|
|
229
|
+
|
|
230
|
+
collect(annotation)
|
|
231
|
+
expression = ast.parse(inspect.formatannotation(annotation, base_module=module.__name__), mode="eval")
|
|
232
|
+
return ast.unparse(QualifiedTypes().visit(expression))
|
|
233
|
+
|
|
234
|
+
found = False
|
|
235
|
+
scoped_relations = []
|
|
236
|
+
for node in tree.body:
|
|
237
|
+
if not isinstance(node, ast.ClassDef):
|
|
238
|
+
continue
|
|
239
|
+
cls = vars(module).get(node.name)
|
|
240
|
+
if isinstance(cls, type) and "_record_metadata" in vars(cls):
|
|
241
|
+
scope_declarations = [
|
|
242
|
+
(member, vars(cls)[member.name])
|
|
243
|
+
for member in node.body
|
|
244
|
+
if isinstance(member, ast.FunctionDef) and isinstance(vars(cls).get(member.name), Scope)
|
|
245
|
+
] if "_record_key" in vars(cls) else []
|
|
246
|
+
relation_name = f"_RecordRelationFor{node.name}" if scope_declarations else None
|
|
247
|
+
if relation_name:
|
|
248
|
+
relation = ast.parse(f"class {relation_name}(_RecordRelation[{node.name}]): ...").body[0]
|
|
249
|
+
relation.body = [
|
|
250
|
+
_scope_method(member, relation_name, receiver="self", decorator="property" if scope.is_property else None)
|
|
251
|
+
for member, scope in scope_declarations
|
|
252
|
+
]
|
|
253
|
+
scoped_relations.append(relation)
|
|
254
|
+
node.body = _model_body(node, cls, render, scope_declarations, relation_name)
|
|
255
|
+
node.decorator_list = []
|
|
256
|
+
found = True
|
|
257
|
+
if not found:
|
|
258
|
+
raise ValueError(f"No Narabi models declared in {module.__name__}")
|
|
259
|
+
|
|
260
|
+
tree.body.extend(scoped_relations)
|
|
261
|
+
index = 0
|
|
262
|
+
if isinstance(tree.body[0], ast.Expr) and isinstance(tree.body[0].value, ast.Constant):
|
|
263
|
+
index = 1
|
|
264
|
+
while index < len(tree.body):
|
|
265
|
+
node = tree.body[index]
|
|
266
|
+
if not isinstance(node, ast.ImportFrom) or node.module != "__future__":
|
|
267
|
+
break
|
|
268
|
+
index += 1
|
|
269
|
+
prelude = "".join(f"import {name} as {alias}\n" for name, alias in imports.items()) + _API
|
|
270
|
+
tree.body[index:index] = ast.parse(prelude).body
|
|
271
|
+
tree.body = [
|
|
272
|
+
node for node in tree.body
|
|
273
|
+
if not (isinstance(node, ast.If) and ast.unparse(node.test) == "__name__ == '__main__'")
|
|
274
|
+
]
|
|
275
|
+
return "# Generated by python -m narabi stubs.\n" + ast.unparse(_Declarations().visit(tree)) + "\n"
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: narabi-orm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An asynchronous Active Record ORM for Python.
|
|
5
|
+
Project-URL: Homepage, https://github.com/RickBarretto/narabi-orm
|
|
6
|
+
Project-URL: Documentation, https://github.com/RickBarretto/narabi-orm/tree/main/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/RickBarretto/narabi-orm
|
|
8
|
+
Project-URL: Issues, https://github.com/RickBarretto/narabi-orm/issues
|
|
9
|
+
License-Expression: BSD-3-Clause
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: active-record,async,orm,postgresql,sqlite
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Database
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.12
|
|
19
|
+
Requires-Dist: attrs>=23.2
|
|
20
|
+
Requires-Dist: cattrs>=24.1
|
|
21
|
+
Requires-Dist: cyclopts<5,>=4
|
|
22
|
+
Provides-Extra: all
|
|
23
|
+
Requires-Dist: aiosqlite; extra == 'all'
|
|
24
|
+
Requires-Dist: ipython<10,>=9; extra == 'all'
|
|
25
|
+
Requires-Dist: psycopg-pool; extra == 'all'
|
|
26
|
+
Requires-Dist: psycopg[binary]; extra == 'all'
|
|
27
|
+
Provides-Extra: console
|
|
28
|
+
Requires-Dist: ipython<10,>=9; extra == 'console'
|
|
29
|
+
Provides-Extra: postgres
|
|
30
|
+
Requires-Dist: psycopg-pool; extra == 'postgres'
|
|
31
|
+
Requires-Dist: psycopg[binary]; extra == 'postgres'
|
|
32
|
+
Provides-Extra: sqlite
|
|
33
|
+
Requires-Dist: aiosqlite; extra == 'sqlite'
|
|
34
|
+
Provides-Extra: test
|
|
35
|
+
Requires-Dist: aiosqlite; extra == 'test'
|
|
36
|
+
Requires-Dist: ipython<10,>=9; extra == 'test'
|
|
37
|
+
Requires-Dist: pytest; extra == 'test'
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
# Narabi
|
|
41
|
+
|
|
42
|
+
Narabi is an async Active Record library for Python. Declare a model with ordinary type annotations, then create, query, and update rows through that model. Use SQLite for a local project or PostgreSQL for a service.
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from narabi import Increment, Primary, table
|
|
46
|
+
|
|
47
|
+
@table
|
|
48
|
+
class Book:
|
|
49
|
+
id: Primary[int] = Increment()
|
|
50
|
+
title: str
|
|
51
|
+
|
|
52
|
+
book = await Book.create(title="A Wizard of Earthsea")
|
|
53
|
+
saved = await Book.require(book.id)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The example assumes a project scaffolded with `narabi init` and a migrated `books` table. Narabi infers `books` from `Book`. The [bookstore tutorial](docs/tutorial.md) builds both from a clean directory.
|
|
57
|
+
|
|
58
|
+
## Privacy belongs in the model
|
|
59
|
+
|
|
60
|
+
A bookstore needs a customer's contact details. Its logs and JSON responses rarely need all of them.
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from narabi import Personal, Private, Sensitive, record
|
|
64
|
+
|
|
65
|
+
@record
|
|
66
|
+
class CustomerContact:
|
|
67
|
+
email: Personal[str]
|
|
68
|
+
access_token: Private[Sensitive[str]]
|
|
69
|
+
|
|
70
|
+
contact = CustomerContact(email="reader@example.test", access_token="demo-token")
|
|
71
|
+
print(contact)
|
|
72
|
+
# CustomerContact(email=<redacted>, access_token=<redacted>)
|
|
73
|
+
print(contact.to_dict())
|
|
74
|
+
# {'email': 'reader@example.test'}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
All three markers redact values in record representations. `Private` also omits the field from default serialization. `narabi privacy inventory` lists classifications from configured models without reading stored rows. If the record lives in a configured module named `models`, the inventory includes:
|
|
78
|
+
|
|
79
|
+
```text
|
|
80
|
+
models.CustomerContact.email: Personal
|
|
81
|
+
models.CustomerContact.access_token: Private, Sensitive
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
See [Privacy and serialization](docs/guides.md#privacy-and-serialization).
|
|
85
|
+
|
|
86
|
+
## From a model to a running app
|
|
87
|
+
|
|
88
|
+
- Generate an editable Python migration, review the changes, and apply it. Render SQL offline or load a versioned schema snapshot. [Migration workflows](docs/guides.md#migrations-and-recovery)
|
|
89
|
+
- Compose queries, load associations, and inspect SQL and query plans. [API reference](docs/reference.md)
|
|
90
|
+
- Try a write in `narabi console --sandbox` and see it in the next cell. Exit to roll it back. [Console guide](docs/guides.md#console)
|
|
91
|
+
- Use the same models in a [FastAPI app](docs/fastapi.md) or a [Flask app](docs/flask.md).
|
|
92
|
+
|
|
93
|
+
## How it fits
|
|
94
|
+
|
|
95
|
+
| Library | Where persistence lives |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| Narabi | Async operations on Python models, with a `Database` for connections and explicit transactions |
|
|
98
|
+
| Rails Active Record | Persistence and queries on Ruby models within the Rails conventions |
|
|
99
|
+
| SQLModel | Typed Python models based on Pydantic and SQLAlchemy, with persistence through a session |
|
|
100
|
+
| SQLAlchemy ORM | Mapped Python classes, SQL expressions, and a session that manages a unit of work |
|
|
101
|
+
|
|
102
|
+
[Compare the same bookstore operations](docs/comparisons.md) · [Why Narabi exists](PITCH.md) · [Documentation](docs/README.md) · [Contributing](CONTRIBUTING.md)
|
|
103
|
+
|
|
104
|
+
Narabi is released under the [BSD 3-Clause License](LICENSE).
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
narabi/__init__.py,sha256=PdzAXNWzykUm6YY0t3GdvpNt01ejYSy4XfT7dkQ86X0,1291
|
|
2
|
+
narabi/__main__.py,sha256=wu5N2wk8mvBgyvr2ghmQf4prezAe0_i-p123VVreyYc,62
|
|
3
|
+
narabi/cli.py,sha256=7M80uvrj_ZS1edIezHPop6n_hdTkfnMXzNEepuE_llc,13602
|
|
4
|
+
narabi/console.py,sha256=KdXAROLk7pbiEwZeLYNBIkBI_gb9_YE5OwnoAR1w5WU,3432
|
|
5
|
+
narabi/database.py,sha256=6MxLSW4H2ZahiWGVgb561l1pn3DeXdns9KxNFO1raQ4,11214
|
|
6
|
+
narabi/project.py,sha256=782WHJcJRDicy0mp_7b_T1HbjZS7odnC2LQT8bGmxNw,4287
|
|
7
|
+
narabi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
narabi/pytest.py,sha256=EU3v5wBJuR9DoeevIQcaEPXvb64baVgcfdM87JJZNaQ,270
|
|
9
|
+
narabi/schema.py,sha256=QwBHiLYdZcs6EFpDCo-zqrSlnZnQxMDr4b94h0rXkBM,5678
|
|
10
|
+
narabi/stubs.py,sha256=zBhYVyNxNKg_mXm7tMCeYRDDSTDdXoYhLNxA34FqRYs,13076
|
|
11
|
+
narabi/fields/__init__.py,sha256=CcySPQWnW1RmXaMgEBY3vKhglVymzjlOowOP6X98BmM,493
|
|
12
|
+
narabi/fields/defaults.py,sha256=8XCScjJCvSHQah9roG6yojxIWvfVbtsHuwNFMRafQOQ,1644
|
|
13
|
+
narabi/fields/markers.py,sha256=YG_FcEctn3zR5fFmxwRNiwWdB4-3z4_USuGvlg2FpHM,1733
|
|
14
|
+
narabi/migrations/__init__.py,sha256=kcFFw4yMisY8RUt9EpgxxLDmQXBNi-Wjkx2-iGdTLfU,953
|
|
15
|
+
narabi/migrations/bootstrap.py,sha256=Wv2tJvIqsRF9fzAwQWRYgrluHFsJGfIVnEp9WJxYR00,1290
|
|
16
|
+
narabi/migrations/decorators.py,sha256=OL0o21VkccBrn3Hnfa5Du2k1pvx8ENDeyzaX2fBLHGw,639
|
|
17
|
+
narabi/migrations/diff.py,sha256=TGQQWHcM_3KvMbCWM5aWL7QicTyJXL65oP7bKacBlQM,4201
|
|
18
|
+
narabi/migrations/dsl.py,sha256=Wea1xZQMmpsQZSfv9rHe4nEL__Aak5l8zC_rkK6mNbE,10297
|
|
19
|
+
narabi/migrations/errors.py,sha256=06b8cqkpNPk3Xr2QkGlGkPF-6JqDngJ-7g22-POnxEY,154
|
|
20
|
+
narabi/migrations/executor.py,sha256=e88NySQyDLSjO-N0f88kazeRKPHaFU8UERBvEdVDJtc,12328
|
|
21
|
+
narabi/migrations/generate.py,sha256=dTvt8Y2qimUd_xbBCxozEi0RQSuSIBjSgv1DysrDq88,5118
|
|
22
|
+
narabi/migrations/historical.py,sha256=g3B68pDd3sC21pp9ppAVjOltpoXsbJIN43EmzVRS7Zk,6191
|
|
23
|
+
narabi/migrations/history.py,sha256=SnwzxlIoaOCCrP1g8fsBPMcc5Ll1CPHPnYP2Aa61nxo,5618
|
|
24
|
+
narabi/migrations/models.py,sha256=ygf-o_25SOJjIQgEJacT6tE7N_HVW8fcPCPCsnqEoK0,2867
|
|
25
|
+
narabi/migrations/postgres_executor.py,sha256=MnbDIuRcTVmJ5Rn1trB3J7jTz308d-XBzGMAaB5YzCc,10544
|
|
26
|
+
narabi/migrations/postgresql.py,sha256=7vA5AhpCJvHliHMJl4JScKuZWdyL5JkBfy8mbK8Emko,12268
|
|
27
|
+
narabi/migrations/preview.py,sha256=amyeBjDRgKlzPX_lggaioYiiQBSAhYH3NCuMJM29mIE,6518
|
|
28
|
+
narabi/migrations/replay.py,sha256=P71s-8BHgTZZ33ARJbEYCwnvqao5DhaR3x0tcBeFsN8,1410
|
|
29
|
+
narabi/migrations/reverse.py,sha256=gzcJ0hkQNPi4It2qOviQJq536FWGznk7ROc1PRKuJmk,5859
|
|
30
|
+
narabi/migrations/schema.py,sha256=TcJujNDBjKUyvXPhr_x1GI0ltbd-4NZtzoqc8pnWYLw,6385
|
|
31
|
+
narabi/migrations/snapshot.py,sha256=9DqtiCXCHeW-Ky6PD8HoqcTYmBOcHf_tr-qZ9iE0lH0,2250
|
|
32
|
+
narabi/migrations/sqlite.py,sha256=SOlbtkicjON4aO9s0EFD7D688J8jmhUy7TR3TYyn0uk,5195
|
|
33
|
+
narabi/models/__init__.py,sha256=R4MpohWQ-rZh65waDhdHoExauIo4QcRJO-731uYd-lk,50
|
|
34
|
+
narabi/models/bulk.py,sha256=9e8_AUivZHlQsQ2XEQrPwBgET7P-r4V6rs7f_dY1Okc,5037
|
|
35
|
+
narabi/models/core.py,sha256=u5-Rgh-i5KSTQhLAWNaUrOnQwqOztIik7ui6r15LIj4,17172
|
|
36
|
+
narabi/models/inflection.py,sha256=6P5BUYYaxXe-w5PCTZU5rP8WN45yRhC3o5nkzK2ABdM,1411
|
|
37
|
+
narabi/models/lifecycle.py,sha256=ExD01Luc3yac7UamqpIWP_SIrYq8kxgTjCI2hxbVX0k,4434
|
|
38
|
+
narabi/models/privacy.py,sha256=DfNcWKxOglrPRxz3L6eC7JC_OvwG-1m1Q9yduu_hLNg,559
|
|
39
|
+
narabi/models/serialization.py,sha256=rX48Rzm3LUgjqrNcoY-9JXDuVuHn_2AT_0xAEdSqhYY,5872
|
|
40
|
+
narabi/models/soft_delete.py,sha256=gZ5iL5jH3CKjUPxi9-Ko2G5zpC_4vwlMuknHYCv5JYo,2053
|
|
41
|
+
narabi/models/timestamps.py,sha256=I4RLajYrvEJWwhnVZZOpFEK9s9cM-JLj69aisPgeTPM,1468
|
|
42
|
+
narabi/models/validation.py,sha256=fIduABvMEGX8AgRKRwDoY4D9EygybI5Bulwtffcd_Jw,5176
|
|
43
|
+
narabi/models/values.py,sha256=RoVS2fP5judkKSFboE-3r0zE147cmCrCDp5XNqrKeok,7655
|
|
44
|
+
narabi/query/__init__.py,sha256=Hh8YeviV2AyvIGWTL3H7W5bhgu0HCATZWniBLAs3xvc,222
|
|
45
|
+
narabi/query/expressions.py,sha256=XadMhLiUOG-XmUEb1vnX-zYr5feXJL-ZAMt3AtnJdYE,5261
|
|
46
|
+
narabi/query/relation.py,sha256=x3O9b2torvxlTv2Zzza1A0f-iV7mib_XzSsVqtT5jNk,25453
|
|
47
|
+
narabi/query/scopes.py,sha256=R--41Stx5WLavkYDSLEQEwyDuNgepWHQBYhM6w9tImk,1332
|
|
48
|
+
narabi/relations/__init__.py,sha256=PKHIlr4KmQ4qdVZdkkAI2Zh_42bXg5B83vR24vy66GY,204
|
|
49
|
+
narabi/relations/prefetch.py,sha256=gyyDnbdE6xWYRfbqaB6GdnHJ52TlHNnUdvBVxr0NkFw,2838
|
|
50
|
+
narabi/relations/references.py,sha256=k5r8G67_322bB4Xp-_BeCF_FpzJ5iS1huGLn6Cs0gC0,6917
|
|
51
|
+
narabi/relations/relationships.py,sha256=rjMC-n8FkpLVcX3WfCD0suPz95h5vdVnDsmK7QDaK5w,8015
|
|
52
|
+
narabi_orm-0.1.0.dist-info/METADATA,sha256=xZnctcbD-h4oicFM_hn3rGwiADBE-NodwpM1eNJnJQo,4436
|
|
53
|
+
narabi_orm-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
54
|
+
narabi_orm-0.1.0.dist-info/entry_points.txt,sha256=SHdJ2Ho1lFOZ0Ixga0VVfyAJW1shlmqdI5Dx1p__Ck8,43
|
|
55
|
+
narabi_orm-0.1.0.dist-info/licenses/LICENSE,sha256=5NFj4XTXXfJgqU5jOdQm-eit-3tq5FdBIJckOuZ-3GM,1499
|
|
56
|
+
narabi_orm-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, RickBarretto
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice,
|
|
9
|
+
this list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its contributors
|
|
16
|
+
may be used to endorse or promote products derived from this software
|
|
17
|
+
without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
|
22
|
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
|
|
23
|
+
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
|
24
|
+
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
|
25
|
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
|
26
|
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
|
27
|
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
28
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
29
|
+
POSSIBILITY OF SUCH DAMAGE.
|