Skip to content

Commit 55a6d4b

Browse files
committed
add InspectDb and show_create_tables
1 parent c5535f1 commit 55a6d4b

File tree

5 files changed

+72
-3
lines changed

5 files changed

+72
-3
lines changed

aerich/cli.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from configparser import ConfigParser
55
from functools import wraps
66
from pathlib import Path
7+
from typing import List
78

89
import click
910
from click import Context, UsageError
@@ -12,6 +13,7 @@
1213
from tortoise.transactions import in_transaction
1314
from tortoise.utils import get_schema_sql
1415

16+
from aerich.inspectdb import InspectDb
1517
from aerich.migrate import Migrate
1618
from aerich.utils import (
1719
get_app_connection,
@@ -288,6 +290,25 @@ async def init_db(ctx: Context, safe):
288290
click.secho(f'Success generate schema for app "{app}"', fg=Color.green)
289291

290292

293+
@cli.command(help="Introspects the database tables to standard output as TortoiseORM model.")
294+
@click.option(
295+
"-t",
296+
"--table",
297+
help="Which tables to inspect.",
298+
multiple=True,
299+
required=False,
300+
)
301+
@click.pass_context
302+
@coro
303+
async def inspectdb(ctx: Context, table: List[str]):
304+
config = ctx.obj["config"]
305+
app = ctx.obj["app"]
306+
connection = get_app_connection(config, app)
307+
308+
inspect = InspectDb(connection, table)
309+
await inspect.inspect()
310+
311+
291312
def main():
292313
sys.path.insert(0, ".")
293314
cli()

aerich/inspectdb.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List, Optional
2+
3+
from ddlparse import DdlParse
4+
from tortoise import BaseDBAsyncClient
5+
from tortoise.backends.mysql.client import MySQLSchemaGenerator
6+
7+
8+
class InspectDb:
9+
def __init__(self, conn: BaseDBAsyncClient, tables: Optional[List[str]] = None):
10+
self.conn = conn
11+
self.tables = tables
12+
self.DIALECT = conn.schema_generator.DIALECT
13+
14+
async def show_create_tables(self):
15+
if self.DIALECT == MySQLSchemaGenerator.DIALECT:
16+
if not self.tables:
17+
sql_tables = f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{self.conn.database}';"
18+
ret = await self.conn.execute_query(sql_tables)
19+
self.tables = map(lambda x: x[0], ret)
20+
for table in self.tables:
21+
sql_show_create_table = f"SHOW CREATE TABLE {table}"
22+
ret = await self.conn.execute_query(sql_show_create_table)
23+
yield ret[1][0]["Create Table"]
24+
else:
25+
raise NotImplementedError("Currently only support MySQL")
26+
27+
async def inspect(self):
28+
ddl_list = self.show_create_tables()
29+
async for ddl in ddl_list:
30+
parser = DdlParse(ddl, DdlParse.DATABASE.mysql)
31+
table = parser.parse()
32+
print(table)

conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def reset_migrate():
3636
Migrate._downgrade_m2m = []
3737

3838

39-
@pytest.yield_fixture(scope="session")
39+
@pytest.fixture(scope="session")
4040
def event_loop():
4141
policy = asyncio.get_event_loop_policy()
4242
res = policy.new_event_loop()

poetry.lock

Lines changed: 17 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ click = "*"
2121
pydantic = "*"
2222
aiomysql = {version = "*", optional = true}
2323
asyncpg = {version = "*", optional = true}
24+
ddlparse = "*"
2425

2526
[tool.poetry.dev-dependencies]
2627
flake8 = "*"

0 commit comments

Comments
 (0)