]> git.phdru.name Git - xsetbg.git/blob - xsetbg_db.py
Refactoring: move DB (re)creation code to xsetbg_db.py
[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     StringCol, UnicodeCol, IntCol, BoolCol, DatabaseIndex, dberrors, \
15     SQLObjectNotFound
16 from xsetbg_conf import xsetbg_conf
17
18
19 class SqliteSequence(SQLObject):
20     class sqlmeta:
21         idName = 'rowid'
22     name = StringCol(unique=True)
23     seq = IntCol()
24
25
26 class XSetBg(SQLObject):
27     full_name = UnicodeCol(alternateID=True)
28     last_shown = IntCol(default=None)  # timestamp
29     flag = BoolCol(default=None)
30
31     last_shown_idx = DatabaseIndex('last_shown')
32     flag_idx = DatabaseIndex('flag')
33
34     def clearTable(self):
35         super.clearTable(XSetBg, self)
36         try:
37             seq = SqliteSequence.byName(XSetBg.sqlmeta.table)
38         except SQLObjectNotFound:
39             SqliteSequence(name=XSetBg.sqlmeta.table, seq=0)
40         else:
41             seq.seq = 0  # Reset autoincrement counter
42
43
44 def recreate_db():
45     global xsetbg_db
46     if xsetbg_db:
47         xsetbg_db.clearTable()
48     else:
49         xsetbg_db = XSetBg
50         xsetbg_db.createTable()
51     return xsetbg_db
52
53
54 db_dirs = []
55 try:
56     xsetbg_db_path = xsetbg_conf.get('xsetbg', 'database')
57 except:
58     xsetbg_db_path = None
59
60 if not xsetbg_db_path:
61     if 'XDG_CACHE_HOME' in os.environ:
62         db_dirs.append(os.environ['XDG_CACHE_HOME'])
63     home_cache = os.path.expanduser('~/.cache')
64     if home_cache not in db_dirs:
65         db_dirs.append(home_cache)
66     db_dirs.append(os.path.dirname(os.path.abspath(__file__)))
67
68     for d in db_dirs:
69         xsetbg_db_path = os.path.join(d, 'xsetbg.sqlite')
70         if os.path.exists(xsetbg_db_path):
71             break
72
73 if xsetbg_db_path:
74     sqlhub.processConnection = \
75         connectionForURI('sqlite:///%s' % xsetbg_db_path)
76     try:
77         XSetBg.select()[0]
78     except IndexError:
79         xsetbg_db = XSetBg  # Table exists but is empty
80     except dberrors.Error:
81         xsetbg_db = None
82     else:
83         xsetbg_db = XSetBg
84 else:
85     xsetbg_db = None
86
87 if __name__ == '__main__':
88     print "DB dirs:", db_dirs
89     print "DB file:", xsetbg_db_path