1
|
|
|
# -*- coding: utf-8 -*- |
2
|
|
|
import transaction |
3
|
|
|
from pyramid.paster import ( |
4
|
|
|
get_appsettings, |
5
|
|
|
setup_logging, |
6
|
|
|
) |
7
|
|
|
|
8
|
|
|
from tracim import CFG |
9
|
|
|
from tracim.fixtures import FixturesLoader |
10
|
|
|
from tracim.fixtures.users_and_groups import Base as BaseFixture |
11
|
|
|
from sqlalchemy.exc import IntegrityError |
12
|
|
|
from tracim.command import AppContextCommand |
13
|
|
|
from tracim.models.meta import DeclarativeBase |
14
|
|
|
from tracim.models import ( |
15
|
|
|
get_engine, |
16
|
|
|
get_session_factory, |
17
|
|
|
get_tm_session, |
18
|
|
|
) |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
class InitializeDBCommand(AppContextCommand): |
22
|
|
|
auto_setup_context = False |
23
|
|
|
|
24
|
|
|
def get_description(self): |
25
|
|
|
return "Initialize DB" |
26
|
|
|
|
27
|
|
|
def get_parser(self, prog_name): |
28
|
|
|
parser = super().get_parser(prog_name) |
29
|
|
|
return parser |
30
|
|
|
|
31
|
|
|
def take_action(self, parsed_args): |
32
|
|
|
super(InitializeDBCommand, self).take_action(parsed_args) |
33
|
|
|
config_uri = parsed_args.config_file |
34
|
|
|
setup_logging(config_uri) |
35
|
|
|
settings = get_appsettings(config_uri) |
36
|
|
|
self._create_schema(settings) |
37
|
|
|
self._populate_database(settings) |
38
|
|
|
|
39
|
|
|
@classmethod |
40
|
|
|
def _create_schema(cls, settings): |
41
|
|
|
print("- Create Schemas of databases -") |
42
|
|
|
engine = get_engine(settings) |
43
|
|
|
DeclarativeBase.metadata.create_all(engine) |
44
|
|
|
|
45
|
|
|
@classmethod |
46
|
|
|
def _populate_database(cls, settings): |
47
|
|
|
engine = get_engine(settings) |
48
|
|
|
session_factory = get_session_factory(engine) |
49
|
|
|
app_config = CFG(settings) |
50
|
|
|
print("- Populate database with default data -") |
51
|
|
|
with transaction.manager: |
52
|
|
|
dbsession = get_tm_session(session_factory, transaction.manager) |
53
|
|
|
try: |
54
|
|
|
fixtures_loader = FixturesLoader(dbsession, app_config) |
55
|
|
|
fixtures_loader.loads([BaseFixture]) |
56
|
|
|
transaction.commit() |
57
|
|
|
print("Database initialized.") |
58
|
|
|
except IntegrityError: |
59
|
|
|
print('Warning, there was a problem when adding default data' |
60
|
|
|
', it may have already been added:') |
61
|
|
|
import traceback |
62
|
|
|
print(traceback.format_exc()) |
63
|
|
|
transaction.abort() |
64
|
|
|
print('Database initialization failed') |
65
|
|
|
|