database.py 992 B

12345678910111213141516171819202122232425262728293031
  1. # encoding=utf-8
  2. import sqlalchemy
  3. from sqlalchemy.engine import create_engine
  4. from sqlalchemy.pool import SingletonThreadPool
  5. from terroroftinytown.tracker.model import Session, Base
  6. class Database(object):
  7. def __init__(self, path, delete_everything=False):
  8. if path.startswith('sqlite:'):
  9. self.engine = create_engine(path, poolclass=SingletonThreadPool)
  10. sqlalchemy.event.listen(
  11. self.engine, 'connect', self._apply_pragmas_callback)
  12. else:
  13. self.engine = create_engine(path)
  14. Session.configure(bind=self.engine)
  15. if delete_everything == 'yes-really!':
  16. self._delete_everything()
  17. Base.metadata.create_all(self.engine)
  18. @classmethod
  19. def _apply_pragmas_callback(cls, connection, record):
  20. connection.execute('PRAGMA journal_mode=WAL')
  21. connection.execute('PRAGMA synchronous=NORMAL')
  22. def _delete_everything(self):
  23. Base.metadata.drop_all(self.engine)