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