-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdatabase_schema.py
More file actions
50 lines (38 loc) · 1.68 KB
/
database_schema.py
File metadata and controls
50 lines (38 loc) · 1.68 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
import re
from argparse import ArgumentParser
from typing import Any
from re import Pattern
from collections.abc import Iterable
from peewee import MySQLDatabase
from cli.base import ScriptBase
from common.model import create_all_tables
class MysqlPrintDatabase(MySQLDatabase):
"""Instead of executing the SQL statements, this DB implementation only prints them."""
_create_table_re: Pattern[str] = re.compile(r"(CREATE TABLE `\w+` \()(.*)(\))")
_column_split_re: Pattern[str] = re.compile(r",\s*")
def __init__(self) -> None:
super().__init__("")
def execute_sql(self, sql: str, params: Iterable[Any] | None = None, commit: bool | None = None) -> None:
if params:
raise Exception(f"Params are not expected to be needed to run DDL SQL, but found {params}")
if match := self._create_table_re.match(sql):
sql = "\n".join(
(
match.group(1),
",\n".join([f" {part}" for part in self._column_split_re.split(match.group(2))]),
match.group(3),
)
)
print(sql, end=";\n\n")
class DbSchemaSql(ScriptBase):
"""Outputs the SQL needed to create the database schema."""
subcommand: str = "db-schema-sql"
@classmethod
def args(cls, parser: ArgumentParser) -> None:
parser.description = "Outputs the SQL needed to create the database schema."
parser.usage = f"$ cli {cls.subcommand}"
@staticmethod
def subcmd_entry_point() -> None:
print("\n--\n-- SQL statements to create the database schema for Observability\n--\n")
database = MysqlPrintDatabase()
create_all_tables(database)