]> git.phdru.name Git - xsetbg.git/blob - xsetbg_db.py
Version 5.0.2
[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 # octal; -rw-------; make the database file(s) readable only by the user
18 os.umask(0066)
19
20
21 class XSetBg(SQLObject):
22     full_name = UnicodeCol(alternateID=True)
23     last_shown = IntCol(default=None)  # timestamp
24     flag = BoolCol(default=None)
25
26     last_shown_idx = DatabaseIndex('last_shown')
27     flag_idx = DatabaseIndex('flag')
28
29
30 def recreate_db():
31     global xsetbg_db
32     if not xsetbg_db:
33         xsetbg_db = XSetBg
34         xsetbg_db.createTable()
35     return xsetbg_db
36
37
38 class SQLiteMassInsert(object):
39     def __init__(self):
40         self.connection = sqlhub.processConnection
41
42     def __enter__(self):
43         connection = self.connection
44         connection.query("PRAGMA synchronous=OFF")
45         connection.query("PRAGMA count_changes=OFF")
46         connection.query("PRAGMA journal_mode=MEMORY")
47         connection.query("PRAGMA temp_store=MEMORY")
48
49         txn = connection.transaction()
50         sqlhub.processConnection = txn
51         return txn
52
53     def __exit__(self, *args, **kw):
54         sqlhub.processConnection.commit()
55         connection = sqlhub.processConnection = self.connection
56         connection.query("VACUUM %s" % xsetbg_db.sqlmeta.table)
57
58
59 db_dirs = []
60 try:
61     xsetbg_db_path = xsetbg_conf.get('xsetbg', 'database')
62 except:
63     xsetbg_db_path = None
64
65 if not xsetbg_db_path:
66     if 'XDG_CACHE_HOME' in os.environ:
67         db_dirs.append(os.environ['XDG_CACHE_HOME'])
68     home_cache = os.path.expanduser('~/.cache')
69     if home_cache not in db_dirs:
70         db_dirs.append(home_cache)
71     db_dirs.append(os.path.dirname(os.path.abspath(__file__)))
72
73     for d in db_dirs:
74         xsetbg_db_path = os.path.join(d, 'xsetbg.sqlite')
75         if os.path.exists(xsetbg_db_path):
76             break
77
78 if xsetbg_db_path:
79     sqlhub.processConnection = \
80         connectionForURI('sqlite:///%s' % xsetbg_db_path)
81     try:
82         XSetBg.select()[0]
83     except IndexError:
84         xsetbg_db = XSetBg  # Table exists but is empty
85     except dberrors.Error:
86         xsetbg_db = None
87     else:
88         xsetbg_db = XSetBg
89 else:
90     xsetbg_db = None
91
92 if __name__ == '__main__':
93     print "DB dirs:", db_dirs
94     print "DB file:", xsetbg_db_path