Commit 74494ea1956ed2b57f654fe229787622f97841ba

Authored by hitier
1 parent ab5ec0ea

cli.create_db holds errors at existing db

Showing 1 changed file with 23 additions and 9 deletions   Show diff stats
app/commands/commands.py
... ... @@ -3,7 +3,7 @@ import click
3 3 import random
4 4  
5 5 from flask import current_app
6   -from sqlalchemy.exc import OperationalError
  6 +from sqlalchemy.exc import OperationalError, IntegrityError
7 7 from sqlalchemy.sql import func
8 8 from sqlalchemy.ext.automap import automap_base
9 9 from sqlalchemy.orm import Session
... ... @@ -17,9 +17,10 @@ from . import bp
17 17  
18 18 @bp.cli.command("feed_from_lesia")
19 19 def feed_from_lesia():
20   - """ Feed db with agents from a lesia like mysql database.
  20 + """
  21 + Feed db with agents from a lesia like mysql database.
21 22  
22   - configure that database uri in the db_config.py file.
  23 + configure the proper database uri in the db_config.py file.
23 24 """
24 25 Base = automap_base()
25 26  
... ... @@ -29,8 +30,7 @@ def feed_from_lesia():
29 30 try:
30 31 Base.prepare(engine, reflect=True)
31 32 except OperationalError:
32   - # TODO: use logging facility instead
33   - print("Please, configure the mysql database (see db_config.py)")
  33 + current_app.logger.error("Please, configure the mysql database (see db_config.py)")
34 34 sys.exit(-1)
35 35  
36 36 # mapped classes are now created with names by default
... ... @@ -142,11 +142,25 @@ def user_delete(user_id):
142 142  
143 143 @bp.cli.command('create_db')
144 144 def create_db():
145   - """ Create the database structure."""
  145 + """
  146 + Create the database structure. Database should be empty.
  147 +
  148 + configure the proper database uri in the db_config.py file.
  149 + """
146 150 db.create_all()
147 151 admin = User(email='admin@nowhere.org', name='admin', login='admin', password='admin', role='admin')
148   - db.session.add(admin)
149   - db.session.commit()
  152 + sqlite_uri = db.engine.url.__str__() if 'sqlite' in db.engine.url.__str__() else None
  153 + try:
  154 + db.session.add(admin)
  155 + db.session.commit()
  156 + except IntegrityError:
  157 + current_app.logger.error("User admin already exists, database should be empty at create")
  158 + if sqlite_uri:
  159 + current_app.logger.error("see "+sqlite_uri)
  160 + sys.exit(-1)
  161 +
  162 + if sqlite_uri:
  163 + current_app.logger.info("Created sqlite db: "+sqlite_uri)
150 164  
151 165  
152 166 @bp.cli.command('user_add')
... ... @@ -159,7 +173,7 @@ def user_add(email, name, login, password):
159 173 user = User(email=email, name=name, login=login, password=password)
160 174 db.session.add(user)
161 175 db.session.commit()
162   - print("added ", name)
  176 + current_app.logger.info("added ", name)
163 177  
164 178  
165 179 @bp.cli.command('user_show_all')
... ...