bazaar-contrib-schema 0.3.0rc1__tar.gz

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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-contrib-schema
3
+ Version: 0.3.0rc1
4
+ Summary: Module schema registration and versioned migrations
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: bazaar-core~=0.3.0rc1
8
+ Requires-Dist: bazaar-contrib-storage~=0.3.0rc1
9
+ Requires-Dist: packaging>=25.0
10
+ Requires-Dist: pydantic>=2.12.0
11
+ Requires-Python: >=3.15
12
+ Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
13
+ Description-Content-Type: text/markdown
14
+
15
+ # bazaar-contrib-schema
16
+
17
+ Register contrib-owned tables and migrations through `SCHEMA` before starting business services.
18
+
19
+ ```sh
20
+ bcn contrib add schema --enable
21
+ ```
22
+
23
+ The corresponding entry in `config.toml`:
24
+
25
+ ```toml
26
+ version = "5"
27
+
28
+ [[contribs]]
29
+ package = "bazaar-contrib-schema~=0.3.0rc1"
30
+ [[contribs.enabled]]
31
+ entry = "schema"
32
+ ```
33
+
34
+ ```python
35
+ from contextlib import asynccontextmanager
36
+
37
+ from bazaar_contrib_schema import SCHEMA, Migration, ModuleSchema
38
+ from bazaar_contrib_storage import ColumnDefinition, CreateTable, Table
39
+ from bazaar_core import Context, Contrib
40
+
41
+ MODULE = ModuleSchema(
42
+ tables=("notes",),
43
+ migrations=(
44
+ Migration(
45
+ version=1,
46
+ name="create_notes",
47
+ operations=(
48
+ CreateTable(
49
+ table=Table(
50
+ name="notes",
51
+ columns=(ColumnDefinition(name="id", type="text"),),
52
+ primary_key=("id",),
53
+ )
54
+ ),
55
+ ),
56
+ ),
57
+ ),
58
+ )
59
+
60
+
61
+ @asynccontextmanager
62
+ async def lifespan(ctx: Context):
63
+ async with ctx.accept(SCHEMA).register(MODULE):
64
+ # Create and offer business services here, after migrations finish.
65
+ yield
66
+
67
+
68
+ notes = Contrib(accepts=[SCHEMA], lifespan=lifespan)
69
+ ```
70
+
71
+ Append consecutive migration versions starting at 1 and keep published migrations unchanged.
@@ -0,0 +1,57 @@
1
+ # bazaar-contrib-schema
2
+
3
+ Register contrib-owned tables and migrations through `SCHEMA` before starting business services.
4
+
5
+ ```sh
6
+ bcn contrib add schema --enable
7
+ ```
8
+
9
+ The corresponding entry in `config.toml`:
10
+
11
+ ```toml
12
+ version = "5"
13
+
14
+ [[contribs]]
15
+ package = "bazaar-contrib-schema~=0.3.0rc1"
16
+ [[contribs.enabled]]
17
+ entry = "schema"
18
+ ```
19
+
20
+ ```python
21
+ from contextlib import asynccontextmanager
22
+
23
+ from bazaar_contrib_schema import SCHEMA, Migration, ModuleSchema
24
+ from bazaar_contrib_storage import ColumnDefinition, CreateTable, Table
25
+ from bazaar_core import Context, Contrib
26
+
27
+ MODULE = ModuleSchema(
28
+ tables=("notes",),
29
+ migrations=(
30
+ Migration(
31
+ version=1,
32
+ name="create_notes",
33
+ operations=(
34
+ CreateTable(
35
+ table=Table(
36
+ name="notes",
37
+ columns=(ColumnDefinition(name="id", type="text"),),
38
+ primary_key=("id",),
39
+ )
40
+ ),
41
+ ),
42
+ ),
43
+ ),
44
+ )
45
+
46
+
47
+ @asynccontextmanager
48
+ async def lifespan(ctx: Context):
49
+ async with ctx.accept(SCHEMA).register(MODULE):
50
+ # Create and offer business services here, after migrations finish.
51
+ yield
52
+
53
+
54
+ notes = Contrib(accepts=[SCHEMA], lifespan=lifespan)
55
+ ```
56
+
57
+ Append consecutive migration versions starting at 1 and keep published migrations unchanged.
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "bazaar-contrib-schema"
3
+ version = "0.3.0rc1"
4
+ description = "Module schema registration and versioned migrations"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.15"
9
+ dependencies = [
10
+ "bazaar-core~=0.3.0rc1",
11
+ "bazaar-contrib-storage~=0.3.0rc1",
12
+ "packaging>=25.0",
13
+ "pydantic>=2.12.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
18
+
19
+ [project.entry-points."bazaar_compute_node.contribs"]
20
+ schema = "bazaar_contrib_schema:schema"
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.13.0,<0.14.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+ addopts = "-p no:anyio"
29
+ asyncio_mode = "auto"
30
+ asyncio_default_fixture_loop_scope = "function"
31
+
32
+ [tool.pyright]
33
+ extends = "../../pyrightconfig.json"
34
+ include = [
35
+ "src",
36
+ "tests",
37
+ ]
38
+
39
+ [tool.ruff]
40
+ extend = "../../pyproject.toml"
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "bazaar-contrib-schema"
3
+ version = "0.3.0rc1"
4
+ description = "Module schema registration and versioned migrations"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.15"
9
+ dependencies = ["bazaar-core~=0.3.0rc1", "bazaar-contrib-storage~=0.3.0rc1", "packaging>=25.0", "pydantic>=2.12.0"]
10
+
11
+ [project.urls]
12
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
13
+
14
+ [project.entry-points."bazaar_compute_node.contribs"]
15
+ schema = "bazaar_contrib_schema:schema"
16
+
17
+ [build-system]
18
+ requires = ["uv_build>=0.13.0,<0.14.0"]
19
+ build-backend = "uv_build"
20
+
21
+ [tool.pytest.ini_options]
22
+ testpaths = ["tests"]
23
+ addopts = "-p no:anyio"
24
+ asyncio_mode = "auto"
25
+ asyncio_default_fixture_loop_scope = "function"
26
+
27
+ [tool.pyright]
28
+ extends = "../../pyrightconfig.json"
29
+ include = ["src", "tests"]
30
+
31
+ [tool.ruff]
32
+ extend = "../../pyproject.toml"
@@ -0,0 +1,430 @@
1
+ """Transactional, version-based migrations registered by business plugins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager
6
+ from typing import Annotated, Self, cast
7
+ lazy import asyncio
8
+ lazy from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
9
+ lazy from time import monotonic_ns, time_ns
10
+
11
+ from bazaar_contrib_storage import (
12
+ DB,
13
+ Column,
14
+ ColumnDefinition,
15
+ Compare,
16
+ Copy,
17
+ CreateTable,
18
+ Delete,
19
+ Identifier,
20
+ In,
21
+ Insert,
22
+ MigrationError,
23
+ Mutation,
24
+ RenameTable,
25
+ SchemaOperation,
26
+ Select,
27
+ Sort,
28
+ Table,
29
+ Update,
30
+ Value,
31
+ )
32
+ from bazaar_core import CURRENT_CONTEXT, Context, Contrib, ServiceKey
33
+ from packaging.utils import canonicalize_name
34
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
35
+ lazy from bazaar_contrib_storage import Database, Record, Session
36
+
37
+ __all__ = [
38
+ "SCHEMA",
39
+ "Dependency",
40
+ "Migration",
41
+ "ModuleSchema",
42
+ "Progress",
43
+ "Schema",
44
+ "schema",
45
+ ]
46
+
47
+ type Package = Annotated[str, Field(pattern=r"^[a-z0-9]+(?:[-.][a-z0-9]+)*$")]
48
+
49
+
50
+ class Migration(BaseModel):
51
+ model_config = ConfigDict(extra="forbid", frozen=True)
52
+ version: int = Field(gt=0)
53
+ name: str = Field(min_length=1)
54
+ operations: tuple[SchemaOperation, ...] = ()
55
+ apply: Callable[[Session], Awaitable[None]] | None = None
56
+
57
+ @model_validator(mode="after")
58
+ def implementation(self) -> Self:
59
+ if not self.operations and self.apply is None:
60
+ raise ValueError("a migration requires operations or an apply callback")
61
+ return self
62
+
63
+
64
+ class Progress(BaseModel):
65
+ """Identify a module's version records in an existing database."""
66
+
67
+ model_config = ConfigDict(extra="forbid", frozen=True)
68
+ table: Identifier
69
+ identity: str = Field(min_length=1)
70
+ version: Identifier = "version"
71
+ name: Identifier = "migration_name"
72
+ package: Package | None = None
73
+
74
+
75
+ class Dependency(BaseModel):
76
+ model_config = ConfigDict(extra="forbid", frozen=True)
77
+ package: Package
78
+ version: int = Field(gt=0)
79
+
80
+
81
+ def operation_tables(operation: SchemaOperation) -> tuple[str, ...]:
82
+ if isinstance(operation, CreateTable):
83
+ return (operation.table.name,)
84
+ if isinstance(operation, RenameTable):
85
+ return (operation.table, operation.name)
86
+ return (operation.table,)
87
+
88
+
89
+ class ModuleSchema(BaseModel):
90
+ model_config = ConfigDict(extra="forbid", frozen=True)
91
+ tables: tuple[Identifier, ...] = Field(min_length=1)
92
+ migrations: tuple[Migration, ...] = Field(min_length=1)
93
+ baseline: Migration | None = None
94
+ progress: Progress | None = None
95
+ predecessor: Dependency | None = None
96
+ dependencies: tuple[Dependency, ...] = ()
97
+
98
+ @property
99
+ def version(self) -> int:
100
+ return self.migrations[-1].version
101
+
102
+ @model_validator(mode="after")
103
+ def ownership(self) -> Self:
104
+ if tuple(item.version for item in self.migrations) != tuple(
105
+ range(1, len(self.migrations) + 1)
106
+ ):
107
+ raise ValueError(
108
+ "module migrations must have consecutive versions starting at 1"
109
+ )
110
+ if len(set(self.tables)) != len(self.tables):
111
+ raise ValueError("module table names must be unique")
112
+ if self.baseline is not None and self.baseline.version > self.version:
113
+ raise ValueError("baseline version must belong to the module's migrations")
114
+ if self.predecessor is not None and self.baseline is None:
115
+ raise ValueError("a predecessor requires a baseline for ownership handoff")
116
+ migrations = (
117
+ (*self.migrations, self.baseline)
118
+ if self.baseline is not None
119
+ else self.migrations
120
+ )
121
+ for migration in migrations:
122
+ for operation in migration.operations:
123
+ for table in operation_tables(operation):
124
+ if table not in self.tables:
125
+ raise ValueError(
126
+ f"migration operation uses unowned table {table!r}"
127
+ )
128
+ return self
129
+
130
+
131
+ _LEDGER = Table(
132
+ name="contrib_schema_migrations",
133
+ columns=(
134
+ ColumnDefinition(name="package", type="text"),
135
+ ColumnDefinition(name="version", type="integer"),
136
+ ColumnDefinition(name="name", type="text"),
137
+ ColumnDefinition(name="applied_at_ms", type="integer"),
138
+ ColumnDefinition(name="duration_ms", type="integer"),
139
+ ),
140
+ primary_key=("package", "version"),
141
+ )
142
+ _OWNERS = Table(
143
+ name="contrib_schema_tables",
144
+ columns=(
145
+ ColumnDefinition(name="name", type="text"),
146
+ ColumnDefinition(name="package", type="text"),
147
+ ),
148
+ primary_key=("name",),
149
+ )
150
+
151
+
152
+ class MigrationSession:
153
+ """Constrain migration writes to the module's declared tables."""
154
+
155
+ def __init__(self, session: Session, package: str, tables: tuple[str, ...]) -> None:
156
+ self._session = session
157
+ self._package = package
158
+ self._tables = tables
159
+
160
+ def _require_table(self, table: str) -> None:
161
+ if table not in self._tables:
162
+ raise MigrationError(
163
+ f"{self._package} migration uses unowned table {table!r}"
164
+ )
165
+
166
+ async def table_exists(self, name: str) -> bool:
167
+ return await self._session.table_exists(name)
168
+
169
+ async def select(self, request: Select) -> tuple[Record, ...]:
170
+ return await self._session.select(request)
171
+
172
+ async def insert(self, request: Insert) -> Mutation:
173
+ self._require_table(request.table)
174
+ return await self._session.insert(request)
175
+
176
+ async def copy(self, request: Copy) -> Mutation:
177
+ self._require_table(request.table)
178
+ return await self._session.copy(request)
179
+
180
+ async def update(self, request: Update) -> Mutation:
181
+ self._require_table(request.table)
182
+ return await self._session.update(request)
183
+
184
+ async def delete(self, request: Delete) -> Mutation:
185
+ self._require_table(request.table)
186
+ return await self._session.delete(request)
187
+
188
+ async def apply_schema(self, operations: tuple[SchemaOperation, ...]) -> None:
189
+ for operation in operations:
190
+ for table in operation_tables(operation):
191
+ self._require_table(table)
192
+ await self._session.apply_schema(operations)
193
+
194
+
195
+ class Schema:
196
+ def __init__(self, database: Database) -> None:
197
+ self._database = database
198
+ self._modules: dict[str, ModuleSchema] = {}
199
+ self._lock = asyncio.Lock()
200
+
201
+ @property
202
+ def modules(self) -> Mapping[str, ModuleSchema]:
203
+ return dict(self._modules)
204
+
205
+ async def start(self) -> None:
206
+ await self._database.apply_schema(
207
+ (
208
+ CreateTable(table=_LEDGER, if_not_exists=True),
209
+ CreateTable(table=_OWNERS, if_not_exists=True),
210
+ )
211
+ )
212
+
213
+ async def _version(
214
+ self, session: Session, package: str, progress: Progress | None
215
+ ) -> int:
216
+ for identity in (
217
+ package,
218
+ *((progress.package,) if progress is not None and progress.package else ()),
219
+ ):
220
+ applied = await session.select(
221
+ Select(
222
+ table=_LEDGER.name,
223
+ where=Compare(
224
+ left=Column(name="package"),
225
+ operator="=",
226
+ right=Value(value=identity),
227
+ ),
228
+ order_by=(
229
+ Sort(expression=Column(name="version"), descending=True),
230
+ ),
231
+ limit=1,
232
+ )
233
+ )
234
+ if applied:
235
+ version = cast(int, applied[0]["version"])
236
+ if identity != package:
237
+ await self._record(
238
+ session, package, version, cast(str, applied[0]["name"])
239
+ )
240
+ return version
241
+ if progress is not None and await session.table_exists(progress.table):
242
+ history = await session.select(
243
+ Select(
244
+ table=progress.table,
245
+ columns={
246
+ "version": Column(name=progress.version),
247
+ "name": Column(name=progress.name),
248
+ },
249
+ order_by=(Sort(expression=Column(name=progress.version)),),
250
+ )
251
+ )
252
+ if history and history[0]["name"] == progress.identity:
253
+ versions = tuple(row["version"] for row in history)
254
+ if versions != tuple(range(1, len(history) + 1)):
255
+ raise MigrationError(
256
+ f"{package} existing migration ledger has a version gap"
257
+ )
258
+ version = cast(int, history[-1]["version"])
259
+ await self._record(
260
+ session, package, version, cast(str, history[-1]["name"])
261
+ )
262
+ return version
263
+ return 0
264
+
265
+ async def _record(
266
+ self,
267
+ session: Session,
268
+ package: str,
269
+ version: int,
270
+ name: str,
271
+ duration_ms: int = 0,
272
+ ) -> None:
273
+ await session.insert(
274
+ Insert(
275
+ table=_LEDGER.name,
276
+ rows=(
277
+ {
278
+ "package": package,
279
+ "version": version,
280
+ "name": name,
281
+ "applied_at_ms": time_ns() // 1_000_000,
282
+ "duration_ms": duration_ms,
283
+ },
284
+ ),
285
+ )
286
+ )
287
+
288
+ @asynccontextmanager
289
+ async def register(
290
+ self, module: ModuleSchema, *, upgrade_only: bool = False
291
+ ) -> AsyncIterator[None]:
292
+ """Register one schema; upgrade-only registrations leave fresh databases alone."""
293
+ ctx = CURRENT_CONTEXT.get()
294
+ if ctx is None or ctx.source is None:
295
+ raise MigrationError(
296
+ "schema registration requires an installed contrib source"
297
+ )
298
+ package = canonicalize_name(ctx.source.package)
299
+ async with self._lock:
300
+ if package in self._modules:
301
+ raise MigrationError(
302
+ f"schema package {package!r} is already registered"
303
+ )
304
+ for dependency in module.dependencies:
305
+ prerequisite = self._modules.get(dependency.package)
306
+ if prerequisite is None or prerequisite.version < dependency.version:
307
+ raise MigrationError(
308
+ f"{package} requires registered schema {dependency.package} >= {dependency.version}"
309
+ )
310
+
311
+ async def apply(session: Session) -> None:
312
+ version = await self._version(session, package, module.progress)
313
+ if version > module.version:
314
+ raise MigrationError(
315
+ f"{package} has unknown applied migration version {version}"
316
+ )
317
+ if upgrade_only and version in (0, module.version):
318
+ return
319
+ inherited = False
320
+ predecessor = module.predecessor
321
+ origins: set[str] = set()
322
+ if (
323
+ version
324
+ and module.progress is not None
325
+ and module.progress.package is not None
326
+ ):
327
+ origins.add(module.progress.package)
328
+ if predecessor is not None:
329
+ previous = await self._version(session, predecessor.package, None)
330
+ if previous and previous < predecessor.version:
331
+ raise MigrationError(
332
+ f"{package} requires predecessor {predecessor.package} >= {predecessor.version}"
333
+ )
334
+ inherited = previous >= predecessor.version
335
+ if inherited:
336
+ origins.add(predecessor.package)
337
+ declaration = self._modules.get(predecessor.package)
338
+ if (
339
+ declaration is not None
340
+ and declaration.progress is not None
341
+ and declaration.progress.package is not None
342
+ ):
343
+ origins.add(declaration.progress.package)
344
+ owners = await session.select(
345
+ Select(
346
+ table=_OWNERS.name,
347
+ where=In(expression=Column(name="name"), values=module.tables),
348
+ )
349
+ )
350
+ owned = {row["name"] for row in owners}
351
+ for row in owners:
352
+ if row["package"] == package:
353
+ continue
354
+ if row["package"] not in origins:
355
+ raise MigrationError(
356
+ f"table {row['name']!r} belongs to {row['package']!r}"
357
+ )
358
+ await session.update(
359
+ Update(
360
+ table=_OWNERS.name,
361
+ values={"package": Value(value=package)},
362
+ where=Compare(
363
+ left=Column(name="name"),
364
+ operator="=",
365
+ right=Value(value=row["name"]),
366
+ ),
367
+ )
368
+ )
369
+ for table in module.tables:
370
+ if table in {_LEDGER.name, _OWNERS.name}:
371
+ raise MigrationError(
372
+ f"table {table!r} belongs to the schema service"
373
+ )
374
+ if table not in owned:
375
+ await session.insert(
376
+ Insert(
377
+ table=_OWNERS.name,
378
+ rows=({"name": table, "package": package},),
379
+ )
380
+ )
381
+ if version == 0 and inherited:
382
+ baseline = module.baseline
383
+ assert baseline is not None
384
+ version = baseline.version
385
+ await self._record(session, package, version, baseline.name)
386
+ pending = tuple(
387
+ migration
388
+ for migration in module.migrations
389
+ if migration.version > version
390
+ )
391
+ if version == 0 and module.baseline is not None:
392
+ pending = (
393
+ module.baseline,
394
+ *(m for m in pending if m.version > module.baseline.version),
395
+ )
396
+ bound = MigrationSession(session, package, module.tables)
397
+ for migration in pending:
398
+ started = monotonic_ns()
399
+ await bound.apply_schema(migration.operations)
400
+ if migration.apply is not None:
401
+ await migration.apply(bound)
402
+ await self._record(
403
+ session,
404
+ package,
405
+ migration.version,
406
+ migration.name,
407
+ (monotonic_ns() - started) // 1_000_000,
408
+ )
409
+
410
+ await self._database.transaction(apply)
411
+ self._modules[package] = module
412
+ try:
413
+ yield
414
+ finally:
415
+ async with self._lock:
416
+ del self._modules[package]
417
+
418
+
419
+ SCHEMA = ServiceKey[Schema]("storage.schema")
420
+
421
+
422
+ @asynccontextmanager
423
+ async def lifespan(ctx: Context):
424
+ service = Schema(ctx.accept(DB))
425
+ await service.start()
426
+ ctx.offer(SCHEMA, service)
427
+ yield
428
+
429
+
430
+ schema = Contrib(accepts=[DB], offers=[SCHEMA], lifespan=lifespan)