-
Notifications
You must be signed in to change notification settings - Fork 7
/
createdatabase.py
executable file
·205 lines (176 loc) · 5.69 KB
/
createdatabase.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python3
"""
Create or drop databases for django project
Usage:
$ ./createdatabase.py # Just create a new database
$ ./createdatbase.py -d # Drop db if exists and then create a new one
$ ./createdatabase.py -m # Run `./manage.py migrate` after create
$ ./createdatabase.py -dm # drop, create, migrate
"""
import contextlib
import os
import sys
from pathlib import Path
SETTINGS_ENV = "DJANGO_SETTINGS_MODULE"
SQL = "create database {} CHARACTER SET {}"
def secho(*args, **kw):
with contextlib.suppress(ImportError):
from click import secho as print
print(" ".join(str(i) for i in args), **kw)
def configure_settings():
p = Path("manage.py")
MAX_NESTED = 5 # make `mg` work at sub directory
for _ in range(MAX_NESTED):
if p.exists():
break
p = Path(f"../{p}")
else:
raise Exception('`manage.py` not found at "." or ".."')
s = p.read_text()
conf_line = [i for i in s.split("\n") if SETTINGS_ENV in i][0]
exec(conf_line.strip())
return p
def get_db(alias="default", all_=False):
from django.conf import settings
dbs = settings.DATABASES
if all_:
return dbs.keys(), dbs.values()
try:
return dbs[alias]
except KeyError:
raise Exception(f"database NAME ``{alias}`` not found at settings.") from None
def getconf(dbconf):
config = {
"host": dbconf.get("HOST"),
"user": dbconf.get("USER"),
"passwd": dbconf.get("PASSWORD"),
"port": dbconf.get("PORT"),
"charset": "utf8",
}
config = {k: v for k, v in config.items() if v is not None}
db_name = dbconf.get("NAME")
engine = dbconf.get("ENGINE")
return config, db_name, engine
def creat_db(config, db_name, engine, drop=False):
if "mysql" in engine:
mysql(config, db_name, drop)
elif "postgres" in engine:
postgres(config, db_name, drop)
elif "sqlite" in engine:
sqlite(config, db_name, drop)
else:
raise Exception(f"Not handle database engine ``{engine}`` yet..")
def mysql(config, db_name, drop=False):
import MySQLdb
try:
conn = MySQLdb.connect(**config)
cur = conn.cursor()
if drop:
cur.execute(f"drop database {db_name}")
secho(f"success to execute `drop database {db_name};`")
command = SQL.format(db_name, config["charset"])
cur.execute(command)
secho(f"success to execute `{command};`")
conn.commit()
cur.close()
conn.close()
except Exception as e:
secho(f"SQL Error: {e}")
def prompt_mysql_create_db(name, user: str):
sql = (
f"CREATE DATABASE IF NOT EXISTS {name}"
" DEFAULT CHARACTER SET utf8"
" DEFAULT COLLATE utf8_chinese_ci;"
)
secho(f"Run the following line inside mysql client:\n\n{sql}")
connect_db = f"mysql -u{user} -p"
secho("\n-->", connect_db)
os.system(connect_db)
def postgres(config, db_name, drop=False):
who = "sudo -u postgres psql -U postgres -d postgres -c "
option = "encoding='utf-8'"
if drop:
cmd = f'{who}"drop database {db_name};"'
secho("\n-->", cmd, "...")
os.system(f"cd /tmp && {cmd}")
cmd = f'{who}"create database {db_name} {option};"'
secho("\n-->", cmd, "...")
os.system(f"cd /tmp && {cmd}")
def sqlite(config, db_name, drop=False):
if drop:
try:
os.remove(db_name)
except FileNotFoundError:
secho(f"sqlite3 file `{db_name}` not exist!")
else:
secho(f"{db_name} was deleted.")
else:
secho("sqlite3 no need to create db.")
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
"-d",
"--delete",
action="store_true",
help="whether to delete the database if exists",
)
parser.add_argument(
"-m",
"--migrate",
action="store_true",
help="whether to run the migrate command",
)
parser.add_argument(
"--all", action="store_true", help="whether to handle all databases"
)
parser.add_argument(
"-a",
"--alias",
default="default",
help="the alias of the database(default:default)",
)
parser.add_argument(
"--name",
default="auto",
help="the db name to be created(default:auto detect from manage.py)",
)
parser.add_argument(
"--user",
default="root",
help="the engine client user name(default:root)",
)
parser.add_argument(
"--engine",
"--client",
dest="engine",
default="postgres",
choices=("mysql", "postgres", "sqlite"),
help="What's the database engine(default:postgres)",
)
args, unknown = parser.parse_known_args()
if args.name != "auto":
if args.engine == "mysql":
return prompt_mysql_create_db(args.name, args.user)
aliases = ["default"]
dbs = [{"NAME": args.name, "ENGINE": args.engine}]
else:
manage_path = configure_settings()
sys.path.insert(0, str(manage_path.parent))
secho("Reading DATABASES configure from django settings...")
if args.all:
aliases, dbs = get_db(all_=True)
else:
aliases, dbs = [args.alias], [get_db(args.alias)]
for db in dbs:
creat_db(*getconf(db), drop=args.delete)
if args.migrate:
cmd = f"python {manage_path} makemigrations"
secho("\n-->", cmd, "...")
os.system(cmd)
for alias in aliases:
cmd = f"python {manage_path} migrate --database={alias}"
secho("\n-->", cmd, "...")
os.system(cmd)
if __name__ == "__main__":
main()