bazaar-contrib-storage 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,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: bazaar-contrib-storage
3
+ Version: 0.3.0rc1
4
+ Summary: Shared explicit storage contracts and backend selection
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Dist: bazaar-core~=0.3.0rc1
8
+ Requires-Dist: pydantic>=2.12.0
9
+ Requires-Python: >=3.15
10
+ Project-URL: Repository, https://github.com/yuchanns/bazaar-compute-node
11
+ Description-Content-Type: text/markdown
12
+
13
+ # bazaar-contrib-storage
14
+
15
+ Enable backend registration and select the database backend. Install the selected provider as well.
16
+
17
+ ```sh
18
+ bcn contrib add storage --enable
19
+ ```
20
+
21
+ The corresponding entry in `config.toml`:
22
+
23
+ ```toml
24
+ version = "5"
25
+
26
+ [[contribs]]
27
+ package = "bazaar-contrib-storage~=0.3.0rc1"
28
+ [[contribs.enabled]]
29
+ entry = "storage"
30
+ [[contribs.enabled]]
31
+ entry = "database"
32
+ [contribs.enabled.config]
33
+ backend = "sqlite"
34
+ ```
@@ -0,0 +1,22 @@
1
+ # bazaar-contrib-storage
2
+
3
+ Enable backend registration and select the database backend. Install the selected provider as well.
4
+
5
+ ```sh
6
+ bcn contrib add storage --enable
7
+ ```
8
+
9
+ The corresponding entry in `config.toml`:
10
+
11
+ ```toml
12
+ version = "5"
13
+
14
+ [[contribs]]
15
+ package = "bazaar-contrib-storage~=0.3.0rc1"
16
+ [[contribs.enabled]]
17
+ entry = "storage"
18
+ [[contribs.enabled]]
19
+ entry = "database"
20
+ [contribs.enabled.config]
21
+ backend = "sqlite"
22
+ ```
@@ -0,0 +1,33 @@
1
+ [project]
2
+ name = "bazaar-contrib-storage"
3
+ version = "0.3.0rc1"
4
+ description = "Shared explicit storage contracts and backend selection"
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
+ "pydantic>=2.12.0",
12
+ ]
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/yuchanns/bazaar-compute-node"
16
+
17
+ [project.entry-points."bazaar_compute_node.contribs"]
18
+ storage = "bazaar_contrib_storage:storage"
19
+ database = "bazaar_contrib_storage:database"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.13.0,<0.14.0"]
23
+ build-backend = "uv_build"
24
+
25
+ [tool.bcn.ci]
26
+ skip = true
27
+
28
+ [tool.pyright]
29
+ extends = "../../pyrightconfig.json"
30
+ include = ["src"]
31
+
32
+ [tool.ruff]
33
+ extend = "../../pyproject.toml"
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "bazaar-contrib-storage"
3
+ version = "0.3.0rc1"
4
+ description = "Shared explicit storage contracts and backend selection"
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", "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
+ storage = "bazaar_contrib_storage:storage"
16
+ database = "bazaar_contrib_storage:database"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.13.0,<0.14.0"]
20
+ build-backend = "uv_build"
21
+
22
+ [tool.bcn.ci]
23
+ skip = true
24
+
25
+ [tool.pyright]
26
+ extends = "../../pyrightconfig.json"
27
+ include = ["src"]
28
+
29
+ [tool.ruff]
30
+ extend = "../../pyproject.toml"
@@ -0,0 +1,135 @@
1
+ """Explicit queries, schema operations, and interchangeable storage services."""
2
+
3
+ from .contracts import (
4
+ DB,
5
+ STORAGE,
6
+ BackendName,
7
+ BackendRegistry,
8
+ Database,
9
+ DatabaseConfig,
10
+ MigrationError,
11
+ Session,
12
+ StorageClosedError,
13
+ StorageError,
14
+ StorageIntegrityError,
15
+ StorageQueryError,
16
+ StorageQueryTimeoutError,
17
+ StorageUnavailableError,
18
+ backend_key,
19
+ database,
20
+ storage,
21
+ )
22
+ from .models import (
23
+ AddColumn,
24
+ All,
25
+ AnyOf,
26
+ Binary,
27
+ Call,
28
+ Case,
29
+ Column,
30
+ ColumnDefinition,
31
+ Compare,
32
+ Conflict,
33
+ Contains,
34
+ Copy,
35
+ CreateIndex,
36
+ CreateTable,
37
+ CreateTrigger,
38
+ Delete,
39
+ DropColumn,
40
+ DropIndex,
41
+ DropTable,
42
+ DropTrigger,
43
+ Expression,
44
+ ForeignKey,
45
+ Identifier,
46
+ In,
47
+ Index,
48
+ Insert,
49
+ IsNull,
50
+ Join,
51
+ Mutation,
52
+ Not,
53
+ Predicate,
54
+ Record,
55
+ Reference,
56
+ RenameColumn,
57
+ RenameTable,
58
+ RowId,
59
+ RowNumber,
60
+ Scalar,
61
+ SchemaOperation,
62
+ Search,
63
+ Select,
64
+ Sort,
65
+ Subquery,
66
+ Table,
67
+ Update,
68
+ Value,
69
+ )
70
+
71
+ __all__ = [
72
+ "DB",
73
+ "STORAGE",
74
+ "AddColumn",
75
+ "All",
76
+ "AnyOf",
77
+ "BackendName",
78
+ "BackendRegistry",
79
+ "Binary",
80
+ "Call",
81
+ "Case",
82
+ "Column",
83
+ "ColumnDefinition",
84
+ "Compare",
85
+ "Conflict",
86
+ "Contains",
87
+ "Copy",
88
+ "CreateIndex",
89
+ "CreateTable",
90
+ "CreateTrigger",
91
+ "Database",
92
+ "DatabaseConfig",
93
+ "Delete",
94
+ "DropColumn",
95
+ "DropIndex",
96
+ "DropTable",
97
+ "DropTrigger",
98
+ "Expression",
99
+ "ForeignKey",
100
+ "Identifier",
101
+ "In",
102
+ "Index",
103
+ "Insert",
104
+ "IsNull",
105
+ "Join",
106
+ "MigrationError",
107
+ "Mutation",
108
+ "Not",
109
+ "Predicate",
110
+ "Record",
111
+ "Reference",
112
+ "RenameColumn",
113
+ "RenameTable",
114
+ "RowId",
115
+ "RowNumber",
116
+ "Scalar",
117
+ "SchemaOperation",
118
+ "Search",
119
+ "Select",
120
+ "Session",
121
+ "Sort",
122
+ "StorageClosedError",
123
+ "StorageError",
124
+ "StorageIntegrityError",
125
+ "StorageQueryError",
126
+ "StorageQueryTimeoutError",
127
+ "StorageUnavailableError",
128
+ "Subquery",
129
+ "Table",
130
+ "Update",
131
+ "Value",
132
+ "backend_key",
133
+ "database",
134
+ "storage",
135
+ ]
@@ -0,0 +1,154 @@
1
+ """Storage services and lifespan-bound backend registration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import asynccontextmanager, contextmanager
6
+ from functools import cache
7
+ from typing import Annotated, Protocol
8
+ lazy from collections.abc import Awaitable, Callable, Iterator
9
+
10
+ from bazaar_core import Context, Contrib, ServiceKey
11
+ from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
12
+
13
+ lazy from .models import (
14
+ Copy,
15
+ Delete,
16
+ Insert,
17
+ Mutation,
18
+ Record,
19
+ SchemaOperation,
20
+ Select,
21
+ Update,
22
+ )
23
+
24
+ type BackendName = Annotated[str, Field(pattern=r"^[A-Za-z_][A-Za-z0-9_-]*$")]
25
+ _NAME = TypeAdapter(BackendName)
26
+
27
+
28
+ class StorageError(RuntimeError):
29
+ """A backend could not complete a public storage operation."""
30
+
31
+
32
+ class StorageClosedError(StorageError):
33
+ """The backend has finished its lifecycle."""
34
+
35
+
36
+ class StorageUnavailableError(StorageError):
37
+ """The underlying data source is unavailable or busy."""
38
+
39
+
40
+ class StorageIntegrityError(StorageError):
41
+ """A write violates the declared data constraints."""
42
+
43
+
44
+ class StorageQueryError(StorageError):
45
+ """The data source could not execute the declared operation."""
46
+
47
+
48
+ class StorageQueryTimeoutError(TimeoutError, StorageError):
49
+ """The data source interrupted a query after its execution budget."""
50
+
51
+
52
+ class MigrationError(StorageError):
53
+ """The stored migration history cannot be safely advanced."""
54
+
55
+
56
+ class Session(Protocol):
57
+ async def table_exists(self, name: str) -> bool: ...
58
+
59
+ async def select(self, request: Select) -> tuple[Record, ...]: ...
60
+
61
+ async def copy(self, request: Copy) -> Mutation: ...
62
+
63
+ async def insert(self, request: Insert) -> Mutation: ...
64
+
65
+ async def update(self, request: Update) -> Mutation: ...
66
+
67
+ async def delete(self, request: Delete) -> Mutation: ...
68
+
69
+ async def apply_schema(self, operations: tuple[SchemaOperation, ...]) -> None: ...
70
+
71
+
72
+ class Database(Session, Protocol):
73
+ async def read[T](
74
+ self,
75
+ operation: Callable[[Session], Awaitable[T]],
76
+ *,
77
+ snapshot: bool = False,
78
+ query_budget: float | None = None,
79
+ ) -> T:
80
+ """Run on one reader, optionally holding its original snapshot and budget."""
81
+ ...
82
+
83
+ async def write[T](
84
+ self,
85
+ operation: Callable[[Session], Awaitable[T]],
86
+ *,
87
+ transactional: bool = False,
88
+ ) -> T:
89
+ """Run one writer operation with its declared transaction boundary."""
90
+ ...
91
+
92
+ async def transaction[T](self, operation: Callable[[Session], Awaitable[T]]) -> T:
93
+ """Commit the operation together, rolling it back on failure or cancellation."""
94
+ ...
95
+
96
+
97
+ class BackendRegistry:
98
+ def __init__(self) -> None:
99
+ self._backends: dict[str, Database] = {}
100
+
101
+ @property
102
+ def names(self) -> tuple[str, ...]:
103
+ return tuple(self._backends)
104
+
105
+ def get(self, name: str) -> Database:
106
+ return self._backends[name]
107
+
108
+ @contextmanager
109
+ def register(self, name: str, database: Database) -> Iterator[None]:
110
+ name = _NAME.validate_python(name)
111
+ if name in self._backends:
112
+ raise StorageError(
113
+ f"storage backend {name!r} is already registered; choose a unique backend name"
114
+ )
115
+ self._backends[name] = database
116
+ try:
117
+ yield
118
+ finally:
119
+ del self._backends[name]
120
+
121
+
122
+ STORAGE = ServiceKey[BackendRegistry]("storage.backends")
123
+ DB = ServiceKey[Database]("storage.database")
124
+
125
+
126
+ @cache
127
+ def backend_key(name: str) -> ServiceKey[Database]:
128
+ return ServiceKey[Database](f"storage.backend.{_NAME.validate_python(name)}")
129
+
130
+
131
+ class DatabaseConfig(BaseModel):
132
+ model_config = ConfigDict(extra="forbid", frozen=True)
133
+ backend: BackendName
134
+
135
+
136
+ @asynccontextmanager
137
+ async def _storage(ctx: Context):
138
+ ctx.offer(STORAGE, BackendRegistry())
139
+ yield
140
+
141
+
142
+ @asynccontextmanager
143
+ async def _database(ctx: Context, config: DatabaseConfig):
144
+ ctx.offer(DB, ctx.accept(STORAGE).get(config.backend))
145
+ yield
146
+
147
+
148
+ storage = Contrib(offers=[STORAGE], lifespan=_storage)
149
+ database = Contrib(
150
+ config=DatabaseConfig,
151
+ accepts=lambda config: [STORAGE, backend_key(config.backend)],
152
+ offers=[DB],
153
+ lifespan=_database,
154
+ )
@@ -0,0 +1,410 @@
1
+ """Backend-independent data, query, and schema descriptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated, Literal, Self
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ StrictBool,
12
+ StrictBytes,
13
+ StrictFloat,
14
+ StrictInt,
15
+ StrictStr,
16
+ model_validator,
17
+ )
18
+
19
+ type Identifier = Annotated[
20
+ str, Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]*$", max_length=63)
21
+ ]
22
+ type Scalar = StrictStr | StrictInt | StrictFloat | StrictBool | StrictBytes | None
23
+ type Record = dict[str, Scalar]
24
+
25
+
26
+ class Model(BaseModel):
27
+ model_config = ConfigDict(
28
+ extra="forbid", frozen=True, allow_inf_nan=False, ser_json_bytes="base64"
29
+ )
30
+
31
+
32
+ class Column(Model):
33
+ kind: Literal["column"] = "column"
34
+ name: Identifier
35
+ table: Identifier | None = None
36
+
37
+
38
+ class RowId(Model):
39
+ """The provider's physical row identity within the current table."""
40
+
41
+ kind: Literal["row_id"] = "row_id"
42
+ table: Identifier | None = None
43
+
44
+
45
+ class Value(Model):
46
+ kind: Literal["value"] = "value"
47
+ value: Scalar
48
+
49
+
50
+ class Binary(Model):
51
+ kind: Literal["binary"] = "binary"
52
+ operator: Literal["+", "-", "*", "/", "%", "||"]
53
+ left: Expression
54
+ right: Expression
55
+
56
+
57
+ class Call(Model):
58
+ kind: Literal["call"] = "call"
59
+ name: Literal[
60
+ "count", "sum", "min", "max", "avg", "coalesce", "lower", "length", "replace"
61
+ ]
62
+ arguments: tuple[Expression, ...] = ()
63
+
64
+
65
+ class RowNumber(Model):
66
+ kind: Literal["row_number"] = "row_number"
67
+ order_by: Annotated[tuple[Sort, ...], Field(min_length=1)]
68
+ partition_by: tuple[Expression, ...] = ()
69
+
70
+
71
+ class Case(Model):
72
+ kind: Literal["case"] = "case"
73
+ when: Predicate
74
+ then: Expression
75
+ otherwise: Expression
76
+
77
+
78
+ class Subquery(Model):
79
+ kind: Literal["subquery"] = "subquery"
80
+ query: Select
81
+
82
+
83
+ type Expression = Annotated[
84
+ Column | RowId | Value | Binary | Call | RowNumber | Case | Subquery,
85
+ Field(discriminator="kind"),
86
+ ]
87
+
88
+
89
+ class Compare(Model):
90
+ kind: Literal["compare"] = "compare"
91
+ left: Expression
92
+ operator: Literal["=", "!=", "<", "<=", ">", ">="]
93
+ right: Expression
94
+
95
+
96
+ class In(Model):
97
+ kind: Literal["in"] = "in"
98
+ expression: Expression
99
+ values: tuple[Scalar, ...]
100
+ exclude: bool = False
101
+
102
+
103
+ class IsNull(Model):
104
+ kind: Literal["null"] = "null"
105
+ expression: Expression
106
+ exclude: bool = False
107
+
108
+
109
+ class Contains(Model):
110
+ kind: Literal["contains"] = "contains"
111
+ expression: Expression
112
+ text: str
113
+
114
+
115
+ class All(Model):
116
+ kind: Literal["all"] = "all"
117
+ conditions: tuple[Predicate, ...]
118
+
119
+
120
+ class AnyOf(Model):
121
+ kind: Literal["any"] = "any"
122
+ conditions: tuple[Predicate, ...]
123
+
124
+
125
+ class Not(Model):
126
+ kind: Literal["not"] = "not"
127
+ condition: Predicate
128
+
129
+
130
+ class Search(Model):
131
+ """Require every literal term to occur in at least one indexed column."""
132
+
133
+ kind: Literal["search"] = "search"
134
+ index: Identifier
135
+ table: Identifier
136
+ columns: Annotated[tuple[Identifier, ...], Field(min_length=1)]
137
+ terms: Annotated[
138
+ tuple[Annotated[str, Field(min_length=1)], ...], Field(min_length=1)
139
+ ]
140
+ row_key: Identifier | None = None
141
+
142
+
143
+ type Predicate = Annotated[
144
+ Compare | In | IsNull | Contains | All | AnyOf | Not | Search,
145
+ Field(discriminator="kind"),
146
+ ]
147
+
148
+
149
+ class Sort(Model):
150
+ expression: Expression
151
+ descending: bool = False
152
+ nulls: Literal["first", "last"] = "last"
153
+
154
+
155
+ class Join(Model):
156
+ table: Identifier
157
+ alias: Identifier | None = None
158
+ kind: Literal["inner", "left"] = "inner"
159
+ on: Predicate
160
+
161
+
162
+ class Select(Model):
163
+ table: Identifier
164
+ ctes: dict[Identifier, Select] = Field(default_factory=dict)
165
+ alias: Identifier | None = None
166
+ columns: dict[Identifier, Expression] = Field(default_factory=dict)
167
+ where: Predicate | None = None
168
+ joins: tuple[Join, ...] = ()
169
+ group_by: tuple[Expression, ...] = ()
170
+ having: Predicate | None = None
171
+ order_by: tuple[Sort, ...] = ()
172
+ limit: Annotated[int, Field(ge=0)] | None = None
173
+ offset: Annotated[int, Field(ge=0)] = 0
174
+ distinct: bool = False
175
+
176
+
177
+ class Copy(Model):
178
+ """Insert the explicitly named projection of a query into another table."""
179
+
180
+ table: Identifier
181
+ query: Select
182
+
183
+ @model_validator(mode="after")
184
+ def projection(self) -> Self:
185
+ if not self.query.columns:
186
+ raise ValueError("copy queries must explicitly name their target columns")
187
+ return self
188
+
189
+
190
+ class Conflict(Model):
191
+ columns: Annotated[tuple[Identifier, ...], Field(min_length=1)]
192
+ update: tuple[Identifier, ...] = ()
193
+
194
+
195
+ class Insert(Model):
196
+ table: Identifier
197
+ rows: Annotated[tuple[dict[Identifier, Scalar], ...], Field(min_length=1)]
198
+ conflict: Conflict | None = None
199
+ returning: tuple[Identifier, ...] = ()
200
+
201
+ @model_validator(mode="after")
202
+ def columns(self) -> Self:
203
+ columns = self.rows[0].keys()
204
+ if not columns or any(row.keys() != columns for row in self.rows):
205
+ raise ValueError("insert rows must contain the same non-empty column set")
206
+ return self
207
+
208
+
209
+ class Update(Model):
210
+ table: Identifier
211
+ values: Annotated[dict[Identifier, Expression], Field(min_length=1)]
212
+ where: Predicate | None = None
213
+ returning: tuple[Identifier, ...] = ()
214
+
215
+
216
+ class Delete(Model):
217
+ table: Identifier
218
+ where: Predicate | None = None
219
+ returning: tuple[Identifier, ...] = ()
220
+
221
+
222
+ class Mutation(Model):
223
+ count: Annotated[int, Field(ge=0)]
224
+ rows: tuple[Record, ...] = ()
225
+
226
+
227
+ class Reference(Model):
228
+ table: Identifier
229
+ column: Identifier
230
+ on_delete: Literal["restrict", "cascade", "set null"] = "restrict"
231
+
232
+
233
+ class ColumnDefinition(Model):
234
+ name: Identifier
235
+ type: Literal["text", "integer", "real", "blob"]
236
+ nullable: bool = False
237
+ default: Scalar = None
238
+ generated: bool = False
239
+ unique: bool = False
240
+ check: Predicate | None = None
241
+ references: Reference | None = None
242
+
243
+
244
+ class ForeignKey(Model):
245
+ columns: Annotated[tuple[Identifier, ...], Field(min_length=1)]
246
+ table: Identifier
247
+ references: Annotated[tuple[Identifier, ...], Field(min_length=1)]
248
+ on_delete: Literal["restrict", "cascade", "set null"] = "restrict"
249
+
250
+
251
+ class Table(Model):
252
+ name: Identifier
253
+ columns: Annotated[tuple[ColumnDefinition, ...], Field(min_length=1)]
254
+ primary_key: tuple[Identifier, ...] = ()
255
+ foreign_keys: tuple[ForeignKey, ...] = ()
256
+ unique: tuple[tuple[Identifier, ...], ...] = ()
257
+ checks: tuple[Predicate, ...] = ()
258
+
259
+ @model_validator(mode="after")
260
+ def definitions(self) -> Self:
261
+ columns = {column.name for column in self.columns}
262
+ if len(columns) != len(self.columns) or not set(self.primary_key) <= columns:
263
+ raise ValueError("table columns must be unique and contain its primary key")
264
+ if any(not key or not set(key) <= columns for key in self.unique):
265
+ raise ValueError("unique keys must contain columns belonging to the table")
266
+ for column in self.columns:
267
+ if column.generated and (
268
+ column.type != "integer" or self.primary_key != (column.name,)
269
+ ):
270
+ raise ValueError("a generated integer must be the sole primary key")
271
+ for key in self.foreign_keys:
272
+ if not set(key.columns) <= columns or len(key.columns) != len(
273
+ key.references
274
+ ):
275
+ raise ValueError(
276
+ "foreign key columns must belong to the table and match references"
277
+ )
278
+ return self
279
+
280
+
281
+ class Index(Model):
282
+ name: Identifier
283
+ columns: tuple[Identifier, ...] = ()
284
+ order_by: tuple[Sort, ...] = ()
285
+ unique: bool = False
286
+ kind: Literal["btree", "search"] = "btree"
287
+ where: Predicate | None = None
288
+ row_key: Identifier | None = None
289
+
290
+ @model_validator(mode="after")
291
+ def search_options(self) -> Self:
292
+ if not self.columns and not self.order_by:
293
+ raise ValueError("an index requires columns or expressions")
294
+ if self.kind == "search" and (
295
+ self.unique or self.where is not None or self.order_by or not self.columns
296
+ ):
297
+ raise ValueError(
298
+ "search indexes cover their full columns without uniqueness"
299
+ )
300
+ return self
301
+
302
+
303
+ class CreateTable(Model):
304
+ kind: Literal["create_table"] = "create_table"
305
+ table: Table
306
+ if_not_exists: bool = False
307
+ temporary: bool = False
308
+
309
+
310
+ class AddColumn(Model):
311
+ kind: Literal["add_column"] = "add_column"
312
+ table: Identifier
313
+ column: ColumnDefinition
314
+
315
+
316
+ class CreateIndex(Model):
317
+ kind: Literal["create_index"] = "create_index"
318
+ table: Identifier
319
+ index: Index
320
+ if_not_exists: bool = False
321
+
322
+
323
+ class DropIndex(Model):
324
+ kind: Literal["drop_index"] = "drop_index"
325
+ table: Identifier
326
+ name: Identifier
327
+
328
+
329
+ class DropTable(Model):
330
+ kind: Literal["drop_table"] = "drop_table"
331
+ table: Identifier
332
+ if_exists: bool = False
333
+
334
+
335
+ class RenameTable(Model):
336
+ kind: Literal["rename_table"] = "rename_table"
337
+ table: Identifier
338
+ name: Identifier
339
+
340
+
341
+ class RenameColumn(Model):
342
+ kind: Literal["rename_column"] = "rename_column"
343
+ table: Identifier
344
+ column: Identifier
345
+ name: Identifier
346
+
347
+
348
+ class DropColumn(Model):
349
+ kind: Literal["drop_column"] = "drop_column"
350
+ table: Identifier
351
+ column: Identifier
352
+
353
+
354
+ class CreateTrigger(Model):
355
+ kind: Literal["create_trigger"] = "create_trigger"
356
+ name: Identifier
357
+ table: Identifier
358
+ event: Literal["insert", "update", "delete"]
359
+ when: Predicate | None = None
360
+ action: Update
361
+
362
+ @model_validator(mode="after")
363
+ def statement(self) -> Self:
364
+ if self.action.table != self.table or self.action.returning:
365
+ raise ValueError("a trigger updates its own table without returning rows")
366
+ return self
367
+
368
+
369
+ class DropTrigger(Model):
370
+ kind: Literal["drop_trigger"] = "drop_trigger"
371
+ name: Identifier
372
+ table: Identifier
373
+ if_exists: bool = False
374
+
375
+
376
+ type SchemaOperation = Annotated[
377
+ CreateTable
378
+ | AddColumn
379
+ | CreateIndex
380
+ | DropIndex
381
+ | DropTable
382
+ | RenameTable
383
+ | RenameColumn
384
+ | DropColumn
385
+ | CreateTrigger
386
+ | DropTrigger,
387
+ Field(discriminator="kind"),
388
+ ]
389
+
390
+
391
+ for model in (
392
+ Binary,
393
+ Call,
394
+ RowNumber,
395
+ Case,
396
+ Subquery,
397
+ Compare,
398
+ In,
399
+ IsNull,
400
+ Contains,
401
+ All,
402
+ AnyOf,
403
+ Not,
404
+ Select,
405
+ Join,
406
+ Sort,
407
+ Update,
408
+ Index,
409
+ ):
410
+ model.model_rebuild()