3 from __future__ import print_function
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
11 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
12 'AuthorBook', 'BookGenre', 'open_db', 'init_db',
13 'insert_name', 'insert_author', 'update_counters',
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)
28 fullnames = filter(None, (self.surname, self.name, self.misc_name))
29 return ' '.join(fullnames)
31 full_name_idx = DatabaseIndex(surname, name, misc_name, unique=True)
32 count_idx = DatabaseIndex(count)
35 class AuthorBook(SQLObject):
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)
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)
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)
77 return self.authors[0].fullname
80 def author_list(self):
81 return u', '.join([a.fullname for a in self.authors])
84 class BookGenre(SQLObject):
87 book = ForeignKey('Book', notNull=True, cascade=True)
88 genre = ForeignKey('Genre', notNull=True, cascade=True)
89 book_idx = DatabaseIndex(book)
90 genre_idx = DatabaseIndex(genre)
91 main_idx = DatabaseIndex(book, genre, unique=True)
94 class Extension(SQLObject):
95 name = UnicodeCol(notNull=True, unique=True)
96 count = IntCol(notNull=True)
97 count_idx = DatabaseIndex(count)
100 class Genre(SQLObject):
101 name = UnicodeCol(notNull=True, unique=True)
102 title = UnicodeCol(notNull=True)
103 count = IntCol(notNull=True)
104 books = RelatedJoin('Book', otherColumn='book_id',
105 intermediateTable='book_genre',
106 createRelatedTable=False)
107 title_idx = DatabaseIndex(title)
108 count_idx = DatabaseIndex(count)
111 class Language(SQLObject):
112 name = UnicodeCol(notNull=True, unique=True)
113 count = IntCol(notNull=True)
114 count_idx = DatabaseIndex(count)
117 def _find_sqlite_db_dirs_posix():
119 if 'XDG_CACHE_HOME' in os.environ:
120 db_dirs.append(os.environ['XDG_CACHE_HOME'])
121 home_cache = os.path.expanduser('~/.cache')
122 if home_cache not in db_dirs:
123 db_dirs.append(home_cache)
127 def find_sqlite_db_dirs():
128 if os.name == 'posix':
129 return _find_sqlite_db_dirs_posix()
130 raise OSError("Unknow OS")
133 def find_sqlite_dburi(db_dirs=None):
135 db_dirs = find_sqlite_db_dirs()
137 db_file = os.path.join(d, 'm_librarian.sqlite')
138 if os.path.exists(db_file):
142 # make the database file/directory readable/writeable only by the user
147 except OSError: # Perhaps already exists
149 db_file = os.path.join(db_dir, 'm_librarian.sqlite')
151 return 'sqlite://%s' % db_file.replace(os.sep, '/')
154 def open_db(db_uri=None):
156 db_uri = get_config().get('database', 'URI') or find_sqlite_dburi()
158 if '://' not in db_uri:
159 db_uri = 'sqlite://' + os.path.abspath(db_uri).replace(os.sep, '/')
161 sqlhub.processConnection = connection = connectionForURI(db_uri)
163 if connection.dbName == 'sqlite':
165 if isinstance(s, string_type):
169 sqlite = connection.module
171 class MLConnection(sqlite.Connection):
172 def __init__(self, *args, **kwargs):
173 super(MLConnection, self).__init__(*args, **kwargs)
174 self.create_function('lower', 1, lower)
176 # This hack must be done at the very beginning, before the first query
177 connection._connOptions['factory'] = MLConnection
179 # Speedup SQLite connection
180 connection.query("PRAGMA synchronous=OFF")
181 connection.query("PRAGMA count_changes=OFF")
182 connection.query("PRAGMA journal_mode=MEMORY")
183 connection.query("PRAGMA temp_store=MEMORY")
189 except IndexError: # Table exists but is empty
191 except dberrors.Error:
192 for table in Author, Extension, Genre, Language, Book, \
193 AuthorBook, BookGenre:
199 def insert_name(table, name, **kw):
201 return table.byName(name)
202 except SQLObjectNotFound:
203 return table(name=name, count=0, **kw)
206 def insert_author(surname, name, misc_name):
208 return Author.full_name_idx.get(
209 surname=surname, name=name, misc_name=misc_name)
210 except SQLObjectNotFound:
211 return Author(surname=surname, name=name, misc_name=misc_name, count=0)
214 def update_counters(pbar_cb=None):
217 for table in Author, Extension, Genre, Language:
218 count += table.select().count()
219 pbar_cb.set_max(count)
224 for author in Author.select():
225 author.count = AuthorBook.select(AuthorBook.q.author == author).count()
228 pbar_cb.display(count)
230 for ext in Extension.select():
231 ext.count = Book.select(Book.q.extension == ext.id).count()
234 pbar_cb.display(count)
236 for genre in Genre.select():
237 genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
240 pbar_cb.display(count)
242 for language in Language.select():
243 language.count = Book.select(Book.q.language == language.id).count()
246 pbar_cb.display(count)
253 db_dirs = find_sqlite_db_dirs()
254 print("DB dirs:", db_dirs)
255 print("DB URI:", find_sqlite_dburi())
258 if __name__ == '__main__':