xtr-orm-fixtures 7.2.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.
- xtr_orm_fixtures/.agents/skills/xtr-orm-fixtures/SKILL.md +168 -0
- xtr_orm_fixtures/__init__.py +25 -0
- xtr_orm_fixtures/bundle/__init__.py +7 -0
- xtr_orm_fixtures/bundle/orm_fixtures_bundle.py +107 -0
- xtr_orm_fixtures/command/__init__.py +7 -0
- xtr_orm_fixtures/command/load_data_fixtures_command.py +176 -0
- xtr_orm_fixtures/dependent_fixture_interface.py +24 -0
- xtr_orm_fixtures/exception/__init__.py +19 -0
- xtr_orm_fixtures/exception/circular_reference_error.py +24 -0
- xtr_orm_fixtures/exception/invalid_argument_error.py +29 -0
- xtr_orm_fixtures/exception/missing_fixture_error.py +30 -0
- xtr_orm_fixtures/exception/orm_fixtures_error.py +14 -0
- xtr_orm_fixtures/exception/reference_exists_error.py +30 -0
- xtr_orm_fixtures/exception/reference_not_found_error.py +27 -0
- xtr_orm_fixtures/executor/__init__.py +9 -0
- xtr_orm_fixtures/executor/abstract_executor.py +86 -0
- xtr_orm_fixtures/executor/dry_run_orm_executor.py +40 -0
- xtr_orm_fixtures/executor/orm_executor.py +36 -0
- xtr_orm_fixtures/fixture.py +83 -0
- xtr_orm_fixtures/fixture_group_interface.py +25 -0
- xtr_orm_fixtures/fixture_interface.py +24 -0
- xtr_orm_fixtures/loader.py +183 -0
- xtr_orm_fixtures/ordered_fixture_interface.py +22 -0
- xtr_orm_fixtures/purger/__init__.py +17 -0
- xtr_orm_fixtures/purger/orm_purger.py +93 -0
- xtr_orm_fixtures/purger/orm_purger_factory.py +42 -0
- xtr_orm_fixtures/purger/purge_mode.py +20 -0
- xtr_orm_fixtures/purger/purger_factory_interface.py +42 -0
- xtr_orm_fixtures/purger/purger_interface.py +24 -0
- xtr_orm_fixtures/py.typed +0 -0
- xtr_orm_fixtures/recipe/__init__.py +14 -0
- xtr_orm_fixtures/recipe/manifest.toml +26 -0
- xtr_orm_fixtures/reference_repository.py +84 -0
- xtr_orm_fixtures/shared_fixture_interface.py +25 -0
- xtr_orm_fixtures/table_definitions.py +47 -0
- xtr_orm_fixtures-7.2.0.dist-info/METADATA +389 -0
- xtr_orm_fixtures-7.2.0.dist-info/RECORD +40 -0
- xtr_orm_fixtures-7.2.0.dist-info/WHEEL +4 -0
- xtr_orm_fixtures-7.2.0.dist-info/entry_points.txt +6 -0
- xtr_orm_fixtures-7.2.0.dist-info/licenses/LICENSE +23 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: xtr-orm-fixtures
|
|
3
|
+
description: Seed development and test databases from fixture classes with xtr-orm-fixtures - a Fixture with async load(session), references shared by name, dependencies, numeric order and groups, an emptying in foreign-key order by DELETE or TRUNCATE, one transaction or a dry run, and the orm:fixtures:load command. Use when writing or ordering fixtures, sharing objects between them, loading JSON or CSV rows in a fixture, choosing what a run empties or keeps, writing a purger factory, loading fixtures without a container, reading MissingFixtureError, CircularReferenceError, ReferenceNotFoundError or SetAsideModuleUsedError, keeping a production install without development dependencies booting, or adding OrmFixturesBundle to an application on xtr-dependency-injection.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# xtr-orm-fixtures
|
|
7
|
+
|
|
8
|
+
A development-only package: fixture classes seed a database through xtr-orm's connections, in
|
|
9
|
+
one transaction after an emptying of the tables the application maps.
|
|
10
|
+
|
|
11
|
+
## Quick reference
|
|
12
|
+
|
|
13
|
+
| Need | Use |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| A fixture | `class X(Fixture)` with `async def load(self, session)` |
|
|
16
|
+
| Share an object | `self.add_reference("admin", user)`; later `self.get_reference("admin", User)` |
|
|
17
|
+
| Load after others | `DependentFixtureInterface.get_dependencies() -> (UserFixtures,)` |
|
|
18
|
+
| Load first, by number | `OrderedFixtureInterface.get_order() -> 1` (not with dependencies) |
|
|
19
|
+
| Load a subset | `FixtureGroupInterface.get_groups()` (classmethod); `--group demo` |
|
|
20
|
+
| Run them | `uv run app orm:fixtures:load` (`-n`, `--append`, `--dry-run`, `--group`, `--connection`, `--purger`, `--purge-exclusions`, `--purge-with-truncate`) |
|
|
21
|
+
| Without a container | `Loader().load_from_package("app.fixtures")`, then `OrmExecutor(session, OrmPurger(metadata)).execute(loader.get_fixtures())` |
|
|
22
|
+
|
|
23
|
+
- Imports: `Fixture`, the interfaces, `Loader`, `ReferenceRepository`, `TableDefinitions` from
|
|
24
|
+
`xtr_orm_fixtures`; `OrmExecutor`, `DryRunOrmExecutor` from `xtr_orm_fixtures.executor`;
|
|
25
|
+
`OrmPurger`, `OrmPurgerFactory`, `PurgeMode`, `PurgerFactoryInterface` from
|
|
26
|
+
`xtr_orm_fixtures.purger`; `OrmFixturesBundle` from `xtr_orm_fixtures.bundle`.
|
|
27
|
+
- Fixtures live anywhere in the application; the bundle finds every concrete class with
|
|
28
|
+
`FixtureInterface` among its bases. An abstract base is not registered.
|
|
29
|
+
|
|
30
|
+
## A fixture with references
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from collections.abc import Sequence
|
|
34
|
+
|
|
35
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
36
|
+
from xtr_orm_fixtures import DependentFixtureInterface, Fixture, FixtureInterface
|
|
37
|
+
|
|
38
|
+
from app.models import Order, User
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class UserFixtures(Fixture):
|
|
42
|
+
async def load(self, session: AsyncSession) -> None:
|
|
43
|
+
admin = User(email="admin@example.com")
|
|
44
|
+
session.add(admin)
|
|
45
|
+
self.add_reference("admin", admin)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OrderFixtures(Fixture, DependentFixtureInterface):
|
|
49
|
+
def get_dependencies(self) -> Sequence[type[FixtureInterface]]:
|
|
50
|
+
return (UserFixtures,)
|
|
51
|
+
|
|
52
|
+
async def load(self, session: AsyncSession) -> None:
|
|
53
|
+
session.add(Order(customer=self.get_reference("admin", User)))
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The executor flushes after each fixture and commits once at the end: never commit in `load`.
|
|
57
|
+
Names are kept per class (a mapped object under its mapped class). `add_reference` refuses a
|
|
58
|
+
taken name; `set_reference` replaces it.
|
|
59
|
+
|
|
60
|
+
## A fixture with services
|
|
61
|
+
|
|
62
|
+
With the bundle, the container builds each fixture once per run, so its constructor takes
|
|
63
|
+
services — `AsyncSession` included, the same session `load` is handed:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
class CatalogFixtures(Fixture):
|
|
67
|
+
def __init__(self, pricing: PricingService) -> None:
|
|
68
|
+
self._pricing = pricing
|
|
69
|
+
|
|
70
|
+
async def load(self, session: AsyncSession) -> None:
|
|
71
|
+
session.add(Book(title="Dune", price=self._pricing.list_price("dune")))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Rows from a file
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from pathlib import Path
|
|
78
|
+
|
|
79
|
+
from advanced_alchemy.repository import SQLAlchemyAsyncRepository
|
|
80
|
+
from advanced_alchemy.utils.fixtures import open_fixture_async
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class CountryRepository(SQLAlchemyAsyncRepository[Country]):
|
|
84
|
+
model_type = Country
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class CountryFixtures(Fixture):
|
|
88
|
+
async def load(self, session: AsyncSession) -> None:
|
|
89
|
+
rows = await open_fixture_async(Path(__file__).parent / "data", "countries")
|
|
90
|
+
await CountryRepository(session=session).add_many([Country(**row) for row in rows])
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## What a run empties
|
|
94
|
+
|
|
95
|
+
- Each connection's table definitions — `ConnectionConfig.table_definitions()`, what its
|
|
96
|
+
migrations compare with — children before parents. Nothing else in the database.
|
|
97
|
+
- `--purge-exclusions countries` keeps a table; `--purge-with-truncate` uses `TRUNCATE`
|
|
98
|
+
(PostgreSQL: one statement, no `CASCADE`; MySQL: checks off, each table, commits; SQLite:
|
|
99
|
+
`DELETE`).
|
|
100
|
+
- A purger of your own, picked with `--purger keep_countries`:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from xtr_dependency_injection import as_alias, when
|
|
104
|
+
from xtr_orm_fixtures.purger import OrmPurger, PurgerFactoryInterface
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@when("dev", "test")
|
|
108
|
+
@as_alias(PurgerFactoryInterface, qualifier="keep_countries")
|
|
109
|
+
class KeepCountriesPurgerFactory(PurgerFactoryInterface):
|
|
110
|
+
def create_for_connection(
|
|
111
|
+
self, connection, metadata, *, excluded=(), purge_with_truncate=False
|
|
112
|
+
):
|
|
113
|
+
return OrmPurger(metadata, (*excluded, "countries"))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Testing
|
|
117
|
+
|
|
118
|
+
- Load fixtures into a test database with the executor directly: `Loader`,
|
|
119
|
+
`OrmExecutor(session, OrmPurger(Base.metadata))`, `execute(loader.get_fixtures())`.
|
|
120
|
+
- `DryRunOrmExecutor` runs everything and rolls it back: a constraint a fixture breaks still
|
|
121
|
+
fails it.
|
|
122
|
+
- Inside a transaction a test opened, the executor takes a savepoint and leaves the
|
|
123
|
+
transaction to the test.
|
|
124
|
+
- A fixture is a plain class: build it, hand it a `ReferenceRepository` with
|
|
125
|
+
`set_reference_repository`, and `await fixture.load(session)`.
|
|
126
|
+
|
|
127
|
+
## Use in an application
|
|
128
|
+
|
|
129
|
+
1. **Install** — `uv run xtr-recipes recipes:add --dev xtr-orm-fixtures` (or
|
|
130
|
+
`uv add --dev xtr-orm-fixtures`, then `uv run xtr-recipes recipes:sync`). The database driver
|
|
131
|
+
is xtr-orm's extra.
|
|
132
|
+
2. **Recipe** — lists the bundle for `dev` and `test`, and nothing else.
|
|
133
|
+
3. **Activate** — `from xtr_orm_fixtures.bundle import OrmFixturesBundle` in
|
|
134
|
+
`<app>/config/bundles.py`, and `OrmFixturesBundle: {"dev": True, "test": True}` in `BUNDLES`.
|
|
135
|
+
To seed production too, install it as a runtime dependency and list it `{"all": True}`.
|
|
136
|
+
4. **Brings along** — the orm bundle; `orm:fixtures:load` when the console bundle is active.
|
|
137
|
+
5. **Configure** — nothing.
|
|
138
|
+
6. **Environment** — nothing.
|
|
139
|
+
7. **Ignore** — nothing: fixtures are code to commit.
|
|
140
|
+
8. **Remove** — `uv run xtr-recipes recipes:remove xtr-orm-fixtures`, then delete the fixtures.
|
|
141
|
+
9. **Check** — `debug:bundles` lists `orm_fixtures` active in `dev`; in production without the
|
|
142
|
+
dev dependencies, it is not active and the fixture modules are listed under **Set aside**.
|
|
143
|
+
|
|
144
|
+
## Errors
|
|
145
|
+
|
|
146
|
+
Every one derives from `OrmFixturesError`, in `xtr_orm_fixtures.exception`:
|
|
147
|
+
|
|
148
|
+
| Error | Raised when |
|
|
149
|
+
| --- | --- |
|
|
150
|
+
| `InvalidArgumentError` | A fixture is numbered and dependent, depends on nothing or itself; a reference is asked for before a run; an unknown connection |
|
|
151
|
+
| `MissingFixtureError` | A dependency was not added (`fixture`, `required_by`) |
|
|
152
|
+
| `CircularReferenceError` | Fixtures depend on one another in a circle (`fixtures`) |
|
|
153
|
+
| `ReferenceNotFoundError` | `get_reference` of a name not kept for that class |
|
|
154
|
+
| `ReferenceExistsError` | `add_reference` of a taken name; use `set_reference` |
|
|
155
|
+
|
|
156
|
+
In production, a fixture module set aside while the fixtures bundle runs fails the build with
|
|
157
|
+
the container's `SetAsideModuleUsedError`, naming the fixture and the missing package.
|
|
158
|
+
|
|
159
|
+
## Do not
|
|
160
|
+
|
|
161
|
+
- Do not import a fixture, or anything only fixtures use, from production code: that module is
|
|
162
|
+
set aside where the package is not installed.
|
|
163
|
+
- Do not make it a runtime dependency without listing the bundle where it is needed, and the
|
|
164
|
+
libraries the fixtures import as runtime dependencies too.
|
|
165
|
+
- Do not declare a service (`@as_alias`, `@as_service`) in a fixture module without
|
|
166
|
+
`@when("dev", "test")`: a production build without the package refuses it.
|
|
167
|
+
- Do not commit or roll back inside `load`; the run does it once.
|
|
168
|
+
- Do not depend on `--purge-with-truncate` rolling back on MySQL: `TRUNCATE` commits there.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Seed a database from fixture classes, ordered, grouped and sharing references."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .dependent_fixture_interface import DependentFixtureInterface
|
|
6
|
+
from .fixture import Fixture
|
|
7
|
+
from .fixture_group_interface import FixtureGroupInterface
|
|
8
|
+
from .fixture_interface import FixtureInterface
|
|
9
|
+
from .loader import Loader
|
|
10
|
+
from .ordered_fixture_interface import OrderedFixtureInterface
|
|
11
|
+
from .reference_repository import ReferenceRepository
|
|
12
|
+
from .shared_fixture_interface import SharedFixtureInterface
|
|
13
|
+
from .table_definitions import TableDefinitions
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DependentFixtureInterface",
|
|
17
|
+
"Fixture",
|
|
18
|
+
"FixtureGroupInterface",
|
|
19
|
+
"FixtureInterface",
|
|
20
|
+
"Loader",
|
|
21
|
+
"OrderedFixtureInterface",
|
|
22
|
+
"ReferenceRepository",
|
|
23
|
+
"SharedFixtureInterface",
|
|
24
|
+
"TableDefinitions",
|
|
25
|
+
]
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""The xtr-orm-fixtures bundle: the application's fixtures, wherever they are, and their command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from collections.abc import Callable, Iterable
|
|
7
|
+
from typing import Final, final, override
|
|
8
|
+
|
|
9
|
+
from xtr_dependency_injection import (
|
|
10
|
+
Bundle,
|
|
11
|
+
ContainerBuilder,
|
|
12
|
+
ServiceConfigurator,
|
|
13
|
+
as_bundle,
|
|
14
|
+
bundle_active,
|
|
15
|
+
named_factory,
|
|
16
|
+
qualified_name,
|
|
17
|
+
required_bundle,
|
|
18
|
+
)
|
|
19
|
+
from xtr_orm.bundle import OrmConfig
|
|
20
|
+
|
|
21
|
+
from xtr_orm_fixtures.fixture_interface import FixtureInterface
|
|
22
|
+
from xtr_orm_fixtures.purger import OrmPurgerFactory, PurgerFactoryInterface
|
|
23
|
+
from xtr_orm_fixtures.table_definitions import TableDefinitions
|
|
24
|
+
|
|
25
|
+
__all__ = ["DEFAULT_PURGER", "FIXTURE_TAG", "OrmFixturesBundle"]
|
|
26
|
+
|
|
27
|
+
FIXTURE_TAG: Final = "orm_fixtures.fixture"
|
|
28
|
+
"""The tag every fixture the application defines carries."""
|
|
29
|
+
|
|
30
|
+
DEFAULT_PURGER: Final = "default"
|
|
31
|
+
"""The name the purger factory built in is known by, and the one a run uses unless told."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@final
|
|
35
|
+
@required_bundle("xtr_orm.bundle:OrmBundle")
|
|
36
|
+
@required_bundle("xtr_console.bundle:ConsoleBundle", ignore_on_invalid=True)
|
|
37
|
+
@as_bundle("orm_fixtures")
|
|
38
|
+
class OrmFixturesBundle(Bundle):
|
|
39
|
+
"""Registers every fixture class the application defines, and ``orm:fixtures:load``.
|
|
40
|
+
|
|
41
|
+
Nothing is configured and nothing is scanned of the bundle's own: the
|
|
42
|
+
application's scan finds the fixtures wherever the application keeps
|
|
43
|
+
them, and each is built by the container, once per run, so it can take
|
|
44
|
+
the services it needs in its constructor.
|
|
45
|
+
|
|
46
|
+
A purger factory of the application's joins the built-in one under the
|
|
47
|
+
name it is given: ``@as_alias(PurgerFactoryInterface, qualifier="mine")``.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
@override
|
|
51
|
+
def build(self, builder: ContainerBuilder) -> None:
|
|
52
|
+
"""Register each fixture class the scan finds."""
|
|
53
|
+
builder.register_attribute_for_autoconfiguration(_fixtures_in, _register_fixture)
|
|
54
|
+
|
|
55
|
+
@override
|
|
56
|
+
def load_extension(
|
|
57
|
+
self,
|
|
58
|
+
config: object,
|
|
59
|
+
services: ServiceConfigurator,
|
|
60
|
+
builder: ContainerBuilder,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Register the connections' table definitions, the built-in purger, the command."""
|
|
63
|
+
del config
|
|
64
|
+
orm = builder.get_extension_config(OrmConfig)
|
|
65
|
+
_ = services.set(named_factory(_table_definitions_factory(orm), "orm_fixtures_tables"))
|
|
66
|
+
_ = services.set(OrmPurgerFactory)
|
|
67
|
+
services.alias(PurgerFactoryInterface, OrmPurgerFactory, alias_qualifier=DEFAULT_PURGER)
|
|
68
|
+
if bundle_active(builder, "console"):
|
|
69
|
+
services.load("xtr_orm_fixtures.command")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _fixtures_in(obj: object) -> Iterable[type]:
|
|
73
|
+
"""Yield ``obj`` when it is a fixture class that can be built.
|
|
74
|
+
|
|
75
|
+
Read by inheritance, not by shape: a class is a fixture because it says
|
|
76
|
+
so, never because it happens to have a ``load`` method. An abstract base,
|
|
77
|
+
or an interface of the application's own, only lends to the fixtures
|
|
78
|
+
built on it.
|
|
79
|
+
"""
|
|
80
|
+
if not isinstance(obj, type) or FixtureInterface not in obj.__mro__:
|
|
81
|
+
return ()
|
|
82
|
+
if inspect.isabstract(obj) or vars(obj).get("_is_protocol", False):
|
|
83
|
+
return ()
|
|
84
|
+
return (obj,)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _register_fixture(obj: object, fixture: type, services: ServiceConfigurator) -> None:
|
|
88
|
+
"""Register ``fixture``, built once per run, among the fixtures by its qualified name."""
|
|
89
|
+
del obj
|
|
90
|
+
_ = services.set(fixture, lifetime="scoped").add_tag(FIXTURE_TAG)
|
|
91
|
+
services.alias(FixtureInterface, fixture, alias_qualifier=qualified_name(fixture))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _table_definitions_factory(orm: OrmConfig) -> Callable[[], TableDefinitions]:
|
|
95
|
+
"""Build the factory of the table definitions of every connection ``orm`` configures.
|
|
96
|
+
|
|
97
|
+
Each connection's are the ones its migrations compare the database with,
|
|
98
|
+
so the run empties exactly the tables the application maps. They are read
|
|
99
|
+
when the command first needs them, once every model is mapped.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def table_definitions() -> TableDefinitions:
|
|
103
|
+
return TableDefinitions(
|
|
104
|
+
{name: connection.table_definitions() for name, connection in orm.connections.items()}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
return table_definitions
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""``orm:fixtures:load``: empty a database and load the application's fixtures into it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import final, override
|
|
6
|
+
|
|
7
|
+
from xtr_console import ConsoleStyle, ExitCode, as_command, escape
|
|
8
|
+
from xtr_dependency_injection import Injected, ServiceLocator
|
|
9
|
+
from xtr_logging_contracts import AbstractLogger, Context, LevelLike
|
|
10
|
+
from xtr_orm import ConnectionRegistry
|
|
11
|
+
from xtr_orm.exception import SessionUnavailableError, UnknownConnectionError
|
|
12
|
+
|
|
13
|
+
from xtr_orm_fixtures.exception import OrmFixturesError
|
|
14
|
+
from xtr_orm_fixtures.executor import AbstractExecutor, DryRunOrmExecutor, OrmExecutor
|
|
15
|
+
from xtr_orm_fixtures.fixture_interface import FixtureInterface
|
|
16
|
+
from xtr_orm_fixtures.loader import Loader
|
|
17
|
+
from xtr_orm_fixtures.purger import PurgerFactoryInterface, PurgerInterface
|
|
18
|
+
from xtr_orm_fixtures.table_definitions import TableDefinitions
|
|
19
|
+
|
|
20
|
+
__all__ = ["LoadDataFixturesCommand"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@as_command("orm:fixtures:load", description="Load data fixtures into the database.")
|
|
24
|
+
@final
|
|
25
|
+
class LoadDataFixturesCommand:
|
|
26
|
+
"""Empties a connection's database, then loads every fixture of the application into it."""
|
|
27
|
+
|
|
28
|
+
__slots__ = ("_connections", "_purger_factories", "_tables")
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
connections: ConnectionRegistry,
|
|
33
|
+
tables: TableDefinitions,
|
|
34
|
+
purger_factories: ServiceLocator[PurgerFactoryInterface],
|
|
35
|
+
) -> None:
|
|
36
|
+
"""Load through ``connections``, emptying the tables ``tables`` names.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
connections: The connections fixtures may load into.
|
|
40
|
+
tables: The table definitions of each connection: what is emptied.
|
|
41
|
+
purger_factories: What builds the purger, by the name ``--purger`` gives.
|
|
42
|
+
"""
|
|
43
|
+
self._connections = connections
|
|
44
|
+
self._tables = tables
|
|
45
|
+
self._purger_factories = purger_factories
|
|
46
|
+
|
|
47
|
+
async def __call__( # noqa: PLR0911 — one early exit per way a run is refused
|
|
48
|
+
self,
|
|
49
|
+
io: ConsoleStyle,
|
|
50
|
+
fixtures: Injected[ServiceLocator[FixtureInterface]],
|
|
51
|
+
*,
|
|
52
|
+
append: bool = False,
|
|
53
|
+
dry_run: bool = False,
|
|
54
|
+
group: list[str] | None = None,
|
|
55
|
+
connection: str | None = None,
|
|
56
|
+
purger: str = "default",
|
|
57
|
+
purge_exclusions: list[str] | None = None,
|
|
58
|
+
purge_with_truncate: bool = False,
|
|
59
|
+
) -> int:
|
|
60
|
+
"""Load data fixtures into the database.
|
|
61
|
+
|
|
62
|
+
Every table the connection maps is emptied first, a referencing table
|
|
63
|
+
before the one it references, after you confirm; then every fixture
|
|
64
|
+
loads, all in one transaction. Fixtures are found wherever the
|
|
65
|
+
application keeps them.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
io: Where the command reads and writes.
|
|
69
|
+
fixtures: Every fixture of the application, by name.
|
|
70
|
+
append: Add to what the database holds instead of emptying it
|
|
71
|
+
first; nothing is asked. Example: --append.
|
|
72
|
+
dry_run: Run everything, the emptying included, then roll it all
|
|
73
|
+
back; nothing is asked. Example: --dry-run.
|
|
74
|
+
group: Load only the fixtures of this group, and those they
|
|
75
|
+
depend on; repeat for several. A fixture is also in the group
|
|
76
|
+
named after its class. Example: --group demo.
|
|
77
|
+
connection: The connection to load into; the default one when
|
|
78
|
+
left out. Example: --connection audit.
|
|
79
|
+
purger: The purger factory to empty the database with, by name.
|
|
80
|
+
Example: --purger mine.
|
|
81
|
+
purge_exclusions: A table to leave as it is, by name or
|
|
82
|
+
schema-qualified name; repeat for several. Example:
|
|
83
|
+
--purge-exclusions countries.
|
|
84
|
+
purge_with_truncate: Empty the tables with TRUNCATE rather than
|
|
85
|
+
DELETE. Example: --purge-with-truncate.
|
|
86
|
+
"""
|
|
87
|
+
name = connection or self._connections.default
|
|
88
|
+
if not self._connections.has(name):
|
|
89
|
+
unknown = UnknownConnectionError(name, self._connections.names())
|
|
90
|
+
io.error(escape(str(unknown)))
|
|
91
|
+
return ExitCode.FAILURE
|
|
92
|
+
if not (append or dry_run) and not await self._confirmed(io, name):
|
|
93
|
+
return ExitCode.SUCCESS
|
|
94
|
+
|
|
95
|
+
groups = tuple(group or ())
|
|
96
|
+
try:
|
|
97
|
+
ordered = await _ordered(fixtures, groups)
|
|
98
|
+
except OrmFixturesError as error:
|
|
99
|
+
io.error(escape(str(error)))
|
|
100
|
+
return ExitCode.FAILURE
|
|
101
|
+
if not ordered:
|
|
102
|
+
where = f" in the groups ({', '.join(groups)})" if groups else ""
|
|
103
|
+
io.error(escape(f"Could not find any fixture services to load{where}."))
|
|
104
|
+
return ExitCode.FAILURE
|
|
105
|
+
|
|
106
|
+
if purger not in self._purger_factories:
|
|
107
|
+
known = ", ".join(str(alias) for alias in self._purger_factories.provided_services())
|
|
108
|
+
io.error(
|
|
109
|
+
escape(f'No purger factory is named "{purger}"; the purger factories are: {known}.')
|
|
110
|
+
)
|
|
111
|
+
return ExitCode.INVALID
|
|
112
|
+
emptying: PurgerInterface | None = None
|
|
113
|
+
if not append:
|
|
114
|
+
try:
|
|
115
|
+
definitions = self._tables.for_connection(name)
|
|
116
|
+
except OrmFixturesError as error:
|
|
117
|
+
io.error(escape(str(error)))
|
|
118
|
+
return ExitCode.INVALID
|
|
119
|
+
factory = await self._purger_factories.get(purger)
|
|
120
|
+
emptying = factory.create_for_connection(
|
|
121
|
+
name,
|
|
122
|
+
definitions,
|
|
123
|
+
excluded=tuple(purge_exclusions or ()),
|
|
124
|
+
purge_with_truncate=purge_with_truncate,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
session = await self._connections.session(name)
|
|
129
|
+
except SessionUnavailableError as error:
|
|
130
|
+
io.error(escape(str(error)))
|
|
131
|
+
return ExitCode.FAILURE
|
|
132
|
+
if dry_run:
|
|
133
|
+
io.text(" (dry-run)")
|
|
134
|
+
executor_type: type[AbstractExecutor] = DryRunOrmExecutor if dry_run else OrmExecutor
|
|
135
|
+
await executor_type(session, emptying, _ConsoleLogger(io)).execute(ordered, append=append)
|
|
136
|
+
|
|
137
|
+
loaded = f"Loaded {len(ordered)} fixture{'' if len(ordered) == 1 else 's'}"
|
|
138
|
+
io.success(f"{loaded} and rolled them back." if dry_run else f"{loaded}.")
|
|
139
|
+
return ExitCode.SUCCESS
|
|
140
|
+
|
|
141
|
+
async def _confirmed(self, io: ConsoleStyle, name: str) -> bool:
|
|
142
|
+
"""Ask before emptying; a run nobody can answer goes ahead."""
|
|
143
|
+
database = (await self._connections.engine(name)).url.database or name
|
|
144
|
+
return io.confirm(
|
|
145
|
+
escape(f'Careful, database "{database}" will be purged. Do you want to continue?'),
|
|
146
|
+
default=not io.interactive,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def _ordered(
|
|
151
|
+
fixtures: ServiceLocator[FixtureInterface], groups: tuple[str, ...]
|
|
152
|
+
) -> list[FixtureInterface]:
|
|
153
|
+
"""Return the fixtures of ``groups`` — all of them, with none — in the order they load.
|
|
154
|
+
|
|
155
|
+
Raises:
|
|
156
|
+
OrmFixturesError: If a fixture is refused, depends on one that is not
|
|
157
|
+
there, or the fixtures depend on one another in a circle.
|
|
158
|
+
"""
|
|
159
|
+
loader = Loader()
|
|
160
|
+
loader.add_fixtures([fixture async for _, fixture in fixtures])
|
|
161
|
+
return loader.get_fixtures(groups)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@final
|
|
165
|
+
class _ConsoleLogger(AbstractLogger):
|
|
166
|
+
"""Writes each message of a run to the console, its placeholders filled in."""
|
|
167
|
+
|
|
168
|
+
def __init__(self, io: ConsoleStyle) -> None:
|
|
169
|
+
self._io = io
|
|
170
|
+
|
|
171
|
+
@override
|
|
172
|
+
def log(self, level: LevelLike, message: str, /, context: Context | None = None) -> None:
|
|
173
|
+
del level
|
|
174
|
+
for key, value in (context or {}).items():
|
|
175
|
+
message = message.replace(f"{{{key}}}", str(value))
|
|
176
|
+
self._io.text(f" > {escape(message)}")
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""A fixture loaded after the fixtures it names."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from .fixture_interface import FixtureInterface
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
|
|
12
|
+
__all__ = ["DependentFixtureInterface"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@runtime_checkable
|
|
16
|
+
class DependentFixtureInterface(FixtureInterface, Protocol):
|
|
17
|
+
"""A fixture needing others loaded first — those whose references it reads.
|
|
18
|
+
|
|
19
|
+
A fixture is ordered by its dependencies or by a number, never by both.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def get_dependencies(self) -> Sequence[type[FixtureInterface]]:
|
|
23
|
+
"""Return the fixture classes to load before this one; never empty, never this one."""
|
|
24
|
+
...
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Every error this library raises, all deriving from :class:`OrmFixturesError`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .circular_reference_error import CircularReferenceError
|
|
6
|
+
from .invalid_argument_error import InvalidArgumentError
|
|
7
|
+
from .missing_fixture_error import MissingFixtureError
|
|
8
|
+
from .orm_fixtures_error import OrmFixturesError
|
|
9
|
+
from .reference_exists_error import ReferenceExistsError
|
|
10
|
+
from .reference_not_found_error import ReferenceNotFoundError
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"CircularReferenceError",
|
|
14
|
+
"InvalidArgumentError",
|
|
15
|
+
"MissingFixtureError",
|
|
16
|
+
"OrmFixturesError",
|
|
17
|
+
"ReferenceExistsError",
|
|
18
|
+
"ReferenceNotFoundError",
|
|
19
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Fixtures depend on one another in a circle, so none of them can be loaded first."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .orm_fixtures_error import OrmFixturesError
|
|
6
|
+
|
|
7
|
+
__all__ = ["CircularReferenceError"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CircularReferenceError(OrmFixturesError):
|
|
11
|
+
"""Fixtures depend on one another in a circle, so none of them can be loaded first.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
fixtures: The fixtures in the circle, by name, in the order they depend
|
|
15
|
+
on one another; the first is named again at the end.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
fixtures: tuple[str, ...]
|
|
19
|
+
|
|
20
|
+
def __init__(self, fixtures: tuple[str, ...]) -> None:
|
|
21
|
+
"""Record the fixtures in the circle."""
|
|
22
|
+
self.fixtures = fixtures
|
|
23
|
+
circle = " -> ".join(fixtures)
|
|
24
|
+
super().__init__(f"The fixtures depend on one another in a circle: {circle}.")
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""A call was given something the library cannot work with."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .orm_fixtures_error import OrmFixturesError
|
|
6
|
+
|
|
7
|
+
__all__ = ["InvalidArgumentError"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class InvalidArgumentError(OrmFixturesError, ValueError):
|
|
11
|
+
"""A call was given something the library cannot work with.
|
|
12
|
+
|
|
13
|
+
Raised where the value is given — an unknown purger, a fixture asked for a
|
|
14
|
+
reference before a run gave it one — rather than later, when the database
|
|
15
|
+
is reached.
|
|
16
|
+
|
|
17
|
+
Also a :class:`ValueError`, so code that already guards its input with
|
|
18
|
+
``except ValueError`` keeps working without learning a new exception.
|
|
19
|
+
|
|
20
|
+
Attributes:
|
|
21
|
+
reason: What is wrong with the value.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
reason: str
|
|
25
|
+
|
|
26
|
+
def __init__(self, reason: str) -> None:
|
|
27
|
+
"""Record what is wrong with the value."""
|
|
28
|
+
self.reason = reason
|
|
29
|
+
super().__init__(reason)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""A fixture depends on one that was never added to the loader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .orm_fixtures_error import OrmFixturesError
|
|
6
|
+
|
|
7
|
+
__all__ = ["MissingFixtureError"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class MissingFixtureError(OrmFixturesError, LookupError):
|
|
11
|
+
"""A fixture depends on one that was never added to the loader.
|
|
12
|
+
|
|
13
|
+
Also a :class:`LookupError`, as a missing key in any other mapping is.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
fixture: The fixture depended on, by name.
|
|
17
|
+
required_by: The fixture depending on it, by name.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
fixture: str
|
|
21
|
+
required_by: str
|
|
22
|
+
|
|
23
|
+
def __init__(self, fixture: str, required_by: str) -> None:
|
|
24
|
+
"""Record the fixture missing and the one depending on it."""
|
|
25
|
+
self.fixture = fixture
|
|
26
|
+
self.required_by = required_by
|
|
27
|
+
super().__init__(
|
|
28
|
+
f'The fixture "{required_by}" depends on "{fixture}", which was not added; '
|
|
29
|
+
"add it, or remove the dependency."
|
|
30
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""The root every error in this library derives from."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = ["OrmFixturesError"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class OrmFixturesError(Exception):
|
|
9
|
+
"""Base class for every error raised by this library.
|
|
10
|
+
|
|
11
|
+
Catch this to handle anything the library can refuse; catch a subclass to
|
|
12
|
+
handle one cause. Every subclass carries the data a caller needs as typed
|
|
13
|
+
attributes and composes its own message from them.
|
|
14
|
+
"""
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""A reference was added under a name already taken."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .orm_fixtures_error import OrmFixturesError
|
|
6
|
+
|
|
7
|
+
__all__ = ["ReferenceExistsError"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ReferenceExistsError(OrmFixturesError):
|
|
11
|
+
"""A reference was added under a name already taken.
|
|
12
|
+
|
|
13
|
+
Adding refuses to replace; setting replaces on purpose.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
name: The name already taken.
|
|
17
|
+
kind: The class the reference is stored for, by name.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
kind: str
|
|
22
|
+
|
|
23
|
+
def __init__(self, name: str, kind: str) -> None:
|
|
24
|
+
"""Record the name taken and the class it is stored for."""
|
|
25
|
+
self.name = name
|
|
26
|
+
self.kind = kind
|
|
27
|
+
super().__init__(
|
|
28
|
+
f'A reference named "{name}" is already stored for "{kind}"; '
|
|
29
|
+
"use set_reference to replace it."
|
|
30
|
+
)
|