Skip to content

Commit 9c3ba7e

Browse files
authored
fix: aerich init-db process is suspended (#435)
1 parent 074ba9b commit 9c3ba7e

File tree

3 files changed

+42
-4
lines changed

3 files changed

+42
-4
lines changed

CHANGELOG.md

+7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
## 0.8
44

5+
### [0.8.3]**(Unreleased)**
6+
7+
#### Fixed
8+
- fix: `aerich init-db` process is suspended. ([#435])
9+
10+
[#435]: https://github.com/tortoise/aerich/pull/435
11+
512
### [0.8.2](../../releases/tag/v0.8.2) - 2025-02-28
613

714
#### Added

aerich/cli.py

+16
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,22 @@
1919
}
2020

2121

22+
def _patch_context_to_close_tortoise_connections_when_exit() -> None:
23+
from tortoise import Tortoise, connections
24+
25+
origin_aexit = Context.__aexit__
26+
27+
async def aexit(*args, **kw) -> None:
28+
await origin_aexit(*args, **kw)
29+
if Tortoise._inited:
30+
await connections.close_all()
31+
32+
Context.__aexit__ = aexit # type:ignore[method-assign]
33+
34+
35+
_patch_context_to_close_tortoise_connections_when_exit()
36+
37+
2238
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
2339
@click.version_option(__version__, "-V", "--version")
2440
@click.option(

tests/test_sqlite_migrate.py

+19-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import contextlib
44
import os
5+
import platform
56
import shlex
67
import shutil
78
import subprocess
@@ -12,11 +13,16 @@
1213
from tests._utils import Dialect, chdir, copy_files
1314

1415

15-
def run_aerich(cmd: str) -> None:
16-
with contextlib.suppress(subprocess.TimeoutExpired):
17-
if not cmd.startswith("aerich") and not cmd.startswith("poetry"):
16+
def run_aerich(cmd: str) -> subprocess.CompletedProcess | None:
17+
if not cmd.startswith("poetry") and not cmd.startswith("python"):
18+
if not cmd.startswith("aerich"):
1819
cmd = "aerich " + cmd
19-
subprocess.run(shlex.split(cmd), timeout=2)
20+
if platform.system() == "Windows":
21+
cmd = "python -m " + cmd
22+
r = None
23+
with contextlib.suppress(subprocess.TimeoutExpired):
24+
r = subprocess.run(shlex.split(cmd), timeout=2)
25+
return r
2026

2127

2228
def run_shell(cmd: str) -> subprocess.CompletedProcess:
@@ -43,6 +49,15 @@ def prepare_sqlite_project(tmp_path: Path) -> Generator[tuple[Path, str]]:
4349
yield models_py, models_py.read_text("utf-8")
4450

4551

52+
def test_close_tortoise_connections_patch(tmp_path: Path) -> None:
53+
if not Dialect.is_sqlite():
54+
return
55+
with prepare_sqlite_project(tmp_path) as (models_py, models_text):
56+
run_aerich("aerich init -t settings.TORTOISE_ORM")
57+
r = run_aerich("aerich init-db")
58+
assert r is not None
59+
60+
4661
def test_sqlite_migrate_alter_indexed_unique(tmp_path: Path) -> None:
4762
if not Dialect.is_sqlite():
4863
return

0 commit comments

Comments
 (0)