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/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""The public API for Narabi records, queries, and migrations."""
|
|
2
|
+
|
|
3
|
+
from .database import Database, use_database
|
|
4
|
+
from .fields import (
|
|
5
|
+
AutoIncrement, Factory, Increment, Indexed, Length, Now, Personal, Primary,
|
|
6
|
+
Private, Range, Ref, Sensitive, UUID4, UUID7, Unique,
|
|
7
|
+
)
|
|
8
|
+
from .migrations import migrate, rollback, seed, transform, verify
|
|
9
|
+
from .models.core import record, table
|
|
10
|
+
from .models.lifecycle import after, before, on
|
|
11
|
+
from .models.validation import FieldError, ValidationError, ValidationResult, convert, normalize, validate
|
|
12
|
+
from .models.values import value
|
|
13
|
+
from .query import Relation, it, scope
|
|
14
|
+
from .relations import StrictLoadingError
|
|
15
|
+
from .relations.relationships import belongs_to, has_many
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"AutoIncrement", "Database", "Factory", "Increment", "Indexed", "Length", "Now",
|
|
19
|
+
"Personal", "Primary", "Private", "Range", "Ref", "Relation", "Sensitive", "UUID4", "UUID7", "Unique",
|
|
20
|
+
"FieldError", "StrictLoadingError", "ValidationError", "ValidationResult", "belongs_to", "convert", "has_many", "it",
|
|
21
|
+
"after", "before", "migrate", "normalize", "on", "record", "rollback", "scope",
|
|
22
|
+
"seed", "table", "transform", "use_database", "validate", "value", "verify",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# Preserve the previous import name for callers that used it directly.
|
|
27
|
+
Query = Relation
|
narabi/__main__.py
ADDED
narabi/cli.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Narabi command-line interface."""
|
|
2
|
+
|
|
3
|
+
from asyncio import run
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
from contextlib import redirect_stdout
|
|
6
|
+
from importlib import import_module
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import tomllib
|
|
11
|
+
|
|
12
|
+
from cyclopts import App
|
|
13
|
+
|
|
14
|
+
from .database import Database, MissingDriverError, use_database
|
|
15
|
+
from .migrations import (
|
|
16
|
+
MigrationError, apply_pending, diff as schema_diff, generate_migration, migration_history,
|
|
17
|
+
preview_sql, replay, rollback_migrations, schema_from_models,
|
|
18
|
+
)
|
|
19
|
+
from .migrations.executor import _DataStep
|
|
20
|
+
from .migrations.history import _load, _sources, pending_plan
|
|
21
|
+
from .models.privacy import classifications
|
|
22
|
+
from .models.values import VALUE_CHECK_PREFIX
|
|
23
|
+
from .project import Project
|
|
24
|
+
from .schema import generate_sql
|
|
25
|
+
from .stubs import generate_stub
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
app = App(name="narabi", help="Manage Narabi models and database migrations.")
|
|
29
|
+
migration = App(name="migration", help="Generate editable Python migrations.")
|
|
30
|
+
privacy = App(name="privacy", help="Inspect field classifications.")
|
|
31
|
+
schema_app = App(name="schema", help="Preview, dump, and load database schemas.")
|
|
32
|
+
app.command(migration)
|
|
33
|
+
app.command(privacy)
|
|
34
|
+
app.command(schema_app)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.command
|
|
38
|
+
def init(*, config: Path | None = None):
|
|
39
|
+
"""Configure Narabi and scaffold a model package."""
|
|
40
|
+
path = config or (Path("narabi.toml") if Path("narabi.toml").exists() else Path("pyproject.toml"))
|
|
41
|
+
content = path.read_text() if path.exists() else ""
|
|
42
|
+
parsed = tomllib.loads(content)
|
|
43
|
+
project_file = path.name == "pyproject.toml"
|
|
44
|
+
configured = "narabi" in parsed.get("tool", {}) if project_file else bool(parsed)
|
|
45
|
+
if not configured:
|
|
46
|
+
package = path.parent / "models"
|
|
47
|
+
if not (path.parent / "models.py").exists():
|
|
48
|
+
package.mkdir(exist_ok=True)
|
|
49
|
+
entry = package / "__init__.py"
|
|
50
|
+
if not entry.exists():
|
|
51
|
+
with entry.open("x") as file:
|
|
52
|
+
file.write(
|
|
53
|
+
"from narabi import Increment, Primary, table\n\n\n"
|
|
54
|
+
"@table(timestamps=True)\n"
|
|
55
|
+
"class Entry:\n"
|
|
56
|
+
" id: Primary[int] = Increment()\n"
|
|
57
|
+
" title: str\n"
|
|
58
|
+
)
|
|
59
|
+
header = "[tool.narabi]\n" if project_file else ""
|
|
60
|
+
database = "[tool.narabi.database]" if project_file else "[database]"
|
|
61
|
+
separator = "\n\n" if content else ""
|
|
62
|
+
with path.open("a", encoding="utf-8") as file:
|
|
63
|
+
file.write(f'{separator}{header}models = ["models"]\n'
|
|
64
|
+
f'table_inflection = true\nmigrations = "migrations"\n\n'
|
|
65
|
+
f'{database}\nbackend = "sqlite"\npath = "narabi.sqlite3"\n')
|
|
66
|
+
Project.load(path).migration_dir.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
print(f"Narabi configuration is ready in {path}.")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@schema_app.default
|
|
71
|
+
def schema(path: Path | None = None, *, dialect: str | None = None, from_models: bool = False):
|
|
72
|
+
"""Print SQL from a TOML schema or from the configured migration files."""
|
|
73
|
+
if path is not None:
|
|
74
|
+
if from_models:
|
|
75
|
+
raise ValueError("Choose a TOML schema or --from-models")
|
|
76
|
+
if dialect is None:
|
|
77
|
+
raise ValueError("Pass --dialect for a TOML schema.")
|
|
78
|
+
with path.open("rb") as file:
|
|
79
|
+
print(generate_sql(tomllib.load(file), dialect))
|
|
80
|
+
return
|
|
81
|
+
project = Project.load()
|
|
82
|
+
declared = _model_schema(project) if from_models else run(_replay(project))
|
|
83
|
+
print(declared.to_sql(dialect or project.backend))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _model_schema(project):
|
|
87
|
+
models = tuple(model for model in project.models() if "_record_key" in vars(model))
|
|
88
|
+
if not models:
|
|
89
|
+
raise ValueError("Configure at least one table model")
|
|
90
|
+
return schema_from_models(*models)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@schema_app.command
|
|
94
|
+
def load_models(*, database_config: Path | None = None, profile: str | None = None):
|
|
95
|
+
"""Create the declared model schema in an empty database."""
|
|
96
|
+
from .migrations.bootstrap import load_schema
|
|
97
|
+
|
|
98
|
+
project = _selected_project(database_config, profile)
|
|
99
|
+
run(load_schema(project.database(), _model_schema(project)))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@schema_app.command(name="dump")
|
|
103
|
+
def dump_schema(path: Path):
|
|
104
|
+
"""Write a versioned snapshot of the configured migrations."""
|
|
105
|
+
from .migrations.snapshot import dump_snapshot
|
|
106
|
+
|
|
107
|
+
run(dump_snapshot(path, Project.load().migrations()))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@schema_app.command(name="load")
|
|
111
|
+
def load_schema(path: Path, *, database_config: Path | None = None, profile: str | None = None):
|
|
112
|
+
"""Initialize an empty database from a versioned snapshot."""
|
|
113
|
+
from .migrations.snapshot import load_snapshot
|
|
114
|
+
|
|
115
|
+
project = _selected_project(database_config, profile)
|
|
116
|
+
run(load_snapshot(project.database(), path, project.migrations()))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.command
|
|
120
|
+
def stubs(module: str):
|
|
121
|
+
"""Print a typing stub for an importable model module."""
|
|
122
|
+
root = str(Path.cwd())
|
|
123
|
+
sys.path.insert(0, root)
|
|
124
|
+
try:
|
|
125
|
+
with redirect_stdout(sys.stderr):
|
|
126
|
+
stub = generate_stub(import_module(module))
|
|
127
|
+
finally:
|
|
128
|
+
sys.path.remove(root)
|
|
129
|
+
print(stub, end="")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
async def _replay(project):
|
|
133
|
+
with _load(_sources(project.migrations())) as modules:
|
|
134
|
+
return await replay(*modules)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _changes(project, rename, allow_drop_add):
|
|
138
|
+
renames = {}
|
|
139
|
+
for value in rename:
|
|
140
|
+
table_column, separator, new = value.partition("=")
|
|
141
|
+
table, dot, old = table_column.partition(".")
|
|
142
|
+
if not (separator and dot and table and old and new) or (table, old) in renames:
|
|
143
|
+
raise ValueError("Use --rename table.old=new once per source column.")
|
|
144
|
+
renames[table, old] = new
|
|
145
|
+
models = tuple(model for model in project.models() if "_record_key" in vars(model))
|
|
146
|
+
if not models:
|
|
147
|
+
raise ValueError("Configure at least one table model in tool.narabi.models.")
|
|
148
|
+
changes = schema_diff(
|
|
149
|
+
run(_replay(project)), schema_from_models(*models),
|
|
150
|
+
renames=renames, allow_drop_add=allow_drop_add,
|
|
151
|
+
)
|
|
152
|
+
# Preserve checks and custom indexes declared only in migrations.
|
|
153
|
+
return tuple(
|
|
154
|
+
change for change in changes
|
|
155
|
+
if (change.kind != "drop_check" or change.before.startswith(VALUE_CHECK_PREFIX)) and (
|
|
156
|
+
change.kind != "drop_index"
|
|
157
|
+
or re.fullmatch(rf"{re.escape(change.table)}_idx_[0-9]+", change.before.name)
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@app.command
|
|
163
|
+
def diff(*, rename: tuple[str, ...] = (), allow_drop_add: bool = False):
|
|
164
|
+
"""Preview changes from migration history to the configured table models."""
|
|
165
|
+
project = Project.load()
|
|
166
|
+
changes = _changes(project, rename, allow_drop_add)
|
|
167
|
+
print(preview_sql(changes, project.backend) if changes else "No schema changes.")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@migration.command
|
|
171
|
+
def create(name: str = "schema", *, rename: tuple[str, ...] = (), allow_drop_add: bool = False):
|
|
172
|
+
"""Generate the next migration file from the model diff."""
|
|
173
|
+
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]*", name):
|
|
174
|
+
raise ValueError("Use letters, digits, hyphens, or underscores in the migration name.")
|
|
175
|
+
project = Project.load()
|
|
176
|
+
paths = tuple(path for path in project.migrations() if path.parent == project.migration_dir)
|
|
177
|
+
changes = _changes(project, rename, allow_drop_add)
|
|
178
|
+
if not changes:
|
|
179
|
+
print("No schema changes.")
|
|
180
|
+
return
|
|
181
|
+
number = max((int(path.stem.partition("_")[0]) for path in paths), default=0) + 1
|
|
182
|
+
path = project.migration_dir / f"{number:06d}_{name}.py"
|
|
183
|
+
if paths and path.name <= paths[-1].name:
|
|
184
|
+
raise ValueError("Migration filenames must sort in apply order. Review existing filenames.")
|
|
185
|
+
project.migration_dir.mkdir(parents=True, exist_ok=True)
|
|
186
|
+
source = generate_migration(changes)
|
|
187
|
+
with path.open("x", encoding="utf-8") as file:
|
|
188
|
+
file.write(source)
|
|
189
|
+
print(path)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _selected_project(database_config, profile):
|
|
193
|
+
project = Project.load(database_config)
|
|
194
|
+
return replace(project, profile=profile)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _read_database(project):
|
|
198
|
+
db = project.database()
|
|
199
|
+
if db.backend == "sqlite" and not db.database.exists():
|
|
200
|
+
return Database("sqlite", ":memory:")
|
|
201
|
+
return db
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@app.command
|
|
205
|
+
def migrate(*, dry_run: bool = False, allow_destructive: bool = False, database_config: Path | None = None, profile: str | None = None):
|
|
206
|
+
"""Apply pending migrations or preview their structural and data steps."""
|
|
207
|
+
project = _selected_project(database_config, profile)
|
|
208
|
+
paths = project.migrations()
|
|
209
|
+
if dry_run:
|
|
210
|
+
applied, actions, drift = run(pending_plan(_read_database(project), *paths))
|
|
211
|
+
for path in paths[len(applied):]:
|
|
212
|
+
print(f"Pending: {path.stem}")
|
|
213
|
+
for action in actions:
|
|
214
|
+
if isinstance(action, _DataStep):
|
|
215
|
+
print(f" @{action.kind}: {action.function.__name__}")
|
|
216
|
+
else:
|
|
217
|
+
verb = "create" if action.before is None else "drop" if action.after is None else "alter"
|
|
218
|
+
warning = " (destructive; requires --allow-destructive)" if action.destructive else ""
|
|
219
|
+
print(f" {verb} {action.name}{warning}")
|
|
220
|
+
if not paths[len(applied):]:
|
|
221
|
+
print("No pending migrations.")
|
|
222
|
+
if drift:
|
|
223
|
+
raise MigrationError("Live schema differs from applied migration history.")
|
|
224
|
+
return
|
|
225
|
+
run(apply_pending(project.database(), *paths, allow_destructive=allow_destructive))
|
|
226
|
+
print("Migration history is up to date.")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@app.command
|
|
230
|
+
def rollback(*, steps: int = 1, allow_destructive: bool = False, database_config: Path | None = None, profile: str | None = None):
|
|
231
|
+
"""Roll back the most recently applied migrations."""
|
|
232
|
+
project = _selected_project(database_config, profile)
|
|
233
|
+
run(rollback_migrations(
|
|
234
|
+
_read_database(project), *project.migrations(), steps=steps,
|
|
235
|
+
allow_destructive=allow_destructive,
|
|
236
|
+
))
|
|
237
|
+
print("Rollback complete.")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@app.command
|
|
241
|
+
def history(*, database_config: Path | None = None, profile: str | None = None):
|
|
242
|
+
"""List recorded migrations in apply order."""
|
|
243
|
+
project = _selected_project(database_config, profile)
|
|
244
|
+
applied = run(migration_history(_read_database(project)))
|
|
245
|
+
for entry in applied:
|
|
246
|
+
print(entry.position, entry.name, entry.applied_at.isoformat(), entry.checksum)
|
|
247
|
+
if not applied:
|
|
248
|
+
print("No applied migrations.")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@app.command
|
|
252
|
+
def status(*, database_config: Path | None = None, profile: str | None = None):
|
|
253
|
+
"""Check migration checksums, pending files, and live schema drift."""
|
|
254
|
+
project = _selected_project(database_config, profile)
|
|
255
|
+
paths = project.migrations()
|
|
256
|
+
applied, _, drift = run(pending_plan(_read_database(project), *paths))
|
|
257
|
+
for entry in applied:
|
|
258
|
+
print(f"Applied: {entry.name}")
|
|
259
|
+
for path in paths[len(applied):]:
|
|
260
|
+
print(f"Pending: {path.stem}")
|
|
261
|
+
if drift:
|
|
262
|
+
for change in drift:
|
|
263
|
+
print(f"Drift: {change.kind} on {change.table}")
|
|
264
|
+
raise MigrationError("Live schema differs from applied migration history.")
|
|
265
|
+
print("Live schema matches applied migration history.")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
@app.command
|
|
269
|
+
def seed(*, database_config: Path | None = None, profile: str | None = None):
|
|
270
|
+
"""Run the configured async project seeder in a transaction."""
|
|
271
|
+
project = _selected_project(database_config, profile)
|
|
272
|
+
module, separator, name = project.settings.get("seed", "").partition(":")
|
|
273
|
+
if not (module and separator and name):
|
|
274
|
+
raise ValueError('Configure tool.narabi.seed as "module:function".')
|
|
275
|
+
sys.path.insert(0, str(project.root))
|
|
276
|
+
try:
|
|
277
|
+
function = getattr(import_module(module), name)
|
|
278
|
+
db = project.database()
|
|
279
|
+
|
|
280
|
+
async def execute():
|
|
281
|
+
async with db.transaction():
|
|
282
|
+
await function(db)
|
|
283
|
+
|
|
284
|
+
run(execute())
|
|
285
|
+
finally:
|
|
286
|
+
sys.path.remove(str(project.root))
|
|
287
|
+
print("Seeding complete.")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
@app.command
|
|
291
|
+
def doctor(*, database_config: Path | None = None, profile: str | None = None):
|
|
292
|
+
"""Check configuration, model discovery and database connectivity."""
|
|
293
|
+
try:
|
|
294
|
+
project = _selected_project(database_config, profile)
|
|
295
|
+
db = project.database()
|
|
296
|
+
models = project.models()
|
|
297
|
+
run(_read_database(project).execute("SELECT 1"))
|
|
298
|
+
except MissingDriverError:
|
|
299
|
+
raise
|
|
300
|
+
except Exception as error:
|
|
301
|
+
print(f"Diagnostic failed ({type(error).__name__}). Configuration values and SQL parameters are redacted.",
|
|
302
|
+
file=sys.stderr)
|
|
303
|
+
raise SystemExit(1) from None
|
|
304
|
+
print(f"Database backend: {db.backend}")
|
|
305
|
+
if db.backend == "sqlite" and not db.database.exists():
|
|
306
|
+
print("SQLite database has not been created. In-memory connection check passed.")
|
|
307
|
+
else:
|
|
308
|
+
print("Database connection check passed.")
|
|
309
|
+
print(f"Discovered models: {len(models)}")
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@privacy.command
|
|
313
|
+
def inventory():
|
|
314
|
+
"""List classified model fields without reading their values."""
|
|
315
|
+
for model in Project.load().models():
|
|
316
|
+
for name, field in model._record_metadata.items():
|
|
317
|
+
labels = classifications(field)
|
|
318
|
+
if labels:
|
|
319
|
+
print(f"{model.__module__}.{model.__qualname__}.{name}: {', '.join(labels)}")
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@app.command
|
|
323
|
+
def console(*, database_config: Path | None = None, profile: str | None = None, sandbox: bool = False):
|
|
324
|
+
"""Open a Python console with models, db and top-level await."""
|
|
325
|
+
from .console import interact
|
|
326
|
+
|
|
327
|
+
project = _selected_project(database_config, profile)
|
|
328
|
+
db = project.database()
|
|
329
|
+
use_database(db)
|
|
330
|
+
interact(project, db, sandbox=sandbox)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def main():
|
|
334
|
+
try:
|
|
335
|
+
app()
|
|
336
|
+
except (MigrationError, MissingDriverError, ValueError, OSError, ImportError, KeyError) as error:
|
|
337
|
+
print(f"Error: {error}", file=sys.stderr)
|
|
338
|
+
raise SystemExit(1) from None
|
narabi/console.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Optional IPython console and task-owned rollback sandbox."""
|
|
2
|
+
|
|
3
|
+
from asyncio import CancelledError, Queue, Runner, create_task, current_task, get_running_loop, shield
|
|
4
|
+
from contextlib import nullcontext
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class _RollbackSandbox(Exception):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _Sandbox:
|
|
14
|
+
def __init__(self, runner, database):
|
|
15
|
+
self.runner = runner
|
|
16
|
+
self.database = database
|
|
17
|
+
|
|
18
|
+
async def _start(self):
|
|
19
|
+
self.commands = Queue()
|
|
20
|
+
ready = get_running_loop().create_future()
|
|
21
|
+
self.task = create_task(self._serve(ready))
|
|
22
|
+
try:
|
|
23
|
+
await ready
|
|
24
|
+
except BaseException:
|
|
25
|
+
await self.task
|
|
26
|
+
raise
|
|
27
|
+
|
|
28
|
+
async def _serve(self, ready):
|
|
29
|
+
self.database._sandbox_owner = current_task()
|
|
30
|
+
try:
|
|
31
|
+
async with self.database.transaction():
|
|
32
|
+
ready.set_result(None)
|
|
33
|
+
while True:
|
|
34
|
+
coroutine, response = await self.commands.get()
|
|
35
|
+
try:
|
|
36
|
+
async with self.database.transaction():
|
|
37
|
+
result = await coroutine
|
|
38
|
+
if getattr(result, "success", True) is False:
|
|
39
|
+
raise _RollbackSandbox
|
|
40
|
+
except _RollbackSandbox:
|
|
41
|
+
response.set_result(result)
|
|
42
|
+
except Exception as error:
|
|
43
|
+
response.set_exception(error)
|
|
44
|
+
else:
|
|
45
|
+
response.set_result(result)
|
|
46
|
+
except BaseException as error:
|
|
47
|
+
if not ready.done():
|
|
48
|
+
ready.set_exception(error)
|
|
49
|
+
raise
|
|
50
|
+
finally:
|
|
51
|
+
self.database._sandbox_owner = None
|
|
52
|
+
|
|
53
|
+
def __enter__(self):
|
|
54
|
+
self.runner.run(self._start())
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
async def _stop(self):
|
|
58
|
+
self.task.cancel()
|
|
59
|
+
try:
|
|
60
|
+
await self.task
|
|
61
|
+
except CancelledError:
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
def __exit__(self, *_):
|
|
65
|
+
self.runner.run(self._stop())
|
|
66
|
+
|
|
67
|
+
async def _submit(self, coroutine):
|
|
68
|
+
response = get_running_loop().create_future()
|
|
69
|
+
self.commands.put_nowait((coroutine, response))
|
|
70
|
+
return await shield(response)
|
|
71
|
+
|
|
72
|
+
def __call__(self, coroutine):
|
|
73
|
+
return self.runner.run(self._submit(coroutine))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def interact(project, database, *, sandbox=False):
|
|
77
|
+
try:
|
|
78
|
+
from IPython.terminal.embed import InteractiveShellEmbed
|
|
79
|
+
except ModuleNotFoundError as error:
|
|
80
|
+
if error.name != "IPython":
|
|
81
|
+
raise
|
|
82
|
+
raise ImportError("Install narabi-orm[console] to use the console") from error
|
|
83
|
+
|
|
84
|
+
discovered = project.models()
|
|
85
|
+
namespace = {
|
|
86
|
+
**{model.__name__: model for model in discovered},
|
|
87
|
+
"db": database,
|
|
88
|
+
"models": lambda: discovered,
|
|
89
|
+
}
|
|
90
|
+
label = Path(database.database).name if database.backend == "sqlite" else "configured PostgreSQL database"
|
|
91
|
+
header = f"Narabi console | {project.root} | {database.backend} | {label}"
|
|
92
|
+
if sandbox:
|
|
93
|
+
header += " | sandbox"
|
|
94
|
+
with Runner() as runner:
|
|
95
|
+
scope = _Sandbox(runner, database) if sandbox else nullcontext(runner.run)
|
|
96
|
+
with scope as run_cell:
|
|
97
|
+
shell = InteractiveShellEmbed(
|
|
98
|
+
banner1="", exit_msg="", confirm_exit=False,
|
|
99
|
+
simple_prompt=not sys.stdin.isatty(),
|
|
100
|
+
)
|
|
101
|
+
shell.loop_runner = run_cell
|
|
102
|
+
shell(header=header, local_ns=namespace)
|