]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
99a2843aa42f3ad5f347a86efaecde0b30b6a1d5
[m_librarian.git] / m_librarian / db.py
1 #! /usr/bin/env python
2
3 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
4            'AuthorBook', 'BookGenre',
5            'init_db', 'insert_name', 'insert_author', 'update_counters',
6            ]
7
8 import os
9 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
10     ForeignKey, DateCol, DatabaseIndex, RelatedJoin, \
11     connectionForURI, sqlhub, SQLObjectNotFound, dberrors
12 from .config import ml_conf
13
14 try:
15     db_uri = ml_conf.get('database', 'URI')
16 except:
17     db_uri = None
18
19 db_dirs = []
20 if not db_uri:
21     if 'XDG_CACHE_HOME' in os.environ:
22         db_dirs.append(os.environ['XDG_CACHE_HOME'])
23     home_cache = os.path.expanduser('~/.cache')
24     if home_cache not in db_dirs:
25         db_dirs.append(home_cache)
26
27     for d in db_dirs:
28         db_file = os.path.join(d, 'm_librarian.sqlite')
29         if os.path.exists(db_file):
30             break
31     else:
32         # octal; -rw-------;
33         # make the database file/directory readable/writeable only by the user
34         os.umask(0066)
35         db_dir = db_dirs[0]
36         try:
37             os.makedirs(db_dir)
38         except OSError:  # Perhaps already exists
39             pass
40         db_file = os.path.join(db_dir, 'm_librarian.sqlite')
41
42     db_uri = 'sqlite://%s' % db_file.replace(os.sep, '/')
43
44
45 sqlhub.processConnection = connection = connectionForURI(db_uri)
46
47 if connection.dbName == 'sqlite':
48     # Speedup SQLite connection
49     connection.query("PRAGMA synchronous=OFF")
50     connection.query("PRAGMA count_changes=OFF")
51     connection.query("PRAGMA journal_mode=MEMORY")
52     connection.query("PRAGMA temp_store=MEMORY")
53
54
55 class Author(SQLObject):
56     surname = UnicodeCol(notNull=True)
57     name = UnicodeCol(notNull=True)
58     misc_name = UnicodeCol(notNull=True)
59     count = IntCol(notNull=True)
60     books = RelatedJoin('Book', otherColumn='book_id',
61                         intermediateTable='author_book',
62                         createRelatedTable=False)
63     full_name_idx = DatabaseIndex(surname, name, misc_name, unique=True)
64     count_idx = DatabaseIndex(count)
65
66
67 class AuthorBook(SQLObject):
68     class sqlmeta:
69         table = "author_book"
70     author = ForeignKey('Author', notNull=True, cascade=True)
71     book = ForeignKey('Book', notNull=True, cascade=True)
72     author_idx = DatabaseIndex(author)
73     book_idx = DatabaseIndex(book)
74     main_idx = DatabaseIndex(author, book, unique=True)
75
76
77 class Book(SQLObject):
78     authors = RelatedJoin('Author',
79                           intermediateTable='author_book',
80                           createRelatedTable=False)
81     genres = RelatedJoin('Genre',
82                          intermediateTable='book_genre',
83                          createRelatedTable=False)
84     title = UnicodeCol(notNull=True)
85     series = UnicodeCol(notNull=True)
86     ser_no = IntCol()
87     archive = StringCol(notNull=True)
88     file = StringCol(notNull=True)
89     size = IntCol(notNull=True)
90     lib_id = StringCol(notNull=True)
91     deleted = BoolCol(notNull=True)
92     extension = ForeignKey('Extension', notNull=True)
93     date = DateCol(notNull=True)
94     language = ForeignKey('Language')
95     title_idx = DatabaseIndex(title)
96     series_idx = DatabaseIndex(series)
97     ser_no_idx = DatabaseIndex(ser_no)
98     archive_idx = DatabaseIndex(archive)
99     archive_file_idx = DatabaseIndex(archive, file, unique=True)
100     file_idx = DatabaseIndex(file)
101     size_idx = DatabaseIndex(size)
102     deleted_idx = DatabaseIndex(deleted)
103     extension_idx = DatabaseIndex(extension)
104     date_idx = DatabaseIndex(date)
105     language_idx = DatabaseIndex(language)
106
107
108 class BookGenre(SQLObject):
109     class sqlmeta:
110         table = "book_genre"
111     book = ForeignKey('Book', notNull=True, cascade=True)
112     genre = ForeignKey('Genre', notNull=True, cascade=True)
113     book_idx = DatabaseIndex(book)
114     genre_idx = DatabaseIndex(genre)
115     main_idx = DatabaseIndex(book, genre, unique=True)
116
117
118 class Extension(SQLObject):
119     name = StringCol(notNull=True, unique=True)
120     count = IntCol(notNull=True)
121     count_idx = DatabaseIndex(count)
122
123
124 class Genre(SQLObject):
125     name = StringCol(notNull=True, unique=True)
126     title = UnicodeCol(notNull=True)
127     count = IntCol(notNull=True)
128     books = RelatedJoin('Book', otherColumn='book_id',
129                         intermediateTable='book_genre',
130                         createRelatedTable=False)
131     title_idx = DatabaseIndex(title)
132     count_idx = DatabaseIndex(count)
133
134
135 class Language(SQLObject):
136     name = StringCol(notNull=True, unique=True)
137     count = IntCol(notNull=True)
138     count_idx = DatabaseIndex(count)
139
140
141 def init_db():
142     try:
143         Book.select()[0]
144     except IndexError:  # Table exists but is empty
145         return
146     except dberrors.Error:
147         for table in Author, Extension, Genre, Language, Book, \
148                 AuthorBook, BookGenre:
149             table.createTable()
150     else:
151         return
152
153
154 def insert_name(table, name, **kw):
155     try:
156         return table.byName(name)
157     except SQLObjectNotFound:
158         return table(name=name, count=0, **kw)
159
160
161 def insert_author(surname, name, misc_name):
162     try:
163         return Author.full_name_idx.get(
164             surname=surname, name=name, misc_name=misc_name)
165     except SQLObjectNotFound:
166         return Author(surname=surname, name=name, misc_name=misc_name, count=0)
167
168
169 def update_counters():
170     for author in Author.select():
171         author.count = AuthorBook.select(AuthorBook.q.author == author).count()
172
173     for ext in Extension.select():
174         ext.count = Book.select(Book.q.extension == ext.name).count()
175
176     for genre in Genre.select():
177         genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
178
179     for language in Language.select():
180         language.count = Book.select(Book.q.language == language.name).count()
181
182
183 def test():
184     print "DB dirs:", db_dirs
185     if db_uri:
186         print "DB URI:", db_uri
187
188 if __name__ == '__main__':
189     test()