-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix race condition between qk and daemon accessing database. Resolves #…
…48.
- Loading branch information
Showing
2 changed files
with
20 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,5 +28,6 @@ | |
'pyxdg', | ||
'humanize', | ||
'pick', | ||
'filelock' | ||
] | ||
) |