-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.py
More file actions
271 lines (234 loc) · 8.21 KB
/
handlers.py
File metadata and controls
271 lines (234 loc) · 8.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
from __future__ import annotations
import argparse
import os
import typing as t
from functools import wraps
from pathlib import Path
import click
from alembic import command
from alembic.config import Config as AlembicConfig
from alembic.util.exc import CommandError
from ellar.app import App
from ellar_sql.services import EllarSQLService
RevIdType = t.Union[str, t.List[str], t.Tuple[str, ...]]
class Config(AlembicConfig):
def get_template_directory(self) -> str:
package_dir = os.path.abspath(Path(__file__).parent.parent)
return os.path.join(package_dir, "templates")
def _catch_errors(f: t.Callable) -> t.Callable: # type:ignore[type-arg]
@wraps(f)
def wrapped(*args: t.Any, **kwargs: t.Any) -> None:
try:
f(*args, **kwargs)
except (CommandError, RuntimeError) as exc:
raise click.ClickException(str(exc)) from exc
return wrapped
class CLICommandHandlers:
def __init__(self, db_service: EllarSQLService) -> None:
self.db_service = db_service
def get_config(
self,
directory: t.Optional[t.Any] = None,
x_arg: t.Optional[t.Any] = None,
opts: t.Optional[t.Any] = None,
) -> Config:
directory = (
str(directory) if directory else self.db_service.migration_options.directory
)
config = Config(os.path.join(directory, "alembic.ini"))
config.set_main_option("script_location", directory)
config.set_main_option(
"sqlalchemy.url", str(self.db_service.engine.url).replace("%", "%%")
)
if config.cmd_opts is None:
config.cmd_opts = argparse.Namespace()
for opt in opts or []:
setattr(config.cmd_opts, opt, True)
if not hasattr(config.cmd_opts, "x"):
if x_arg is not None:
config.cmd_opts.x = []
if isinstance(x_arg, list) or isinstance(x_arg, tuple):
for x in x_arg:
config.cmd_opts.x.append(x)
else:
config.cmd_opts.x.append(x_arg)
else:
config.cmd_opts.x = None
return config
@_catch_errors
def alembic_init(
self,
directory: str | None = None,
multiple: bool = False,
package: bool = False,
) -> None:
"""Creates a new migration repository"""
if directory is None:
directory = self.db_service.migration_options.directory
config = Config()
config.set_main_option("script_location", directory)
config.config_file_name = os.path.join(directory, "alembic.ini")
template_name = "single"
if multiple:
template_name = "multiple"
command.init(config, directory, template=template_name, package=package)
@_catch_errors
def revision(
self,
directory: str | None = None,
message: str | None = None,
autogenerate: bool = False,
sql: bool = False,
head: str = "head",
splice: bool = False,
branch_label: RevIdType | None = None,
version_path: str | None = None,
rev_id: str | None = None,
) -> None:
"""Create a new revision file."""
opts = ["autogenerate"] if autogenerate else None
config = self.get_config(directory, opts=opts)
command.revision(
config,
message,
autogenerate=autogenerate,
sql=sql,
head=head,
splice=splice,
branch_label=branch_label,
version_path=version_path,
rev_id=rev_id,
)
@_catch_errors
def migrate(
self,
directory: str | None = None,
message: str | None = None,
sql: bool = False,
head: str = "head",
splice: bool = False,
branch_label: RevIdType | None = None,
version_path: str | None = None,
rev_id: str | None = None,
x_arg: str | None = None,
) -> None:
"""Alias for 'revision --autogenerate'"""
config = self.get_config(
directory,
opts=["autogenerate"],
x_arg=x_arg,
)
command.revision(
config,
message,
autogenerate=True,
sql=sql,
head=head,
splice=splice,
branch_label=branch_label,
version_path=version_path,
rev_id=rev_id,
)
@_catch_errors
def edit(self, directory: str | None = None, revision: str = "current") -> None:
"""Edit current revision."""
config = self.get_config(directory)
command.edit(config, revision)
@_catch_errors
def merge(
self,
directory: str | None = None,
revisions: RevIdType = "",
message: str | None = None,
branch_label: RevIdType | None = None,
rev_id: str | None = None,
) -> None:
"""Merge two revisions together. Creates a new migration file"""
config = self.get_config(directory)
command.merge(
config, revisions, message=message, branch_label=branch_label, rev_id=rev_id
)
@_catch_errors
def upgrade(
self,
directory: str | None = None,
revision: str = "head",
sql: bool = False,
tag: str | None = None,
x_arg: str | None = None,
) -> None:
"""Upgrade to a later version"""
config = self.get_config(directory, x_arg=x_arg)
command.upgrade(config, revision, sql=sql, tag=tag)
@_catch_errors
def downgrade(
self,
directory: str | None = None,
revision: str = "-1",
sql: bool = False,
tag: str | None = None,
x_arg: str | None = None,
) -> None:
"""Revert to a previous version"""
config = self.get_config(directory, x_arg=x_arg)
if sql and revision == "-1":
revision = "head:-1"
command.downgrade(config, revision, sql=sql, tag=tag)
@_catch_errors
def show(self, directory: str | None = None, revision: str = "head") -> None:
"""Show the revision denoted by the given symbol."""
config = self.get_config(directory)
command.show(config, revision) # type:ignore[no-untyped-call]
@_catch_errors
def history(
self,
directory: str | None = None,
rev_range: t.Any = None,
verbose: bool = False,
indicate_current: bool = False,
) -> None:
"""List changeset scripts in chronological order."""
config = self.get_config(directory)
command.history(
config, rev_range, verbose=verbose, indicate_current=indicate_current
)
@_catch_errors
def heads(
self,
directory: str | None = None,
verbose: bool = False,
resolve_dependencies: bool = False,
) -> None:
"""Show current available heads in the script directory"""
config = self.get_config(directory)
command.heads( # type:ignore[no-untyped-call]
config, verbose=verbose, resolve_dependencies=resolve_dependencies
)
@_catch_errors
def branches(self, directory: str | None = None, verbose: bool = False) -> None:
"""Show current branch points"""
config = self.get_config(directory)
command.branches(config, verbose=verbose) # type:ignore[no-untyped-call]
@_catch_errors
def current(self, directory: str | None = None, verbose: bool = False) -> None:
"""Display the current revision for each database."""
config = self.get_config(directory)
command.current(config, verbose=verbose)
@_catch_errors
def stamp(
self,
app: App,
directory: str | None = None,
revision: str = "head",
sql: bool = False,
tag: t.Any = None,
) -> None:
"""'stamp' the revision table with the given revision; don't run any
migrations"""
config = self.get_config(app, directory)
command.stamp(config, revision, sql=sql, tag=tag)
@_catch_errors
def check(self, app: App, directory: str | None = None) -> None:
"""Check if there are any new operations to migrate"""
config = self.get_config(app, directory)
command.check(config)