]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
Cleanup: Fix flake8 E722 do not use bare except
[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 = StringCol(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
76 class BookGenre(SQLObject):
77     class sqlmeta:
78         table = "book_genre"
79     book = ForeignKey('Book', notNull=True, cascade=True)
80     genre = ForeignKey('Genre', notNull=True, cascade=True)
81     book_idx = DatabaseIndex(book)
82     genre_idx = DatabaseIndex(genre)
83     main_idx = DatabaseIndex(book, genre, unique=True)
84
85
86 class Extension(SQLObject):
87     name = UnicodeCol(notNull=True, unique=True)
88     count = IntCol(notNull=True)
89     count_idx = DatabaseIndex(count)
90
91
92 class Genre(SQLObject):
93     name = UnicodeCol(notNull=True, unique=True)
94     title = UnicodeCol(notNull=True)
95     count = IntCol(notNull=True)
96     books = RelatedJoin('Book', otherColumn='book_id',
97                         intermediateTable='book_genre',
98                         createRelatedTable=False)
99     title_idx = DatabaseIndex(title)
100     count_idx = DatabaseIndex(count)
101
102
103 class Language(SQLObject):
104     name = UnicodeCol(notNull=True, unique=True)
105     count = IntCol(notNull=True)
106     count_idx = DatabaseIndex(count)
107
108
109 def _find_sqlite_db_dirs_posix():
110     db_dirs = []
111     if 'XDG_CACHE_HOME' in os.environ:
112         db_dirs.append(os.environ['XDG_CACHE_HOME'])
113     home_cache = os.path.expanduser('~/.cache')
114     if home_cache not in db_dirs:
115         db_dirs.append(home_cache)
116     return db_dirs
117
118
119 def find_sqlite_db_dirs():
120     if os.name == 'posix':
121         return _find_sqlite_db_dirs_posix()
122     raise OSError("Unknow OS")
123
124
125 def find_sqlite_dburi(db_dirs=None):
126     if db_dirs is None:
127         db_dirs = find_sqlite_db_dirs()
128     for d in db_dirs:
129         db_file = os.path.join(d, 'm_librarian.sqlite')
130         if os.path.exists(db_file):
131             break
132     else:
133         # octal; -rw-------;
134         # make the database file/directory readable/writeable only by the user
135         os.umask(0o66)
136         db_dir = db_dirs[0]
137         try:
138             os.makedirs(db_dir)
139         except OSError:  # Perhaps already exists
140             pass
141         db_file = os.path.join(db_dir, 'm_librarian.sqlite')
142
143     return 'sqlite://%s' % db_file.replace(os.sep, '/')
144
145
146 def open_db(db_uri=None):
147     if db_uri is None:
148         try:
149             db_uri = get_config().get('database', 'URI')
150         except Exception:
151             db_uri = find_sqlite_dburi()
152
153     if '://' not in db_uri:
154         db_uri = 'sqlite://' + os.path.abspath(db_uri).replace(os.sep, '/')
155
156     sqlhub.processConnection = connection = connectionForURI(db_uri)
157
158     if connection.dbName == 'sqlite':
159         def lower(s):
160             if isinstance(s, string_type):
161                 return s.lower()
162             return s
163
164         sqlite = connection.module
165
166         class MLConnection(sqlite.Connection):
167             def __init__(self, *args, **kwargs):
168                 super(MLConnection, self).__init__(*args, **kwargs)
169                 self.create_function('lower', 1, lower)
170
171         # This hack must be done at the very beginning, before the first query
172         connection._connOptions['factory'] = MLConnection
173
174         # Speedup SQLite connection
175         connection.query("PRAGMA synchronous=OFF")
176         connection.query("PRAGMA count_changes=OFF")
177         connection.query("PRAGMA journal_mode=MEMORY")
178         connection.query("PRAGMA temp_store=MEMORY")
179
180
181 def init_db():
182     try:
183         Book.select()[0]
184     except IndexError:  # Table exists but is empty
185         return
186     except dberrors.Error:
187         for table in Author, Extension, Genre, Language, Book, \
188                 AuthorBook, BookGenre:
189             table.createTable()
190     else:
191         return
192
193
194 def insert_name(table, name, **kw):
195     try:
196         return table.byName(name)
197     except SQLObjectNotFound:
198         return table(name=name, count=0, **kw)
199
200
201 def insert_author(surname, name, misc_name):
202     try:
203         return Author.full_name_idx.get(
204             surname=surname, name=name, misc_name=misc_name)
205     except SQLObjectNotFound:
206         return Author(surname=surname, name=name, misc_name=misc_name, count=0)
207
208
209 def update_counters():
210     for author in Author.select():
211         author.count = AuthorBook.select(AuthorBook.q.author == author).count()
212
213     for ext in Extension.select():
214         ext.count = Book.select(Book.q.extension == ext.id).count()
215
216     for genre in Genre.select():
217         genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
218
219     for language in Language.select():
220         language.count = Book.select(Book.q.language == language.id).count()
221
222
223 def test():
224     db_dirs = find_sqlite_db_dirs()
225     print("DB dirs:", db_dirs)
226     print("DB URI:", find_sqlite_dburi())
227
228
229 if __name__ == '__main__':
230     test()