initializedb.py
2.47 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
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
import os
import sys
import transaction
from sqlalchemy import (
engine_from_config,
select,
)
from sqlalchemy.schema import CreateSchema
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from ..models import (
init_model,
DBSession,
Base,
)
from ..models.isipkd import *
import initial_data
from tools import mkdir
ALEMBIC_CONF = """
[alembic]
script_location = ziggurat_foundations:migrations
sqlalchemy.url = {{db_url}}
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
"""
def usage(argv):
cmd = os.path.basename(argv[0])
print('usage: %s <config_uri>\n'
'(example: "%s development.ini")' % (cmd, cmd))
sys.exit(1)
def create_schema(engine, schema):
sql = select([('schema_name')]).\
select_from('information_schema.schemata').\
where("schema_name = '%s'" % schema)
q = engine.execute(sql)
if not q.fetchone():
engine.execute(CreateSchema(schema))
def create_schemas(engine):
for schema in ['efiling', 'admin', 'aset', 'eis', 'gaji', 'apbd']:
create_schema(engine, schema)
def main(argv=sys.argv):
if len(argv) != 2:
usage(argv)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
mkdir(settings['static_files'])
# Create Ziggurat tables
alembic_ini_file = 'alembic.ini'
if not os.path.exists(alembic_ini_file):
alembic_ini = ALEMBIC_CONF.replace('{{db_url}}',
settings['sqlalchemy.url'])
f = open(alembic_ini_file, 'w')
f.write(alembic_ini)
f.close()
bin_path = os.path.split(sys.executable)[0]
alembic_bin = os.path.join(bin_path, 'alembic')
command = '%s upgrade head' % alembic_bin
os.system(command)
os.remove(alembic_ini_file)
# Insert data
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
init_model()
create_schemas(engine)
Base.metadata.create_all(engine)
initial_data.insert()
transaction.commit()