]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
6e08204acfcdac30da1ec9790b2132d9e7d8df14
[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', '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_file_idx = DatabaseIndex(archive, file, unique=True)
99     file_idx = DatabaseIndex(file)
100     size_idx = DatabaseIndex(size)
101     deleted_idx = DatabaseIndex(deleted)
102     extension_idx = DatabaseIndex(extension)
103     date_idx = DatabaseIndex(date)
104     language_idx = DatabaseIndex(language)
105
106
107 class BookGenre(SQLObject):
108     class sqlmeta:
109         table = "book_genre"
110     book = ForeignKey('Book', notNull=True, cascade=True)
111     genre = ForeignKey('Genre', notNull=True, cascade=True)
112     book_idx = DatabaseIndex(book)
113     genre_idx = DatabaseIndex(genre)
114     main_idx = DatabaseIndex(book, genre, unique=True)
115
116
117 class Extension(SQLObject):
118     name = StringCol(notNull=True, unique=True)
119     count = IntCol(notNull=True)
120     count_idx = DatabaseIndex(count)
121
122
123 class Genre(SQLObject):
124     name = StringCol(notNull=True, unique=True)
125     title = UnicodeCol(notNull=True)
126     count = IntCol(notNull=True)
127     books = RelatedJoin('Book', otherColumn='book_id',
128                         intermediateTable='book_genre',
129                         createRelatedTable=False)
130     title_idx = DatabaseIndex(title)
131     count_idx = DatabaseIndex(count)
132
133
134 class Language(SQLObject):
135     name = StringCol(notNull=True, unique=True)
136     count = IntCol(notNull=True)
137     count_idx = DatabaseIndex(count)
138
139
140 def init_db():
141     try:
142         Book.select()[0]
143     except IndexError:  # Table exists but is empty
144         return
145     except dberrors.Error:
146         for table in Author, Extension, Genre, Language, Book, \
147                 AuthorBook, BookGenre:
148             table.createTable()
149     else:
150         return
151
152
153 def insert_name(table, name, **kw):
154     try:
155         return table.byName(name)
156     except SQLObjectNotFound:
157         return table(name=name, count=0, **kw)
158
159
160 def update_counters():
161     for author in Author.select():
162         author.count = len(author.books)
163
164     for ext in Extension.select():
165         ext.count = Book.select(Book.q.extension == ext.name).count()
166
167     for genre in Genre.select():
168         genre.count = len(genre.books)
169
170     for language in Language.select():
171         language.count = Book.select(Book.q.language == language.name).count()
172
173
174 def test():
175     print "DB dirs:", db_dirs
176     if db_uri:
177         print "DB URI:", db_uri
178
179 if __name__ == '__main__':
180     test()