]> git.phdru.name Git - xsetbg.git/blob - xsetbg_db.py
Refactor mass insert into SQLiteMassInsert context manager
[xsetbg.git] / xsetbg_db.py
1 #! /usr/bin/env python
2 """XSetBg database
3
4 """
5
6 __author__ = "Oleg Broytman <phd@phdru.name>"
7 __copyright__ = "Copyright (C) 2014, 2015 PhiloSoft Design"
8 __license__ = "GNU GPL"
9
10 __all__ = ['xsetbg_db_path', 'xsetbg_db']
11
12 import os
13 from sqlobject import SQLObject, connectionForURI, sqlhub, \
14     UnicodeCol, IntCol, BoolCol, DatabaseIndex, dberrors
15 from xsetbg_conf import xsetbg_conf
16
17
18 class XSetBg(SQLObject):
19     full_name = UnicodeCol(alternateID=True)
20     last_shown = IntCol(default=None)  # timestamp
21     flag = BoolCol(default=None)
22
23     last_shown_idx = DatabaseIndex('last_shown')
24     flag_idx = DatabaseIndex('flag')
25
26
27 def recreate_db():
28     global xsetbg_db
29     if not xsetbg_db:
30         xsetbg_db = XSetBg
31         xsetbg_db.createTable()
32     return xsetbg_db
33
34
35 class SQLiteMassInsert(object):
36     def __init__(self):
37         self.connection = sqlhub.processConnection
38
39     def __enter__(self):
40         connection = self.connection
41         connection.query("PRAGMA synchronous=OFF")
42         connection.query("PRAGMA count_changes=OFF")
43         connection.query("PRAGMA journal_mode=MEMORY")
44         connection.query("PRAGMA temp_store=MEMORY")
45
46         txn = connection.transaction()
47         sqlhub.processConnection = txn
48         return txn
49
50     def __exit__(self, *args, **kw):
51         sqlhub.processConnection.commit()
52         connection = sqlhub.processConnection = self.connection
53         connection.query("VACUUM %s" % xsetbg_db.sqlmeta.table)
54
55
56 db_dirs = []
57 try:
58     xsetbg_db_path = xsetbg_conf.get('xsetbg', 'database')
59 except:
60     xsetbg_db_path = None
61
62 if not xsetbg_db_path:
63     if 'XDG_CACHE_HOME' in os.environ:
64         db_dirs.append(os.environ['XDG_CACHE_HOME'])
65     home_cache = os.path.expanduser('~/.cache')
66     if home_cache not in db_dirs:
67         db_dirs.append(home_cache)
68     db_dirs.append(os.path.dirname(os.path.abspath(__file__)))
69
70     for d in db_dirs:
71         xsetbg_db_path = os.path.join(d, 'xsetbg.sqlite')
72         if os.path.exists(xsetbg_db_path):
73             break
74
75 if xsetbg_db_path:
76     sqlhub.processConnection = \
77         connectionForURI('sqlite:///%s' % xsetbg_db_path)
78     try:
79         XSetBg.select()[0]
80     except IndexError:
81         xsetbg_db = XSetBg  # Table exists but is empty
82     except dberrors.Error:
83         xsetbg_db = None
84     else:
85         xsetbg_db = XSetBg
86 else:
87     xsetbg_db = None
88
89 if __name__ == '__main__':
90     print "DB dirs:", db_dirs
91     print "DB file:", xsetbg_db_path