]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
Fix a bug in opening existing SQLite db
[m_librarian.git] / m_librarian / db.py
1 #! /usr/bin/env python
2
3 import os
4 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
5     ForeignKey, DateCol, connectionForURI, sqlhub, dberrors
6 from .config import ml_conf
7
8 try:
9     db_uri = ml_conf.get('database', 'URI')
10 except:
11     db_uri = None
12
13 db_dirs = []
14 if not db_uri:
15     if 'XDG_CACHE_HOME' in os.environ:
16         db_dirs.append(os.environ['XDG_CACHE_HOME'])
17     home_cache = os.path.expanduser('~/.cache')
18     if home_cache not in db_dirs:
19         db_dirs.append(home_cache)
20
21     for d in db_dirs:
22         db_file = os.path.join(d, 'm_librarian.sqlite')
23         if os.path.exists(db_file):
24             break
25     else:
26         # octal; -rw-------;
27         # make the database file/directory readable/writeable only by the user
28         os.umask(0066)
29         db_dir = db_dirs[0]
30         try:
31             os.makedirs(db_dir)
32         except OSError:  # Perhaps already exists
33             pass
34         db_file = os.path.join(db_dir, 'm_librarian.sqlite')
35
36     db_uri = 'sqlite://%s' % db_file.replace(os.sep, '/')
37
38 sqlhub.processConnection = connectionForURI(db_uri)
39
40
41 class Author(SQLObject):
42     name = UnicodeCol(unique=True)
43     count = IntCol()
44
45
46 class Book(SQLObject):
47     author = ForeignKey('Author')
48     genre = ForeignKey('Genre')
49     title = UnicodeCol()
50     series = UnicodeCol()
51     ser_no = IntCol()
52     file = StringCol()
53     size = IntCol()
54     lib_id = StringCol()
55     deleted = BoolCol()
56     ext = ForeignKey('Extension')
57     date = DateCol()
58     language = ForeignKey('Language')
59
60
61 class Extension(SQLObject):
62     name = StringCol(unique=True)
63     count = IntCol()
64
65
66 class Genre(SQLObject):
67     name = StringCol(unique=True)
68     title = UnicodeCol()
69     count = IntCol()
70
71
72 class Language(SQLObject):
73     name = StringCol(unique=True)
74     count = IntCol()
75
76
77 def init_db():
78     try:
79         Book.select()[0]
80     except IndexError:  # Table exists but is empty
81         return
82     except dberrors.Error:
83         for table in Author, Extension, Genre, Language, Book:
84             table.createTable()
85     else:
86         return
87
88
89 if __name__ == '__main__':
90     print "DB dirs:", db_dirs
91     if db_uri:
92         print "DB URI:", db_uri