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