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