]> git.phdru.name Git - m_librarian.git/blobdiff - m_librarian/db.py
Speedup counting books
[m_librarian.git] / m_librarian / db.py
index 395d667b2855f547a655683843757f0dbd411990..65c79873612025d57bbda38955b8dc97787c0b6b 100755 (executable)
@@ -2,7 +2,7 @@
 
 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
            'AuthorBook', 'BookGenre',
-           'init_db', 'insert_name', 'update_counters',
+           'init_db', 'insert_name', 'insert_author', 'update_counters',
            ]
 
 import os
@@ -53,11 +53,14 @@ if connection.dbName == 'sqlite':
 
 
 class Author(SQLObject):
-    name = UnicodeCol(notNull=True, unique=True)
+    surname = UnicodeCol(notNull=True)
+    name = UnicodeCol(notNull=True)
+    misc_name = UnicodeCol(notNull=True)
     count = IntCol(notNull=True)
     books = RelatedJoin('Book', otherColumn='book_id',
                         intermediateTable='author_book',
                         createRelatedTable=False)
+    full_name_idx = DatabaseIndex(surname, name, misc_name, unique=True)
     count_idx = DatabaseIndex(count)
 
 
@@ -154,15 +157,23 @@ def insert_name(table, name, **kw):
         return table(name=name, count=0, **kw)
 
 
+def insert_author(surname, name, misc_name):
+    try:
+        return Author.full_name_idx.get(
+            surname=surname, name=name, misc_name=misc_name)
+    except SQLObjectNotFound:
+        return Author(surname=surname, name=name, misc_name=misc_name, count=0)
+
+
 def update_counters():
     for author in Author.select():
-        author.count = len(author.books)
+        author.count = AuthorBook.select(AuthorBook.q.author == author).count()
 
     for ext in Extension.select():
         ext.count = Book.select(Book.q.extension == ext.name).count()
 
     for genre in Genre.select():
-        genre.count = len(genre.books)
+        genre.count = BookGenre.select(BookGenre.q.genre == genre).count()
 
     for language in Language.select():
         language.count = Book.select(Book.q.language == language.name).count()