]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
7cd53a17c7bb78b38938901ccac59b0c53f94375
[m_librarian.git] / m_librarian / db.py
1 #! /usr/bin/env python
2
3 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
4            'init_db', 'insert_name',
5            ]
6
7 import os
8 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
9     ForeignKey, DateCol, connectionForURI, sqlhub, SQLObjectNotFound, 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     archive = StringCol()
57     file = StringCol()
58     size = IntCol()
59     lib_id = StringCol()
60     deleted = BoolCol()
61     ext = ForeignKey('Extension')
62     date = DateCol()
63     language = ForeignKey('Language')
64
65
66 class Extension(SQLObject):
67     name = StringCol(unique=True)
68     count = IntCol()
69
70
71 class Genre(SQLObject):
72     name = StringCol(unique=True)
73     title = UnicodeCol()
74     count = IntCol()
75
76
77 class Language(SQLObject):
78     name = StringCol(unique=True)
79     count = IntCol()
80
81
82 def init_db():
83     try:
84         Book.select()[0]
85     except IndexError:  # Table exists but is empty
86         return
87     except dberrors.Error:
88         for table in Author, Extension, Genre, Language, Book:
89             table.createTable()
90     else:
91         return
92
93
94 def insert_name(table, name):
95     try:
96         return table.byName(name)
97     except SQLObjectNotFound:
98         return table(name=name, count=0)
99
100
101 def test():
102     print "DB dirs:", db_dirs
103     if db_uri:
104         print "DB URI:", db_uri
105
106 if __name__ == '__main__':
107     test()