]> git.phdru.name Git - m_librarian.git/blob - m_librarian/db.py
Create intermediate tables with unique indices
[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     name = UnicodeCol(unique=True)
57     count = IntCol()
58     count_idx = DatabaseIndex('count')
59     books = RelatedJoin('Book', otherColumn='book_id',
60                         intermediateTable='author_book',
61                         createRelatedTable=False)
62
63
64 class AuthorBook(SQLObject):
65     class sqlmeta:
66         table = "author_book"
67     author = ForeignKey('Author', notNull=True, cascade=True)
68     book = ForeignKey('Book', notNull=True, cascade=True)
69     main_idx = DatabaseIndex(author, book, unique=True)
70
71
72 class Book(SQLObject):
73     authors = RelatedJoin('Author',
74                           intermediateTable='author_book',
75                           createRelatedTable=False)
76     genres = RelatedJoin('Genre',
77                          intermediateTable='book_genre',
78                          createRelatedTable=False)
79     title = UnicodeCol()
80     series = UnicodeCol()
81     ser_no = IntCol()
82     archive = StringCol()
83     file = StringCol()
84     size = IntCol()
85     lib_id = StringCol()
86     deleted = BoolCol()
87     extension = ForeignKey('Extension')
88     date = DateCol()
89     language = ForeignKey('Language')
90     archive_file_idx = DatabaseIndex('archive', 'file', unique=True)
91
92
93 class BookGenre(SQLObject):
94     class sqlmeta:
95         table = "book_genre"
96     book = ForeignKey('Book', notNull=True, cascade=True)
97     genre = ForeignKey('Genre', notNull=True, cascade=True)
98     main_idx = DatabaseIndex(book, genre, unique=True)
99
100
101 class Extension(SQLObject):
102     name = StringCol(unique=True)
103     count = IntCol()
104     count_idx = DatabaseIndex('count')
105
106
107 class Genre(SQLObject):
108     name = StringCol(unique=True)
109     title = UnicodeCol()
110     count = IntCol()
111     count_idx = DatabaseIndex('count')
112     books = RelatedJoin('Book', otherColumn='book_id',
113                         intermediateTable='book_genre',
114                         createRelatedTable=False)
115
116
117 class Language(SQLObject):
118     name = StringCol(unique=True)
119     count = IntCol()
120     count_idx = DatabaseIndex('count')
121
122
123 def init_db():
124     try:
125         Book.select()[0]
126     except IndexError:  # Table exists but is empty
127         return
128     except dberrors.Error:
129         for table in Author, Extension, Genre, Language, Book, \
130                 AuthorBook, BookGenre:
131             table.createTable()
132     else:
133         return
134
135
136 def insert_name(table, name, **kw):
137     try:
138         return table.byName(name)
139     except SQLObjectNotFound:
140         return table(name=name, count=0, **kw)
141
142
143 def update_counters():
144     for author in Author.select():
145         author.count = len(author.books)
146
147     for ext in Extension.select():
148         ext.count = Book.select(Book.q.extension == ext.name).count()
149
150     for genre in Genre.select():
151         genre.count = len(genre.books)
152
153     for language in Language.select():
154         language.count = Book.select(Book.q.language == language.name).count()
155
156
157 def test():
158     print "DB dirs:", db_dirs
159     if db_uri:
160         print "DB URI:", db_uri
161
162 if __name__ == '__main__':
163     test()