3 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
4 'AuthorBook', 'BookGenre', 'open_db', 'init_db',
5 'insert_name', 'insert_author', 'update_counters',
9 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
10 ForeignKey, DateCol, DatabaseIndex, RelatedJoin, \
11 connectionForURI, sqlhub, SQLObjectNotFound, dberrors
12 from .config import get_config
15 class Author(SQLObject):
16 surname = UnicodeCol(notNull=True)
17 name = UnicodeCol(notNull=True)
18 misc_name = UnicodeCol(notNull=True)
19 count = IntCol(notNull=True)
20 books = RelatedJoin('Book', otherColumn='book_id',
21 intermediateTable='author_book',
22 createRelatedTable=False)
23 full_name_idx = DatabaseIndex(surname, name, misc_name, unique=True)
24 count_idx = DatabaseIndex(count)
27 class AuthorBook(SQLObject):
30 author = ForeignKey('Author', notNull=True, cascade=True)
31 book = ForeignKey('Book', notNull=True, cascade=True)
32 author_idx = DatabaseIndex(author)
33 book_idx = DatabaseIndex(book)
34 main_idx = DatabaseIndex(author, book, unique=True)
37 class Book(SQLObject):
38 authors = RelatedJoin('Author',
39 intermediateTable='author_book',
40 createRelatedTable=False)
41 genres = RelatedJoin('Genre',
42 intermediateTable='book_genre',
43 createRelatedTable=False)
44 title = UnicodeCol(notNull=True)
45 series = UnicodeCol(notNull=True)
47 archive = StringCol(notNull=True)
48 file = StringCol(notNull=True)
49 size = IntCol(notNull=True)
50 lib_id = StringCol(notNull=True)
51 deleted = BoolCol(notNull=True)
52 extension = ForeignKey('Extension', notNull=True)
53 date = DateCol(notNull=True)
54 language = ForeignKey('Language')
55 title_idx = DatabaseIndex(title)
56 series_idx = DatabaseIndex(series)
57 ser_no_idx = DatabaseIndex(ser_no)
58 archive_idx = DatabaseIndex(archive)
59 archive_file_idx = DatabaseIndex(archive, file, unique=True)
60 file_idx = DatabaseIndex(file)
61 size_idx = DatabaseIndex(size)
62 deleted_idx = DatabaseIndex(deleted)
63 extension_idx = DatabaseIndex(extension)
64 date_idx = DatabaseIndex(date)
65 language_idx = DatabaseIndex(language)
68 class BookGenre(SQLObject):
71 book = ForeignKey('Book', notNull=True, cascade=True)
72 genre = ForeignKey('Genre', notNull=True, cascade=True)
73 book_idx = DatabaseIndex(book)
74 genre_idx = DatabaseIndex(genre)
75 main_idx = DatabaseIndex(book, genre, unique=True)
78 class Extension(SQLObject):
79 name = UnicodeCol(notNull=True, unique=True)
80 count = IntCol(notNull=True)
81 count_idx = DatabaseIndex(count)
84 class Genre(SQLObject):
85 name = UnicodeCol(notNull=True, unique=True)
86 title = UnicodeCol(notNull=True)
87 count = IntCol(notNull=True)
88 books = RelatedJoin('Book', otherColumn='book_id',
89 intermediateTable='book_genre',
90 createRelatedTable=False)
91 title_idx = DatabaseIndex(title)
92 count_idx = DatabaseIndex(count)
95 class Language(SQLObject):
96 name = UnicodeCol(notNull=True, unique=True)
97 count = IntCol(notNull=True)
98 count_idx = DatabaseIndex(count)
101 def _find_sqlite_db_dirs_posix():
103 if 'XDG_CACHE_HOME' in os.environ:
104 db_dirs.append(os.environ['XDG_CACHE_HOME'])
105 home_cache = os.path.expanduser('~/.cache')
106 if home_cache not in db_dirs:
107 db_dirs.append(home_cache)
111 def find_sqlite_db_dirs():
112 if os.name == 'posix':
113 return _find_sqlite_db_dirs_posix()
114 raise OSError("Unknow OS")
117 def find_sqlite_dburi(db_dirs=None):
119 db_dirs = find_sqlite_db_dirs()
121 db_file = os.path.join(d, 'm_librarian.sqlite')
122 if os.path.exists(db_file):
126 # make the database file/directory readable/writeable only by the user
131 except OSError: # Perhaps already exists
133 db_file = os.path.join(db_dir, 'm_librarian.sqlite')
135 return 'sqlite://%s' % db_file.replace(os.sep, '/')
138 def open_db(db_uri=None):
141 db_uri = get_config().get('database', 'URI')
143 db_uri = find_sqlite_dburi()
145 sqlhub.processConnection = connection = connectionForURI(db_uri)
147 if connection.dbName == 'sqlite':
151 sqlite = connection.module
153 class MLConnection(sqlite.Connection):
154 def __init__(self, *args, **kwargs):
155 super(MLConnection, self).__init__(*args, **kwargs)
156 self.create_function('lower', 1, lower)
158 # This hack must be done at the very beginning, before the first query
159 connection._connOptions['factory'] = MLConnection
161 # Speedup SQLite connection
162 connection.query("PRAGMA synchronous=OFF")
163 connection.query("PRAGMA count_changes=OFF")
164 connection.query("PRAGMA journal_mode=MEMORY")
165 connection.query("PRAGMA temp_store=MEMORY")
171 except IndexError: # Table exists but is empty
173 except dberrors.Error:
174 for table in Author, Extension, Genre, Language, Book, \
175 AuthorBook, BookGenre:
181 def insert_name(table, name, **kw):
183 return table.byName(name)
184 except SQLObjectNotFound:
185 return table(name=name, count=0, **kw)
188 def insert_author(surname, name, misc_name):
190 return Author.full_name_idx.get(
191 surname=surname, name=name, misc_name=misc_name)
192 except SQLObjectNotFound:
193 return Author(surname=surname, name=name, misc_name=misc_name, count=0)
196 def update_counters():
197 for author in Author.select():
198 author.count = AuthorBook.select(AuthorBook.q.author == author).count()
200 for ext in Extension.select():
201 ext.count = Book.select(Book.q.extension == ext.id).count()
203 for genre in Genre.select():
204 genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
206 for language in Language.select():
207 language.count = Book.select(Book.q.language == language.id).count()
211 db_dirs = find_sqlite_db_dirs()
212 print "DB dirs:", db_dirs
213 print "DB URI:", find_sqlite_dburi()
215 if __name__ == '__main__':