pg-quaestor 0.1.0__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.
- pg_quaestor-0.1.0/LICENSE +177 -0
- pg_quaestor-0.1.0/PKG-INFO +102 -0
- pg_quaestor-0.1.0/README.md +70 -0
- pg_quaestor-0.1.0/pyproject.toml +55 -0
- pg_quaestor-0.1.0/setup.cfg +4 -0
- pg_quaestor-0.1.0/src/pg_quaestor/__init__.py +5 -0
- pg_quaestor-0.1.0/src/pg_quaestor/py.typed +0 -0
- pg_quaestor-0.1.0/src/pg_quaestor/registry.py +51 -0
- pg_quaestor-0.1.0/src/pg_quaestor/runner.py +131 -0
- pg_quaestor-0.1.0/src/pg_quaestor.egg-info/PKG-INFO +102 -0
- pg_quaestor-0.1.0/src/pg_quaestor.egg-info/SOURCES.txt +14 -0
- pg_quaestor-0.1.0/src/pg_quaestor.egg-info/dependency_links.txt +1 -0
- pg_quaestor-0.1.0/src/pg_quaestor.egg-info/requires.txt +7 -0
- pg_quaestor-0.1.0/src/pg_quaestor.egg-info/top_level.txt +1 -0
- pg_quaestor-0.1.0/tests/test_registry.py +47 -0
- pg_quaestor-0.1.0/tests/test_runner.py +404 -0
|
@@ -0,0 +1,177 @@
|
|
|
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 the 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 the 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 any 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
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pg-quaestor
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight PostgreSQL migration module with named migrations and dependency resolution
|
|
5
|
+
Author-email: Kristof Csillag <kristof.csillag@deai-labs.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/deai-network/pg-quaestor
|
|
8
|
+
Project-URL: Repository, https://github.com/deai-network/pg-quaestor
|
|
9
|
+
Project-URL: Issues, https://github.com/deai-network/pg-quaestor/issues
|
|
10
|
+
Keywords: postgresql,postgres,asyncpg,migration,async,asyncio,schema
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Database
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Framework :: AsyncIO
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: asyncpg>=0.29
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
29
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
30
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# pg-quaestor
|
|
34
|
+
|
|
35
|
+
*In ancient Rome, a **quaestor** was the official in charge of the treasury — here, it manages your PostgreSQL schema and data, your real treasure.*
|
|
36
|
+
|
|
37
|
+
Lightweight PostgreSQL migration module with named migrations and dependency resolution.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install pg-quaestor
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import asyncio
|
|
49
|
+
|
|
50
|
+
import asyncpg
|
|
51
|
+
from pg_quaestor import MigrationRegistry
|
|
52
|
+
|
|
53
|
+
registry = MigrationRegistry()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@registry.register("create_users")
|
|
57
|
+
async def create_users(conn):
|
|
58
|
+
await conn.execute("CREATE TABLE users (email text PRIMARY KEY)")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@registry.register("add_status", depends_on=["create_users"])
|
|
62
|
+
async def add_status(conn):
|
|
63
|
+
await conn.execute(
|
|
64
|
+
"ALTER TABLE users ADD COLUMN status text NOT NULL DEFAULT 'active'"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def main():
|
|
69
|
+
conn = await asyncpg.connect("postgresql://localhost/myapp")
|
|
70
|
+
applied = await registry.run(conn, "myapp")
|
|
71
|
+
print(f"Applied migrations: {applied}")
|
|
72
|
+
await conn.close()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
asyncio.run(main())
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## API Reference
|
|
79
|
+
|
|
80
|
+
| Symbol | Signature | Description |
|
|
81
|
+
|--------|-----------|-------------|
|
|
82
|
+
| `MigrationRegistry()` | `MigrationRegistry()` | Create a new registry. No arguments. |
|
|
83
|
+
| `.register()` | `register(name: str, depends_on: list[str] \| None = None) -> Callable` | Decorator. Registers an async migration function. |
|
|
84
|
+
| `.run()` | `async run(conn: asyncpg.Connection, prefix: str) -> list[str]` | Execute all unapplied migrations. Returns names applied in this call. |
|
|
85
|
+
| `.migrations` | `migrations -> dict[str, MigrationDefinition]` | The registry's own mapping. |
|
|
86
|
+
|
|
87
|
+
`MigrationDefinition` is not exported from `pg_quaestor`. A migration function is `async def migration(conn: asyncpg.Connection) -> None`. Pass a connection. Taking one from a pool is the caller's job.
|
|
88
|
+
|
|
89
|
+
## How It Works
|
|
90
|
+
|
|
91
|
+
- Applied migrations are tracked in `{prefix}_migrations` in the schema named by the connection's `search_path`. The library does not change `search_path`.
|
|
92
|
+
- `prefix` is a bare identifier of 1 to 52 characters (`[A-Za-z_][A-Za-z0-9_]*`). The table name is quoted, so `MyApp` stays `MyApp_migrations`.
|
|
93
|
+
- Each row stores `name` (text, primary key) and `applied_at` (timestamptz, UTC, set by the runner).
|
|
94
|
+
- Each migration runs in one transaction on that connection. The runner inserts the tracking row in the same transaction and commits. A raised exception rolls the migration's SQL and the tracking row back together. Migrations already committed in that run stay applied. The next `run` retries the failed one.
|
|
95
|
+
- The migration must not `COMMIT`, `ROLLBACK`, or close the connection. The runner does not detect a migration that does.
|
|
96
|
+
- `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `VACUUM`, `REINDEX CONCURRENTLY`, and `CREATE DATABASE` are outside this version. There is no flag to run a migration outside a transaction.
|
|
97
|
+
- `run` raises `ValueError` if the connection is already inside a transaction.
|
|
98
|
+
- A session advisory lock on `hashtextextended(prefix, 0)` is held for the run, so two runners for the same prefix take turns. Different prefixes lock independently.
|
|
99
|
+
- Dependencies are resolved with Kahn's algorithm. A missing or circular dependency raises `ValueError` and applies nothing further. Independent migrations run in alphabetical order.
|
|
100
|
+
- Several registries share one database by using different prefixes.
|
|
101
|
+
- Requires PostgreSQL 11 or newer.
|
|
102
|
+
- Progress and errors are logged to the `pg_quaestor` logger.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# pg-quaestor
|
|
2
|
+
|
|
3
|
+
*In ancient Rome, a **quaestor** was the official in charge of the treasury — here, it manages your PostgreSQL schema and data, your real treasure.*
|
|
4
|
+
|
|
5
|
+
Lightweight PostgreSQL migration module with named migrations and dependency resolution.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install pg-quaestor
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import asyncio
|
|
17
|
+
|
|
18
|
+
import asyncpg
|
|
19
|
+
from pg_quaestor import MigrationRegistry
|
|
20
|
+
|
|
21
|
+
registry = MigrationRegistry()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@registry.register("create_users")
|
|
25
|
+
async def create_users(conn):
|
|
26
|
+
await conn.execute("CREATE TABLE users (email text PRIMARY KEY)")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@registry.register("add_status", depends_on=["create_users"])
|
|
30
|
+
async def add_status(conn):
|
|
31
|
+
await conn.execute(
|
|
32
|
+
"ALTER TABLE users ADD COLUMN status text NOT NULL DEFAULT 'active'"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def main():
|
|
37
|
+
conn = await asyncpg.connect("postgresql://localhost/myapp")
|
|
38
|
+
applied = await registry.run(conn, "myapp")
|
|
39
|
+
print(f"Applied migrations: {applied}")
|
|
40
|
+
await conn.close()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
asyncio.run(main())
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## API Reference
|
|
47
|
+
|
|
48
|
+
| Symbol | Signature | Description |
|
|
49
|
+
|--------|-----------|-------------|
|
|
50
|
+
| `MigrationRegistry()` | `MigrationRegistry()` | Create a new registry. No arguments. |
|
|
51
|
+
| `.register()` | `register(name: str, depends_on: list[str] \| None = None) -> Callable` | Decorator. Registers an async migration function. |
|
|
52
|
+
| `.run()` | `async run(conn: asyncpg.Connection, prefix: str) -> list[str]` | Execute all unapplied migrations. Returns names applied in this call. |
|
|
53
|
+
| `.migrations` | `migrations -> dict[str, MigrationDefinition]` | The registry's own mapping. |
|
|
54
|
+
|
|
55
|
+
`MigrationDefinition` is not exported from `pg_quaestor`. A migration function is `async def migration(conn: asyncpg.Connection) -> None`. Pass a connection. Taking one from a pool is the caller's job.
|
|
56
|
+
|
|
57
|
+
## How It Works
|
|
58
|
+
|
|
59
|
+
- Applied migrations are tracked in `{prefix}_migrations` in the schema named by the connection's `search_path`. The library does not change `search_path`.
|
|
60
|
+
- `prefix` is a bare identifier of 1 to 52 characters (`[A-Za-z_][A-Za-z0-9_]*`). The table name is quoted, so `MyApp` stays `MyApp_migrations`.
|
|
61
|
+
- Each row stores `name` (text, primary key) and `applied_at` (timestamptz, UTC, set by the runner).
|
|
62
|
+
- Each migration runs in one transaction on that connection. The runner inserts the tracking row in the same transaction and commits. A raised exception rolls the migration's SQL and the tracking row back together. Migrations already committed in that run stay applied. The next `run` retries the failed one.
|
|
63
|
+
- The migration must not `COMMIT`, `ROLLBACK`, or close the connection. The runner does not detect a migration that does.
|
|
64
|
+
- `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `VACUUM`, `REINDEX CONCURRENTLY`, and `CREATE DATABASE` are outside this version. There is no flag to run a migration outside a transaction.
|
|
65
|
+
- `run` raises `ValueError` if the connection is already inside a transaction.
|
|
66
|
+
- A session advisory lock on `hashtextextended(prefix, 0)` is held for the run, so two runners for the same prefix take turns. Different prefixes lock independently.
|
|
67
|
+
- Dependencies are resolved with Kahn's algorithm. A missing or circular dependency raises `ValueError` and applies nothing further. Independent migrations run in alphabetical order.
|
|
68
|
+
- Several registries share one database by using different prefixes.
|
|
69
|
+
- Requires PostgreSQL 11 or newer.
|
|
70
|
+
- Progress and errors are logged to the `pg_quaestor` logger.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pg-quaestor"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Lightweight PostgreSQL migration module with named migrations and dependency resolution"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Kristof Csillag", email = "kristof.csillag@deai-labs.com" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["postgresql", "postgres", "asyncpg", "migration", "async", "asyncio", "schema"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 4 - Beta",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Database",
|
|
26
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
27
|
+
"Framework :: AsyncIO",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
dependencies = [
|
|
31
|
+
"asyncpg>=0.29",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
dev = [
|
|
36
|
+
"pytest>=8.0",
|
|
37
|
+
"pytest-asyncio>=0.23",
|
|
38
|
+
"build>=1.2",
|
|
39
|
+
"twine>=5.0",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[project.urls]
|
|
43
|
+
Homepage = "https://github.com/deai-network/pg-quaestor"
|
|
44
|
+
Repository = "https://github.com/deai-network/pg-quaestor"
|
|
45
|
+
Issues = "https://github.com/deai-network/pg-quaestor/issues"
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.packages.find]
|
|
48
|
+
where = ["src"]
|
|
49
|
+
|
|
50
|
+
[tool.setuptools.package-data]
|
|
51
|
+
pg_quaestor = ["py.typed"]
|
|
52
|
+
|
|
53
|
+
[tool.pytest.ini_options]
|
|
54
|
+
asyncio_mode = "auto"
|
|
55
|
+
testpaths = ["tests"]
|
|
File without changes
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""MigrationRegistry — collects and registers migration definitions."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Awaitable, Callable
|
|
5
|
+
|
|
6
|
+
import asyncpg
|
|
7
|
+
|
|
8
|
+
from pg_quaestor.runner import run_migrations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class MigrationDefinition:
|
|
13
|
+
"""A single migration definition."""
|
|
14
|
+
|
|
15
|
+
name: str
|
|
16
|
+
execute: Callable[[asyncpg.Connection], Awaitable[None]]
|
|
17
|
+
depends_on: list[str] = field(default_factory=list)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MigrationRegistry:
|
|
21
|
+
"""Collects migration definitions and runs them against a database."""
|
|
22
|
+
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
self._migrations: dict[str, MigrationDefinition] = {}
|
|
25
|
+
|
|
26
|
+
def register(
|
|
27
|
+
self,
|
|
28
|
+
name: str,
|
|
29
|
+
depends_on: list[str] | None = None,
|
|
30
|
+
) -> Callable:
|
|
31
|
+
"""Decorator to register a migration function."""
|
|
32
|
+
|
|
33
|
+
def decorator(fn: Callable[[asyncpg.Connection], Awaitable[None]]):
|
|
34
|
+
if name in self._migrations:
|
|
35
|
+
raise ValueError(f"Migration '{name}' is already registered")
|
|
36
|
+
self._migrations[name] = MigrationDefinition(
|
|
37
|
+
name=name,
|
|
38
|
+
execute=fn,
|
|
39
|
+
depends_on=depends_on or [],
|
|
40
|
+
)
|
|
41
|
+
return fn
|
|
42
|
+
|
|
43
|
+
return decorator
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def migrations(self) -> dict[str, MigrationDefinition]:
|
|
47
|
+
return self._migrations
|
|
48
|
+
|
|
49
|
+
async def run(self, conn: asyncpg.Connection, prefix: str) -> list[str]:
|
|
50
|
+
"""Run all unapplied migrations. Returns the names applied in this call."""
|
|
51
|
+
return await run_migrations(conn, prefix, self._migrations)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Migration runner — dependency resolution and execution."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import re
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
|
|
7
|
+
import asyncpg
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("pg_quaestor")
|
|
10
|
+
|
|
11
|
+
_PREFIX = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _quote_ident(prefix: str) -> str:
|
|
15
|
+
if _PREFIX.fullmatch(prefix) is None or len(prefix) > 52:
|
|
16
|
+
raise ValueError(
|
|
17
|
+
f"prefix must be a bare identifier of at most 52 characters, got {prefix!r}"
|
|
18
|
+
)
|
|
19
|
+
return '"' + prefix.replace('"', '""') + '_migrations"'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
# Behavior matches mongo-quaestor src/quaestor/runner.py _topological_sort; keep the two copies in step.
|
|
23
|
+
def _topological_sort(migrations: dict, unapplied: set[str]) -> list[str]:
|
|
24
|
+
"""Topological sort of unapplied migrations respecting depends_on.
|
|
25
|
+
|
|
26
|
+
Raises ValueError on circular dependencies or missing dependencies.
|
|
27
|
+
"""
|
|
28
|
+
all_known = set(migrations.keys())
|
|
29
|
+
for name, mig in migrations.items():
|
|
30
|
+
for dep in mig.depends_on:
|
|
31
|
+
if dep not in all_known:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
f"Migration '{name}' depends on '{dep}', which is not registered"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
in_degree: dict[str, int] = {name: 0 for name in unapplied}
|
|
37
|
+
dependents: dict[str, list[str]] = {name: [] for name in unapplied}
|
|
38
|
+
|
|
39
|
+
for name in unapplied:
|
|
40
|
+
for dep in migrations[name].depends_on:
|
|
41
|
+
if dep in unapplied:
|
|
42
|
+
in_degree[name] += 1
|
|
43
|
+
dependents[dep].append(name)
|
|
44
|
+
|
|
45
|
+
queue = [name for name in unapplied if in_degree[name] == 0]
|
|
46
|
+
queue.sort()
|
|
47
|
+
result = []
|
|
48
|
+
|
|
49
|
+
while queue:
|
|
50
|
+
current = queue.pop(0)
|
|
51
|
+
result.append(current)
|
|
52
|
+
for dependent in sorted(dependents[current]):
|
|
53
|
+
in_degree[dependent] -= 1
|
|
54
|
+
if in_degree[dependent] == 0:
|
|
55
|
+
queue.append(dependent)
|
|
56
|
+
queue.sort()
|
|
57
|
+
|
|
58
|
+
if len(result) != len(unapplied):
|
|
59
|
+
remaining = unapplied - set(result)
|
|
60
|
+
raise ValueError(
|
|
61
|
+
f"Circular dependency detected among migrations: {remaining}"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def run_migrations(
|
|
68
|
+
conn: asyncpg.Connection,
|
|
69
|
+
prefix: str,
|
|
70
|
+
migrations: dict,
|
|
71
|
+
) -> list[str]:
|
|
72
|
+
"""Run unapplied migrations in dependency order."""
|
|
73
|
+
table = _quote_ident(prefix)
|
|
74
|
+
if conn.is_in_transaction():
|
|
75
|
+
raise ValueError(
|
|
76
|
+
"run() requires a connection that is not already in a transaction"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
await conn.execute("SELECT pg_advisory_lock(hashtextextended($1, 0))", prefix)
|
|
80
|
+
body_error = None
|
|
81
|
+
try:
|
|
82
|
+
try:
|
|
83
|
+
await conn.execute(
|
|
84
|
+
f"CREATE TABLE IF NOT EXISTS {table} ("
|
|
85
|
+
"name text PRIMARY KEY, "
|
|
86
|
+
"applied_at timestamptz NOT NULL)"
|
|
87
|
+
)
|
|
88
|
+
rows = await conn.fetch(f"SELECT name FROM {table}")
|
|
89
|
+
applied = {row["name"] for row in rows}
|
|
90
|
+
unapplied = set(migrations.keys()) - applied
|
|
91
|
+
if not unapplied:
|
|
92
|
+
logger.info(
|
|
93
|
+
f"[{prefix}] All {len(migrations)} migrations already applied"
|
|
94
|
+
)
|
|
95
|
+
return []
|
|
96
|
+
|
|
97
|
+
ordered = _topological_sort(migrations, unapplied)
|
|
98
|
+
logger.info(f"[{prefix}] {len(ordered)} migrations to apply: {ordered}")
|
|
99
|
+
|
|
100
|
+
applied_now = []
|
|
101
|
+
for name in ordered:
|
|
102
|
+
mig = migrations[name]
|
|
103
|
+
logger.info(f"[{prefix}] Applying migration: {name}")
|
|
104
|
+
try:
|
|
105
|
+
async with conn.transaction():
|
|
106
|
+
await mig.execute(conn)
|
|
107
|
+
await conn.execute(
|
|
108
|
+
f"INSERT INTO {table} (name, applied_at) VALUES ($1, $2)",
|
|
109
|
+
name,
|
|
110
|
+
datetime.now(timezone.utc),
|
|
111
|
+
)
|
|
112
|
+
except Exception as e:
|
|
113
|
+
logger.error(f"[{prefix}] Migration '{name}' failed: {e}")
|
|
114
|
+
raise
|
|
115
|
+
applied_now.append(name)
|
|
116
|
+
logger.info(f"[{prefix}] Migration '{name}' applied successfully")
|
|
117
|
+
|
|
118
|
+
return applied_now
|
|
119
|
+
except Exception as e:
|
|
120
|
+
body_error = e
|
|
121
|
+
raise
|
|
122
|
+
finally:
|
|
123
|
+
try:
|
|
124
|
+
await conn.execute(
|
|
125
|
+
"SELECT pg_advisory_unlock(hashtextextended($1, 0))",
|
|
126
|
+
prefix,
|
|
127
|
+
)
|
|
128
|
+
except Exception as unlock_error:
|
|
129
|
+
logger.error(f"[{prefix}] Failed to release advisory lock: {unlock_error}")
|
|
130
|
+
if body_error is None:
|
|
131
|
+
raise
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pg-quaestor
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight PostgreSQL migration module with named migrations and dependency resolution
|
|
5
|
+
Author-email: Kristof Csillag <kristof.csillag@deai-labs.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/deai-network/pg-quaestor
|
|
8
|
+
Project-URL: Repository, https://github.com/deai-network/pg-quaestor
|
|
9
|
+
Project-URL: Issues, https://github.com/deai-network/pg-quaestor/issues
|
|
10
|
+
Keywords: postgresql,postgres,asyncpg,migration,async,asyncio,schema
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Database
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Framework :: AsyncIO
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: asyncpg>=0.29
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
28
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
29
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
30
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# pg-quaestor
|
|
34
|
+
|
|
35
|
+
*In ancient Rome, a **quaestor** was the official in charge of the treasury — here, it manages your PostgreSQL schema and data, your real treasure.*
|
|
36
|
+
|
|
37
|
+
Lightweight PostgreSQL migration module with named migrations and dependency resolution.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install pg-quaestor
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
import asyncio
|
|
49
|
+
|
|
50
|
+
import asyncpg
|
|
51
|
+
from pg_quaestor import MigrationRegistry
|
|
52
|
+
|
|
53
|
+
registry = MigrationRegistry()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@registry.register("create_users")
|
|
57
|
+
async def create_users(conn):
|
|
58
|
+
await conn.execute("CREATE TABLE users (email text PRIMARY KEY)")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@registry.register("add_status", depends_on=["create_users"])
|
|
62
|
+
async def add_status(conn):
|
|
63
|
+
await conn.execute(
|
|
64
|
+
"ALTER TABLE users ADD COLUMN status text NOT NULL DEFAULT 'active'"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def main():
|
|
69
|
+
conn = await asyncpg.connect("postgresql://localhost/myapp")
|
|
70
|
+
applied = await registry.run(conn, "myapp")
|
|
71
|
+
print(f"Applied migrations: {applied}")
|
|
72
|
+
await conn.close()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
asyncio.run(main())
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## API Reference
|
|
79
|
+
|
|
80
|
+
| Symbol | Signature | Description |
|
|
81
|
+
|--------|-----------|-------------|
|
|
82
|
+
| `MigrationRegistry()` | `MigrationRegistry()` | Create a new registry. No arguments. |
|
|
83
|
+
| `.register()` | `register(name: str, depends_on: list[str] \| None = None) -> Callable` | Decorator. Registers an async migration function. |
|
|
84
|
+
| `.run()` | `async run(conn: asyncpg.Connection, prefix: str) -> list[str]` | Execute all unapplied migrations. Returns names applied in this call. |
|
|
85
|
+
| `.migrations` | `migrations -> dict[str, MigrationDefinition]` | The registry's own mapping. |
|
|
86
|
+
|
|
87
|
+
`MigrationDefinition` is not exported from `pg_quaestor`. A migration function is `async def migration(conn: asyncpg.Connection) -> None`. Pass a connection. Taking one from a pool is the caller's job.
|
|
88
|
+
|
|
89
|
+
## How It Works
|
|
90
|
+
|
|
91
|
+
- Applied migrations are tracked in `{prefix}_migrations` in the schema named by the connection's `search_path`. The library does not change `search_path`.
|
|
92
|
+
- `prefix` is a bare identifier of 1 to 52 characters (`[A-Za-z_][A-Za-z0-9_]*`). The table name is quoted, so `MyApp` stays `MyApp_migrations`.
|
|
93
|
+
- Each row stores `name` (text, primary key) and `applied_at` (timestamptz, UTC, set by the runner).
|
|
94
|
+
- Each migration runs in one transaction on that connection. The runner inserts the tracking row in the same transaction and commits. A raised exception rolls the migration's SQL and the tracking row back together. Migrations already committed in that run stay applied. The next `run` retries the failed one.
|
|
95
|
+
- The migration must not `COMMIT`, `ROLLBACK`, or close the connection. The runner does not detect a migration that does.
|
|
96
|
+
- `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `VACUUM`, `REINDEX CONCURRENTLY`, and `CREATE DATABASE` are outside this version. There is no flag to run a migration outside a transaction.
|
|
97
|
+
- `run` raises `ValueError` if the connection is already inside a transaction.
|
|
98
|
+
- A session advisory lock on `hashtextextended(prefix, 0)` is held for the run, so two runners for the same prefix take turns. Different prefixes lock independently.
|
|
99
|
+
- Dependencies are resolved with Kahn's algorithm. A missing or circular dependency raises `ValueError` and applies nothing further. Independent migrations run in alphabetical order.
|
|
100
|
+
- Several registries share one database by using different prefixes.
|
|
101
|
+
- Requires PostgreSQL 11 or newer.
|
|
102
|
+
- Progress and errors are logged to the `pg_quaestor` logger.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/pg_quaestor/__init__.py
|
|
5
|
+
src/pg_quaestor/py.typed
|
|
6
|
+
src/pg_quaestor/registry.py
|
|
7
|
+
src/pg_quaestor/runner.py
|
|
8
|
+
src/pg_quaestor.egg-info/PKG-INFO
|
|
9
|
+
src/pg_quaestor.egg-info/SOURCES.txt
|
|
10
|
+
src/pg_quaestor.egg-info/dependency_links.txt
|
|
11
|
+
src/pg_quaestor.egg-info/requires.txt
|
|
12
|
+
src/pg_quaestor.egg-info/top_level.txt
|
|
13
|
+
tests/test_registry.py
|
|
14
|
+
tests/test_runner.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pg_quaestor
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Tests for MigrationRegistry."""
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from pg_quaestor import MigrationRegistry
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_register_migration():
|
|
9
|
+
reg = MigrationRegistry()
|
|
10
|
+
|
|
11
|
+
async def first(conn):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
registered = reg.register("first")(first)
|
|
15
|
+
|
|
16
|
+
assert registered is first
|
|
17
|
+
assert "first" in reg.migrations
|
|
18
|
+
assert reg.migrations["first"].name == "first"
|
|
19
|
+
assert reg.migrations["first"].depends_on == []
|
|
20
|
+
assert reg.migrations["first"].execute is first
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_register_with_dependencies():
|
|
24
|
+
reg = MigrationRegistry()
|
|
25
|
+
|
|
26
|
+
@reg.register("base")
|
|
27
|
+
async def base(conn):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
@reg.register("dependent", depends_on=["base"])
|
|
31
|
+
async def dependent(conn):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
assert reg.migrations["dependent"].depends_on == ["base"]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_duplicate_name_raises():
|
|
38
|
+
reg = MigrationRegistry()
|
|
39
|
+
|
|
40
|
+
@reg.register("dup")
|
|
41
|
+
async def first(conn):
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
with pytest.raises(ValueError, match="already registered"):
|
|
45
|
+
@reg.register("dup")
|
|
46
|
+
async def second(conn):
|
|
47
|
+
pass
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""Tests for the migration runner."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from pg_quaestor import MigrationRegistry
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
async def test_run_applies_migrations(pg):
|
|
12
|
+
reg = MigrationRegistry()
|
|
13
|
+
log = []
|
|
14
|
+
|
|
15
|
+
@reg.register("m1")
|
|
16
|
+
async def m1(conn):
|
|
17
|
+
log.append("m1")
|
|
18
|
+
await conn.execute("CREATE TABLE from_m1 (id int)")
|
|
19
|
+
|
|
20
|
+
@reg.register("m2")
|
|
21
|
+
async def m2(conn):
|
|
22
|
+
log.append("m2")
|
|
23
|
+
await conn.execute("CREATE TABLE from_m2 (id int)")
|
|
24
|
+
|
|
25
|
+
applied = await reg.run(pg.conn, "test")
|
|
26
|
+
assert applied == ["m1", "m2"]
|
|
27
|
+
assert log == ["m1", "m2"]
|
|
28
|
+
|
|
29
|
+
rows = await pg.conn.fetch('SELECT name, applied_at FROM "test_migrations" ORDER BY name')
|
|
30
|
+
assert [row["name"] for row in rows] == ["m1", "m2"]
|
|
31
|
+
assert all(row["applied_at"].tzinfo is not None for row in rows)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def test_run_skips_already_applied(pg):
|
|
35
|
+
reg = MigrationRegistry()
|
|
36
|
+
run_count = {"m1": 0}
|
|
37
|
+
|
|
38
|
+
@reg.register("m1")
|
|
39
|
+
async def m1(conn):
|
|
40
|
+
run_count["m1"] += 1
|
|
41
|
+
|
|
42
|
+
await reg.run(pg.conn, "test")
|
|
43
|
+
applied = await reg.run(pg.conn, "test")
|
|
44
|
+
assert applied == []
|
|
45
|
+
assert run_count["m1"] == 1
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def test_run_respects_dependencies(pg):
|
|
49
|
+
reg = MigrationRegistry()
|
|
50
|
+
log = []
|
|
51
|
+
|
|
52
|
+
@reg.register("base")
|
|
53
|
+
async def base(conn):
|
|
54
|
+
log.append("base")
|
|
55
|
+
|
|
56
|
+
@reg.register("child", depends_on=["base"])
|
|
57
|
+
async def child(conn):
|
|
58
|
+
log.append("child")
|
|
59
|
+
|
|
60
|
+
@reg.register("grandchild", depends_on=["child"])
|
|
61
|
+
async def grandchild(conn):
|
|
62
|
+
log.append("grandchild")
|
|
63
|
+
|
|
64
|
+
applied = await reg.run(pg.conn, "test")
|
|
65
|
+
assert log == ["base", "child", "grandchild"]
|
|
66
|
+
assert applied == ["base", "child", "grandchild"]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def test_run_partial_dependencies_already_applied(pg):
|
|
70
|
+
reg = MigrationRegistry()
|
|
71
|
+
log = []
|
|
72
|
+
|
|
73
|
+
@reg.register("base")
|
|
74
|
+
async def base(conn):
|
|
75
|
+
log.append("base")
|
|
76
|
+
|
|
77
|
+
@reg.register("child", depends_on=["base"])
|
|
78
|
+
async def child(conn):
|
|
79
|
+
log.append("child")
|
|
80
|
+
|
|
81
|
+
await pg.conn.execute(
|
|
82
|
+
"CREATE TABLE test_migrations ("
|
|
83
|
+
"name text PRIMARY KEY, applied_at timestamptz NOT NULL)"
|
|
84
|
+
)
|
|
85
|
+
await pg.conn.execute(
|
|
86
|
+
"INSERT INTO test_migrations (name, applied_at) VALUES ($1, $2)",
|
|
87
|
+
"base",
|
|
88
|
+
datetime.now(timezone.utc),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
applied = await reg.run(pg.conn, "test")
|
|
92
|
+
assert applied == ["child"]
|
|
93
|
+
assert log == ["child"]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
async def test_run_circular_dependency_raises(pg):
|
|
97
|
+
reg = MigrationRegistry()
|
|
98
|
+
|
|
99
|
+
@reg.register("a", depends_on=["b"])
|
|
100
|
+
async def a(conn):
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
@reg.register("b", depends_on=["a"])
|
|
104
|
+
async def b(conn):
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
with pytest.raises(ValueError, match="Circular dependency"):
|
|
108
|
+
await reg.run(pg.conn, "test")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def test_run_missing_dependency_raises(pg):
|
|
112
|
+
reg = MigrationRegistry()
|
|
113
|
+
|
|
114
|
+
@reg.register("orphan", depends_on=["nonexistent"])
|
|
115
|
+
async def orphan(conn):
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
with pytest.raises(ValueError, match="not registered"):
|
|
119
|
+
await reg.run(pg.conn, "test")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def test_run_failed_migration_rolls_back(pg):
|
|
123
|
+
reg = MigrationRegistry()
|
|
124
|
+
|
|
125
|
+
@reg.register("good")
|
|
126
|
+
async def good(conn):
|
|
127
|
+
await conn.execute("CREATE TABLE good_t (id int)")
|
|
128
|
+
await conn.execute("INSERT INTO good_t (id) VALUES (1)")
|
|
129
|
+
|
|
130
|
+
@reg.register("bad", depends_on=["good"])
|
|
131
|
+
async def bad(conn):
|
|
132
|
+
await conn.execute("INSERT INTO good_t (id) VALUES (2)")
|
|
133
|
+
await conn.execute("CREATE TABLE bad_t (id int)")
|
|
134
|
+
raise RuntimeError("intentional failure")
|
|
135
|
+
|
|
136
|
+
with pytest.raises(RuntimeError, match="intentional failure"):
|
|
137
|
+
await reg.run(pg.conn, "test")
|
|
138
|
+
|
|
139
|
+
tables = {
|
|
140
|
+
row["tablename"]
|
|
141
|
+
for row in await pg.conn.fetch(
|
|
142
|
+
"SELECT tablename FROM pg_tables WHERE schemaname = $1",
|
|
143
|
+
pg.schema,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
assert "good_t" in tables
|
|
147
|
+
assert "bad_t" not in tables
|
|
148
|
+
ids = [row["id"] for row in await pg.conn.fetch("SELECT id FROM good_t ORDER BY id")]
|
|
149
|
+
assert ids == [1]
|
|
150
|
+
names = {row["name"] for row in await pg.conn.fetch('SELECT name FROM "test_migrations"')}
|
|
151
|
+
assert names == {"good"}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def test_run_retry_after_failure(pg):
|
|
155
|
+
reg = MigrationRegistry()
|
|
156
|
+
attempt = {"count": 0}
|
|
157
|
+
|
|
158
|
+
@reg.register("flaky")
|
|
159
|
+
async def flaky(conn):
|
|
160
|
+
attempt["count"] += 1
|
|
161
|
+
if attempt["count"] == 1:
|
|
162
|
+
raise RuntimeError("first attempt fails")
|
|
163
|
+
|
|
164
|
+
with pytest.raises(RuntimeError, match="first attempt fails"):
|
|
165
|
+
await reg.run(pg.conn, "test")
|
|
166
|
+
|
|
167
|
+
applied = await reg.run(pg.conn, "test")
|
|
168
|
+
assert applied == ["flaky"]
|
|
169
|
+
assert attempt["count"] == 2
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
async def test_run_with_prefix_isolation(pg):
|
|
173
|
+
reg1 = MigrationRegistry()
|
|
174
|
+
reg2 = MigrationRegistry()
|
|
175
|
+
|
|
176
|
+
@reg1.register("m1")
|
|
177
|
+
async def m1(conn):
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
@reg2.register("m1")
|
|
181
|
+
async def m1_other(conn):
|
|
182
|
+
pass
|
|
183
|
+
|
|
184
|
+
await reg1.run(pg.conn, "alpha")
|
|
185
|
+
await reg2.run(pg.conn, "beta")
|
|
186
|
+
|
|
187
|
+
alpha = await pg.conn.fetch('SELECT name FROM "alpha_migrations"')
|
|
188
|
+
beta = await pg.conn.fetch('SELECT name FROM "beta_migrations"')
|
|
189
|
+
assert len(alpha) == 1
|
|
190
|
+
assert len(beta) == 1
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
async def test_run_parallel_independent_migrations(pg):
|
|
194
|
+
reg = MigrationRegistry()
|
|
195
|
+
log = []
|
|
196
|
+
|
|
197
|
+
@reg.register("charlie")
|
|
198
|
+
async def charlie(conn):
|
|
199
|
+
log.append("charlie")
|
|
200
|
+
|
|
201
|
+
@reg.register("alpha")
|
|
202
|
+
async def alpha(conn):
|
|
203
|
+
log.append("alpha")
|
|
204
|
+
|
|
205
|
+
@reg.register("bravo")
|
|
206
|
+
async def bravo(conn):
|
|
207
|
+
log.append("bravo")
|
|
208
|
+
|
|
209
|
+
await reg.run(pg.conn, "test")
|
|
210
|
+
assert log == ["alpha", "bravo", "charlie"]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def test_run_diamond_dependency(pg):
|
|
214
|
+
reg = MigrationRegistry()
|
|
215
|
+
log = []
|
|
216
|
+
|
|
217
|
+
@reg.register("root")
|
|
218
|
+
async def root(conn):
|
|
219
|
+
log.append("root")
|
|
220
|
+
|
|
221
|
+
@reg.register("left", depends_on=["root"])
|
|
222
|
+
async def left(conn):
|
|
223
|
+
log.append("left")
|
|
224
|
+
|
|
225
|
+
@reg.register("right", depends_on=["root"])
|
|
226
|
+
async def right(conn):
|
|
227
|
+
log.append("right")
|
|
228
|
+
|
|
229
|
+
@reg.register("bottom", depends_on=["left", "right"])
|
|
230
|
+
async def bottom(conn):
|
|
231
|
+
log.append("bottom")
|
|
232
|
+
|
|
233
|
+
await reg.run(pg.conn, "test")
|
|
234
|
+
assert log == ["root", "left", "right", "bottom"]
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
async def test_run_empty_registry_creates_table(pg):
|
|
238
|
+
reg = MigrationRegistry()
|
|
239
|
+
assert await reg.run(pg.conn, "test") == []
|
|
240
|
+
rows = await pg.conn.fetch(
|
|
241
|
+
"SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename = $2",
|
|
242
|
+
pg.schema,
|
|
243
|
+
"test_migrations",
|
|
244
|
+
)
|
|
245
|
+
assert len(rows) == 1
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
async def test_run_migration_name_is_data(pg):
|
|
249
|
+
reg = MigrationRegistry()
|
|
250
|
+
name = 'say "hi"'
|
|
251
|
+
|
|
252
|
+
@reg.register(name)
|
|
253
|
+
async def say(conn):
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
assert await reg.run(pg.conn, "test") == [name]
|
|
257
|
+
rows = await pg.conn.fetch('SELECT name FROM "test_migrations"')
|
|
258
|
+
assert [row["name"] for row in rows] == [name]
|
|
259
|
+
assert await reg.run(pg.conn, "test") == []
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
async def test_run_prefix_case_is_preserved(pg):
|
|
263
|
+
reg = MigrationRegistry()
|
|
264
|
+
|
|
265
|
+
@reg.register("m")
|
|
266
|
+
async def m(conn):
|
|
267
|
+
pass
|
|
268
|
+
|
|
269
|
+
assert await reg.run(pg.conn, "MyApp") == ["m"]
|
|
270
|
+
rows = await pg.conn.fetch(
|
|
271
|
+
"SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename = $2",
|
|
272
|
+
pg.schema,
|
|
273
|
+
"MyApp_migrations",
|
|
274
|
+
)
|
|
275
|
+
assert len(rows) == 1
|
|
276
|
+
stored = await pg.conn.fetch('SELECT name FROM "MyApp_migrations"')
|
|
277
|
+
assert [row["name"] for row in stored] == ["m"]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@pytest.mark.parametrize(
|
|
281
|
+
"prefix",
|
|
282
|
+
["", "a-b", "1abc", "has space", "a" * 53, '"users"'],
|
|
283
|
+
)
|
|
284
|
+
async def test_run_rejects_bad_prefix(pg, prefix):
|
|
285
|
+
reg = MigrationRegistry()
|
|
286
|
+
|
|
287
|
+
@reg.register("m")
|
|
288
|
+
async def m(conn):
|
|
289
|
+
pass
|
|
290
|
+
|
|
291
|
+
with pytest.raises(ValueError, match="bare identifier"):
|
|
292
|
+
await reg.run(pg.conn, prefix)
|
|
293
|
+
|
|
294
|
+
rows = await pg.conn.fetch(
|
|
295
|
+
"SELECT tablename FROM pg_tables WHERE schemaname = $1",
|
|
296
|
+
pg.schema,
|
|
297
|
+
)
|
|
298
|
+
assert rows == []
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
async def test_run_prefix_length_bounds(pg):
|
|
302
|
+
reg = MigrationRegistry()
|
|
303
|
+
|
|
304
|
+
@reg.register("m")
|
|
305
|
+
async def m(conn):
|
|
306
|
+
pass
|
|
307
|
+
|
|
308
|
+
short = "a"
|
|
309
|
+
long = "a" * 52
|
|
310
|
+
assert await reg.run(pg.conn, short) == ["m"]
|
|
311
|
+
assert await reg.run(pg.conn, long) == ["m"]
|
|
312
|
+
rows = await pg.conn.fetch(
|
|
313
|
+
"SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename = ANY($2)",
|
|
314
|
+
pg.schema,
|
|
315
|
+
[short + "_migrations", long + "_migrations"],
|
|
316
|
+
)
|
|
317
|
+
assert {row["tablename"] for row in rows} == {
|
|
318
|
+
short + "_migrations",
|
|
319
|
+
long + "_migrations",
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
async def test_run_rejects_open_transaction(pg):
|
|
324
|
+
reg = MigrationRegistry()
|
|
325
|
+
|
|
326
|
+
@reg.register("m")
|
|
327
|
+
async def m(conn):
|
|
328
|
+
pass
|
|
329
|
+
|
|
330
|
+
async with pg.conn.transaction():
|
|
331
|
+
with pytest.raises(ValueError, match="not already in a transaction"):
|
|
332
|
+
await reg.run(pg.conn, "myapp")
|
|
333
|
+
|
|
334
|
+
other = await pg.connect()
|
|
335
|
+
applied = await asyncio.wait_for(reg.run(other, "myapp"), timeout=2)
|
|
336
|
+
assert applied == ["m"]
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
async def test_run_advisory_lock_serializes(pg):
|
|
340
|
+
reg = MigrationRegistry()
|
|
341
|
+
started = asyncio.Event()
|
|
342
|
+
release = asyncio.Event()
|
|
343
|
+
calls = {"n": 0}
|
|
344
|
+
|
|
345
|
+
@reg.register("m")
|
|
346
|
+
async def m(conn):
|
|
347
|
+
calls["n"] += 1
|
|
348
|
+
started.set()
|
|
349
|
+
await release.wait()
|
|
350
|
+
|
|
351
|
+
other = await pg.connect()
|
|
352
|
+
first = asyncio.create_task(reg.run(pg.conn, "myapp"))
|
|
353
|
+
await started.wait()
|
|
354
|
+
second = asyncio.create_task(reg.run(other, "myapp"))
|
|
355
|
+
done, pending = await asyncio.wait({second}, timeout=0.5)
|
|
356
|
+
assert second in pending
|
|
357
|
+
assert calls["n"] == 1
|
|
358
|
+
release.set()
|
|
359
|
+
assert await first == ["m"]
|
|
360
|
+
assert await second == []
|
|
361
|
+
assert calls["n"] == 1
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
async def test_run_releases_lock_after_failure(pg):
|
|
365
|
+
reg = MigrationRegistry()
|
|
366
|
+
attempt = {"n": 0}
|
|
367
|
+
|
|
368
|
+
@reg.register("flaky")
|
|
369
|
+
async def flaky(conn):
|
|
370
|
+
attempt["n"] += 1
|
|
371
|
+
if attempt["n"] == 1:
|
|
372
|
+
raise RuntimeError("boom")
|
|
373
|
+
|
|
374
|
+
with pytest.raises(RuntimeError, match="boom"):
|
|
375
|
+
await reg.run(pg.conn, "test")
|
|
376
|
+
|
|
377
|
+
other = await pg.connect()
|
|
378
|
+
applied = await asyncio.wait_for(reg.run(other, "test"), timeout=2)
|
|
379
|
+
assert applied == ["flaky"]
|
|
380
|
+
assert attempt["n"] == 2
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
async def test_run_lock_is_per_prefix(pg):
|
|
384
|
+
reg_a = MigrationRegistry()
|
|
385
|
+
reg_b = MigrationRegistry()
|
|
386
|
+
started = asyncio.Event()
|
|
387
|
+
release = asyncio.Event()
|
|
388
|
+
|
|
389
|
+
@reg_a.register("held")
|
|
390
|
+
async def held(conn):
|
|
391
|
+
started.set()
|
|
392
|
+
await release.wait()
|
|
393
|
+
|
|
394
|
+
@reg_b.register("other")
|
|
395
|
+
async def other(conn):
|
|
396
|
+
pass
|
|
397
|
+
|
|
398
|
+
conn_b = await pg.connect()
|
|
399
|
+
task_a = asyncio.create_task(reg_a.run(pg.conn, "alpha"))
|
|
400
|
+
await started.wait()
|
|
401
|
+
applied_b = await asyncio.wait_for(reg_b.run(conn_b, "beta"), timeout=2)
|
|
402
|
+
assert applied_b == ["other"]
|
|
403
|
+
release.set()
|
|
404
|
+
assert await task_a == ["held"]
|