3 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
4 'init_db', 'insert_name', 'update_counters',
8 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
9 ForeignKey, DateCol, DatabaseIndex, RelatedJoin, \
10 connectionForURI, sqlhub, SQLObjectNotFound, dberrors
11 from .config import ml_conf
14 db_uri = ml_conf.get('database', 'URI')
20 if 'XDG_CACHE_HOME' in os.environ:
21 db_dirs.append(os.environ['XDG_CACHE_HOME'])
22 home_cache = os.path.expanduser('~/.cache')
23 if home_cache not in db_dirs:
24 db_dirs.append(home_cache)
27 db_file = os.path.join(d, 'm_librarian.sqlite')
28 if os.path.exists(db_file):
32 # make the database file/directory readable/writeable only by the user
37 except OSError: # Perhaps already exists
39 db_file = os.path.join(db_dir, 'm_librarian.sqlite')
41 db_uri = 'sqlite://%s' % db_file.replace(os.sep, '/')
44 sqlhub.processConnection = connection = connectionForURI(db_uri)
46 if connection.dbName == 'sqlite':
47 # Speedup SQLite connection
48 connection.query("PRAGMA synchronous=OFF")
49 connection.query("PRAGMA count_changes=OFF")
50 connection.query("PRAGMA journal_mode=MEMORY")
51 connection.query("PRAGMA temp_store=MEMORY")
54 class Author(SQLObject):
55 name = UnicodeCol(unique=True)
57 count_idx = DatabaseIndex('count')
58 books = RelatedJoin('Book', otherColumn='book_id')
61 class Book(SQLObject):
62 authors = RelatedJoin('Author')
63 genres = RelatedJoin('Genre')
72 extension = ForeignKey('Extension')
74 language = ForeignKey('Language')
75 archive_file_idx = DatabaseIndex('archive', 'file', unique=True)
78 class Extension(SQLObject):
79 name = StringCol(unique=True)
81 count_idx = DatabaseIndex('count')
84 class Genre(SQLObject):
85 name = StringCol(unique=True)
88 count_idx = DatabaseIndex('count')
89 books = RelatedJoin('Book', otherColumn='book_id')
92 class Language(SQLObject):
93 name = StringCol(unique=True)
95 count_idx = DatabaseIndex('count')
101 except IndexError: # Table exists but is empty
103 except dberrors.Error:
104 for table in Author, Extension, Genre, Language, Book:
110 def insert_name(table, name, **kw):
112 return table.byName(name)
113 except SQLObjectNotFound:
114 return table(name=name, count=0, **kw)
117 def update_counters():
118 for author in Author.select():
119 author.count = len(author.books)
121 for ext in Extension.select():
122 ext.count = Book.select(Book.q.extension == ext.name).count()
124 for genre in Genre.select():
125 genre.count = len(genre.books)
127 for language in Language.select():
128 language.count = Book.select(Book.q.language == language.name).count()
132 print "DB dirs:", db_dirs
134 print "DB URI:", db_uri
136 if __name__ == '__main__':