-
Notifications
You must be signed in to change notification settings - Fork 1
/
dbsetup.py
54 lines (44 loc) · 1.63 KB
/
dbsetup.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
import pymysql.cursors
from music_logger import app
from os.path import abspath
from sys import argv
groupsTableFile = abspath('./test/seeds/music_logger_groups.sql')
tracksTableFile = abspath('./test/seeds/music_logger_tracks.sql')
groupsDataFile = abspath('./test/data/groups_data.sql')
tracksDataFile = abspath('./test/data/tracks_data.sql')
connection = pymysql.connect(host=app.db_host,
user=app.db_user,
password=app.db_password,
db=app.db_name,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
def create(args):
if any(x in args for x in ['-h', '--help']):
print("usage: dbsetup")
try:
if any(x in args for x in ['-E', '--Erase']):
with connection as cur:
cur.execute('DROP DATABASE IF EXISTS test;')
cur.execute('CREATE DATABASE test;')
connection.commit()
read_sql_file(connection, groupsTableFile)
read_sql_file(connection, tracksTableFile)
read_sql_file(connection, groupsDataFile)
finally:
connection.close()
if any(x in args for x in ['-s', '--seed']):
seed_tracks()
def seed_tracks():
try:
read_sql_file(connection, tracksDataFile)
finally:
connection.close()
def read_sql_file(connect, file):
with connect.cursor(), as cursor:
with open(file) as f:
for x in f.read().strip().split(';'):
x.strip()
if x != '':
cursor.execute(x)
connection.commit()
create(argv)