Skip to content

Commit

Permalink
Fix race condition between qk and daemon accessing database. Resolves #…
Browse files Browse the repository at this point in the history
  • Loading branch information
bostrt committed Nov 29, 2020
1 parent 7849ca8 commit 17a3a29
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
30 changes: 19 additions & 11 deletions quikey/models.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,41 @@
from os.path import join
from tinydb import TinyDB, Query
from datetime import datetime
from filelock import FileLock

class Database():

class Database:
def __init__(self, appDirs, dbFile='phrases.json'):
self.lock = FileLock(join(appDirs.data, dbFile + '.lock'))
self.appDirs = appDirs
self.dbFile = self.appDirs.data + '/' + dbFile
# Ensure database file exists
self.dbFile = join(self.appDirs.data, dbFile)
self.db = TinyDB(self.dbFile)

def get(self, key):
phrase = Query()
phraseDict = self.db.get(phrase.key == key)
if phraseDict is None:
return None
return phraseDict.get('value')
with self.lock:
phraseDict = self.db.get(phrase.key == key)
if phraseDict is None:
return None
return phraseDict.get('value')

def put(self, key, value, tags=None):
now = datetime.utcnow().isoformat()
phrase = {'key': key, 'value': value, 'tags': tags, 'updated': now}
self.db.insert(phrase)
with self.lock:
self.db.insert(phrase)

def update(self, key, value, tags=None):
now = datetime.utcnow().isoformat()
phrase = Query()
self.db.update({'key': key, 'value': value, 'updated': now}, phrase.key == key)
with self.lock:
self.db.update({'key': key, 'value': value, 'updated': now}, phrase.key == key)

def delete(self, key):
phrase = Query()
return self.db.remove(phrase.key == key)
with self.lock:
return self.db.remove(phrase.key == key)

def all(self):
return self.db.all()
with self.lock:
return self.db.all()
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@
'pyxdg',
'humanize',
'pick',
'filelock'
]
)

0 comments on commit 17a3a29

Please sign in to comment.