]> git.phdru.name Git - xsetbg.git/blob - xsetbg_db.py
Execute VACUUM after reloading
[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 db_dirs = []
36 try:
37     xsetbg_db_path = xsetbg_conf.get('xsetbg', 'database')
38 except:
39     xsetbg_db_path = None
40
41 if not xsetbg_db_path:
42     if 'XDG_CACHE_HOME' in os.environ:
43         db_dirs.append(os.environ['XDG_CACHE_HOME'])
44     home_cache = os.path.expanduser('~/.cache')
45     if home_cache not in db_dirs:
46         db_dirs.append(home_cache)
47     db_dirs.append(os.path.dirname(os.path.abspath(__file__)))
48
49     for d in db_dirs:
50         xsetbg_db_path = os.path.join(d, 'xsetbg.sqlite')
51         if os.path.exists(xsetbg_db_path):
52             break
53
54 if xsetbg_db_path:
55     sqlhub.processConnection = \
56         connectionForURI('sqlite:///%s' % xsetbg_db_path)
57     try:
58         XSetBg.select()[0]
59     except IndexError:
60         xsetbg_db = XSetBg  # Table exists but is empty
61     except dberrors.Error:
62         xsetbg_db = None
63     else:
64         xsetbg_db = XSetBg
65 else:
66     xsetbg_db = None
67
68 if __name__ == '__main__':
69     print "DB dirs:", db_dirs
70     print "DB file:", xsetbg_db_path