-
Notifications
You must be signed in to change notification settings - Fork 0
/
entrypoint.py
184 lines (140 loc) · 4.37 KB
/
entrypoint.py
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
#!/usr/bin/env python3
import argparse
import os
import shlex
import subprocess
import logging
from enum import Enum
from operator import itemgetter
from urllib.parse import urlparse
class ClickhouseMigrationException(Exception):
pass
class MetadataError(ClickhouseMigrationException):
pass
class OperationError(ClickhouseMigrationException):
pass
def get_logger(logger_name):
FORMATTER = logging.Formatter(
"%(asctime)s %(name)s %(funcName)s %(lineno)d %(levelname)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z",
)
def get_sys_handler():
syslog = logging.StreamHandler()
syslog.setFormatter(FORMATTER)
return syslog
logger = logging.getLogger(logger_name)
logger.addHandler(get_sys_handler())
return logger
logger = get_logger(__file__)
SCHEMA_MIGRATIONS_DDL = """
CREATE TABLE IF NOT EXISTS schema_migrations ON CLUSTER '{cluster}'
(
version String,
ts DateTime DEFAULT now(),
applied UInt8 DEFAULT 1
)
ENGINE = ReplicatedReplacingMergeTree('/clickhouse/{cluster}/tables/{database}/{table}', '{replica}', ts)
PRIMARY KEY version
ORDER BY version;
"""
class Database(Enum):
TEST = "test"
TEST_DEVELOPMENT = "test_development"
TEST_TEST = "test_test"
def __str__(self):
return self.value
DATABASE_CONFIG = {
Database.TEST: {
"database_name": "test",
"migrations_dir": "./databases/test/migrations",
"schema_file": "./databases/test/schema.sql",
},
Database.TEST_DEVELOPMENT: {
"database_name": "test_development",
"migrations_dir": "./databases/test/migrations",
"schema_file": "./databases/test/schema.sql",
},
Database.TEST_TEST: {
"database_name": "test_test",
"migrations_dir": "./databases/test/migrations",
"schema_file": "./databases/test/schema.sql",
},
}
def db_url():
return os.environ["DATABASE_URL"]
def parse_db_url(url):
parsed = urlparse(url)
return {
"hostname": parsed.hostname,
"port": parsed.port,
"username": parsed.username,
"password": parsed.password,
}
def run(cmd):
return subprocess.run(shlex.split(cmd), capture_output=True)
def compile_clickhouse_query_cmd(db, query):
parsed_db_url = parse_db_url(db_url())
hostname, port, username, password = itemgetter(
"hostname", "port", "username", "password"
)(parsed_db_url)
return f'clickhouse-client -h {hostname} --port {port} -u {username} --password {password} -d {db} --query="{query}"'
def compile_dbmate_operation_cmd(db, operation, parameters):
database_name, migrations_dir, schema_file = itemgetter(
"database_name", "migrations_dir", "schema_file"
)(DATABASE_CONFIG[db])
database_url = f"{db_url()}/{database_name}"
return f"dbmate --url {database_url} --migrations-dir {migrations_dir} --schema-file {schema_file} {operation} {parameters}"
def create_metadata_table(db):
cmd = compile_clickhouse_query_cmd(db, SCHEMA_MIGRATIONS_DDL)
res = run(cmd)
if res.stderr:
logger.error(res.stderr)
raise MetadataError
logger.critical(res.stdout)
return
def run_dbmate_operation(db, operation, parameters):
cmd = compile_dbmate_operation_cmd(db, operation, parameters)
res = run(cmd)
if res.stderr:
logger.error(res.stderr)
raise OperationError
logger.critical(res.stdout)
return
class DbmateOperation(Enum):
HELP = "help"
NEW = "new"
STATUS = "status"
MIGRATE = "migrate"
ROLLBACK = "rollback"
def __str__(self):
return self.value
def main():
parser = argparse.ArgumentParser(description="Clickhouse Migration Tool")
parser.add_argument(
"-db",
"--database",
required=True,
type=Database,
choices=list(Database),
help="target database",
)
parser.add_argument(
"-p",
"--parameters",
help="dbmate operation additional paramters",
)
parser.add_argument(
"operation",
type=DbmateOperation,
choices=list(DbmateOperation),
help="dbmate operation",
)
args = parser.parse_args()
database = args.database
operation = args.operation
parameters = args.parameters
create_metadata_table(database)
run_dbmate_operation(database, operation, parameters)
return
if __name__ == "__main__":
main()