]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
Feat(db): Add book.author1 property
[m_librarian.git] / m_librarian / db.py
1 #! /usr/bin/env python
2
3 from __future__ import print_function
4 import os
5 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
6     ForeignKey, DateCol, DatabaseIndex, RelatedJoin, \
7     connectionForURI, sqlhub, SQLObjectNotFound, dberrors
8 from .compat import string_type
9 from .config import get_config
10
11 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
12            'AuthorBook', 'BookGenre', 'open_db', 'init_db',
13            'insert_name', 'insert_author', 'update_counters',
14            ]
15
16
17 class Author(SQLObject):
18     surname = UnicodeCol(notNull=True)
19     name = UnicodeCol(notNull=True)
20     misc_name = UnicodeCol(notNull=True)
21     count = IntCol(notNull=True)
22     books = RelatedJoin('Book', otherColumn='book_id',
23                         intermediateTable='author_book',
24                         createRelatedTable=False)
25
26     @property
27     def fullname(self):
28         fullnames = filter(None, (self.surname, self.name, self.misc_name))
29         return ' '.join(fullnames)
30
31     full_name_idx = DatabaseIndex(surname, name, misc_name, unique=True)
32     count_idx = DatabaseIndex(count)
33
34
35 class AuthorBook(SQLObject):
36     class sqlmeta:
37         table = "author_book"
38     author = ForeignKey('Author', notNull=True, cascade=True)
39     book = ForeignKey('Book', notNull=True, cascade=True)
40     author_idx = DatabaseIndex(author)
41     book_idx = DatabaseIndex(book)
42     main_idx = DatabaseIndex(author, book, unique=True)
43
44
45 class Book(SQLObject):
46     authors = RelatedJoin('Author',
47                           intermediateTable='author_book',
48                           createRelatedTable=False)
49     genres = RelatedJoin('Genre',
50                          intermediateTable='book_genre',
51                          createRelatedTable=False)
52     title = UnicodeCol(notNull=True)
53     series = UnicodeCol(notNull=True)
54     ser_no = IntCol()
55     archive = StringCol(notNull=True)
56     file = UnicodeCol(notNull=True)
57     size = IntCol(notNull=True)
58     lib_id = StringCol(notNull=True)
59     deleted = BoolCol(notNull=True)
60     extension = ForeignKey('Extension', notNull=True)
61     date = DateCol(notNull=True)
62     language = ForeignKey('Language')
63     title_idx = DatabaseIndex(title)
64     series_idx = DatabaseIndex(series)
65     ser_no_idx = DatabaseIndex(ser_no)
66     archive_idx = DatabaseIndex(archive)
67     archive_file_idx = DatabaseIndex(archive, file, unique=True)
68     file_idx = DatabaseIndex(file)
69     size_idx = DatabaseIndex(size)
70     deleted_idx = DatabaseIndex(deleted)
71     extension_idx = DatabaseIndex(extension)
72     date_idx = DatabaseIndex(date)
73     language_idx = DatabaseIndex(language)
74
75     @property
76     def author1(self):
77         return self.authors[0].fullname
78
79
80 class BookGenre(SQLObject):
81     class sqlmeta:
82         table = "book_genre"
83     book = ForeignKey('Book', notNull=True, cascade=True)
84     genre = ForeignKey('Genre', notNull=True, cascade=True)
85     book_idx = DatabaseIndex(book)
86     genre_idx = DatabaseIndex(genre)
87     main_idx = DatabaseIndex(book, genre, unique=True)
88
89
90 class Extension(SQLObject):
91     name = UnicodeCol(notNull=True, unique=True)
92     count = IntCol(notNull=True)
93     count_idx = DatabaseIndex(count)
94
95
96 class Genre(SQLObject):
97     name = UnicodeCol(notNull=True, unique=True)
98     title = UnicodeCol(notNull=True)
99     count = IntCol(notNull=True)
100     books = RelatedJoin('Book', otherColumn='book_id',
101                         intermediateTable='book_genre',
102                         createRelatedTable=False)
103     title_idx = DatabaseIndex(title)
104     count_idx = DatabaseIndex(count)
105
106
107 class Language(SQLObject):
108     name = UnicodeCol(notNull=True, unique=True)
109     count = IntCol(notNull=True)
110     count_idx = DatabaseIndex(count)
111
112
113 def _find_sqlite_db_dirs_posix():
114     db_dirs = []
115     if 'XDG_CACHE_HOME' in os.environ:
116         db_dirs.append(os.environ['XDG_CACHE_HOME'])
117     home_cache = os.path.expanduser('~/.cache')
118     if home_cache not in db_dirs:
119         db_dirs.append(home_cache)
120     return db_dirs
121
122
123 def find_sqlite_db_dirs():
124     if os.name == 'posix':
125         return _find_sqlite_db_dirs_posix()
126     raise OSError("Unknow OS")
127
128
129 def find_sqlite_dburi(db_dirs=None):
130     if db_dirs is None:
131         db_dirs = find_sqlite_db_dirs()
132     for d in db_dirs:
133         db_file = os.path.join(d, 'm_librarian.sqlite')
134         if os.path.exists(db_file):
135             break
136     else:
137         # octal; -rw-------;
138         # make the database file/directory readable/writeable only by the user
139         os.umask(0o66)
140         db_dir = db_dirs[0]
141         try:
142             os.makedirs(db_dir)
143         except OSError:  # Perhaps already exists
144             pass
145         db_file = os.path.join(db_dir, 'm_librarian.sqlite')
146
147     return 'sqlite://%s' % db_file.replace(os.sep, '/')
148
149
150 def open_db(db_uri=None):
151     if db_uri is None:
152         db_uri = get_config().get('database', 'URI') or find_sqlite_dburi()
153
154     if '://' not in db_uri:
155         db_uri = 'sqlite://' + os.path.abspath(db_uri).replace(os.sep, '/')
156
157     sqlhub.processConnection = connection = connectionForURI(db_uri)
158
159     if connection.dbName == 'sqlite':
160         def lower(s):
161             if isinstance(s, string_type):
162                 return s.lower()
163             return s
164
165         sqlite = connection.module
166
167         class MLConnection(sqlite.Connection):
168             def __init__(self, *args, **kwargs):
169                 super(MLConnection, self).__init__(*args, **kwargs)
170                 self.create_function('lower', 1, lower)
171
172         # This hack must be done at the very beginning, before the first query
173         connection._connOptions['factory'] = MLConnection
174
175         # Speedup SQLite connection
176         connection.query("PRAGMA synchronous=OFF")
177         connection.query("PRAGMA count_changes=OFF")
178         connection.query("PRAGMA journal_mode=MEMORY")
179         connection.query("PRAGMA temp_store=MEMORY")
180
181
182 def init_db():
183     try:
184         Book.select()[0]
185     except IndexError:  # Table exists but is empty
186         return
187     except dberrors.Error:
188         for table in Author, Extension, Genre, Language, Book, \
189                 AuthorBook, BookGenre:
190             table.createTable()
191     else:
192         return
193
194
195 def insert_name(table, name, **kw):
196     try:
197         return table.byName(name)
198     except SQLObjectNotFound:
199         return table(name=name, count=0, **kw)
200
201
202 def insert_author(surname, name, misc_name):
203     try:
204         return Author.full_name_idx.get(
205             surname=surname, name=name, misc_name=misc_name)
206     except SQLObjectNotFound:
207         return Author(surname=surname, name=name, misc_name=misc_name, count=0)
208
209
210 def update_counters(pbar_cb=None):
211     if pbar_cb:
212         count = 0
213         for table in Author, Extension, Genre, Language:
214             count += table.select().count()
215         pbar_cb.set_max(count)
216
217     if pbar_cb:
218         count = 0
219
220     for author in Author.select():
221         author.count = AuthorBook.select(AuthorBook.q.author == author).count()
222         if pbar_cb:
223             count += 1
224             pbar_cb.display(count)
225
226     for ext in Extension.select():
227         ext.count = Book.select(Book.q.extension == ext.id).count()
228         if pbar_cb:
229             count += 1
230             pbar_cb.display(count)
231
232     for genre in Genre.select():
233         genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
234         if pbar_cb:
235             count += 1
236             pbar_cb.display(count)
237
238     for language in Language.select():
239         language.count = Book.select(Book.q.language == language.id).count()
240         if pbar_cb:
241             count += 1
242             pbar_cb.display(count)
243
244     if pbar_cb:
245         pbar_cb.close()
246
247
248 def test():
249     db_dirs = find_sqlite_db_dirs()
250     print("DB dirs:", db_dirs)
251     print("DB URI:", find_sqlite_dburi())
252
253
254 if __name__ == '__main__':
255     test()