3 __all__ = ['Author', 'Book', 'Extension', 'Genre', 'Language',
4 'init_db', 'insert_name',
8 from sqlobject import SQLObject, StringCol, UnicodeCol, IntCol, BoolCol, \
9 ForeignKey, DateCol, 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 books = RelatedJoin('Book', otherColumn='book_id')
60 class Book(SQLObject):
61 authors = RelatedJoin('Author')
62 genres = RelatedJoin('Genre')
71 extension = ForeignKey('Extension')
73 language = ForeignKey('Language')
76 class Extension(SQLObject):
77 name = StringCol(unique=True)
81 class Genre(SQLObject):
82 name = StringCol(unique=True)
85 books = RelatedJoin('Book', otherColumn='book_id')
88 class Language(SQLObject):
89 name = StringCol(unique=True)
96 except IndexError: # Table exists but is empty
98 except dberrors.Error:
99 for table in Author, Extension, Genre, Language, Book:
105 def insert_name(table, name):
107 return table.byName(name)
108 except SQLObjectNotFound:
109 return table(name=name, count=0)
113 print "DB dirs:", db_dirs
115 print "DB URI:", db_uri
117 if __name__ == '__main__':