Ensure single-threaded db access
SQLite doesn't really like concurrent access so mediate it with a lock. Change-Id: Ibb7aed2a5f028a2a01b61b37fa24f634e4898fbe
This commit is contained in:
parent
a5bb8ec113
commit
7ea4ad8b36
15
gertty/db.py
15
gertty/db.py
@ -12,7 +12,9 @@
|
|||||||
# License for the specific language governing permissions and limitations
|
# License for the specific language governing permissions and limitations
|
||||||
# under the License.
|
# under the License.
|
||||||
|
|
||||||
|
import time
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
|
|
||||||
import alembic
|
import alembic
|
||||||
import alembic.config
|
import alembic.config
|
||||||
@ -344,9 +346,10 @@ class Database(object):
|
|||||||
self.migrate()
|
self.migrate()
|
||||||
self.session_factory = sessionmaker(bind=self.engine)
|
self.session_factory = sessionmaker(bind=self.engine)
|
||||||
self.session = scoped_session(self.session_factory)
|
self.session = scoped_session(self.session_factory)
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
def getSession(self):
|
def getSession(self):
|
||||||
return DatabaseSession(self.session)
|
return DatabaseSession(self)
|
||||||
|
|
||||||
def migrate(self):
|
def migrate(self):
|
||||||
conn = self.engine.connect()
|
conn = self.engine.connect()
|
||||||
@ -366,10 +369,13 @@ class Database(object):
|
|||||||
alembic.command.upgrade(config, 'head')
|
alembic.command.upgrade(config, 'head')
|
||||||
|
|
||||||
class DatabaseSession(object):
|
class DatabaseSession(object):
|
||||||
def __init__(self, session):
|
def __init__(self, database):
|
||||||
self.session = session
|
self.database = database
|
||||||
|
self.session = database.session
|
||||||
|
|
||||||
def __enter__(self):
|
def __enter__(self):
|
||||||
|
self.database.lock.acquire()
|
||||||
|
self.start = time.time()
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __exit__(self, etype, value, tb):
|
def __exit__(self, etype, value, tb):
|
||||||
@ -379,6 +385,9 @@ class DatabaseSession(object):
|
|||||||
self.session().commit()
|
self.session().commit()
|
||||||
self.session().close()
|
self.session().close()
|
||||||
self.session = None
|
self.session = None
|
||||||
|
end = time.time()
|
||||||
|
self.database.log.debug("Database lock held %s seconds" % (end-self.start,))
|
||||||
|
self.database.lock.release()
|
||||||
|
|
||||||
def abort(self):
|
def abort(self):
|
||||||
self.session().rollback()
|
self.session().rollback()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user