Initial commit
[wl-mobile.git] / initial / initdb.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 import sqlite3
5 import simplejson as j
6
7 add_book = "INSERT INTO book (id, title, html_file, html_file_size, parent, parent_number) VALUES (:id, :title, :html, :html_size, :parent, :parent_number);"
8 add_book_tag = "INSERT INTO book_tag (book, tag) VALUES (:book, :tag);"
9 add_tag = "INSERT INTO tag (id, category, name, sort_key, _books) VALUES (:id, :category, :name, :sort_key, :_books);"
10
11
12
13 dbs = sqlite3.connect('Databases.db')
14 dbs.executescript("""
15 CREATE TABLE Databases (guid INTEGER PRIMARY KEY AUTOINCREMENT, origin TEXT, name TEXT, displayName TEXT, estimatedSize INTEGER, path TEXT);
16 CREATE TABLE Origins (origin TEXT UNIQUE ON CONFLICT REPLACE, quota INTEGER NOT NULL ON CONFLICT FAIL);
17 INSERT INTO Databases VALUES (1, 'file__0', 'wolnelektury', 'Wolne Lektury', 500000, '0000000000000001.db');
18 INSERT INTO Origins Values ('file__0', 1000000);
19 """)
20 dbs.commit()
21 dbs.close()
22
23
24
25 db1 = sqlite3.connect('wolnelektury.db')
26 db2 = sqlite3.connect('0000000000000001.db')
27
28 categories = {'author': 'autor',
29               'epoch': 'epoka', 
30               'genre': 'gatunek', 
31               'kind': 'rodzaj', 
32               'theme': 'motyw'
33               }
34
35 schema = """
36 CREATE TABLE book (
37     id INTEGER PRIMARY KEY, 
38     title VARCHAR, 
39     html_file VARCHAR, 
40     html_file_size INTEGER, 
41     parent INTEGER,
42     parent_number INTEGER
43     );
44 CREATE INDEX IF NOT EXISTS book_title_index ON book (title);
45 CREATE INDEX IF NOT EXISTS book_parent_index ON book (parent);
46
47 CREATE TABLE tag (
48     id INTEGER PRIMARY KEY, 
49     name VARCHAR, 
50     category VARCHAR, 
51     sort_key VARCHAR, 
52     _books VARCHAR);
53 CREATE INDEX IF NOT EXISTS tag_name_index ON tag (name);
54 CREATE INDEX IF NOT EXISTS tag_category_index ON tag (category);
55 CREATE INDEX IF NOT EXISTS tag_sort_key_index ON tag (sort_key);
56
57 CREATE TABLE book_tag (book INTEGER, tag INTEGER);
58 CREATE INDEX IF NOT EXISTS book_tag_book ON book_tag (book);
59 CREATE INDEX IF NOT EXISTS book_tag_tag_index ON book_tag (tag);
60 """
61
62 db1.executescript(schema)
63 db2.executescript(schema)
64
65
66 def utf8ize(d):
67     """ Convert every unicode field of d to unicode consisting
68         of its utf-8 representation bytes as characters.
69         Yes, this is weird and stupid, but it's what Android does."""
70
71     for f in d:
72         if isinstance(d[f], unicode):
73             d[f] = d[f].encode('utf-8').decode('latin1')
74
75 with open('initial.json') as f:
76     data = j.load(f)
77
78 books_by_id = {}
79 tagged = {}
80
81 for book in data['added']['books']:
82     books_by_id[book['id']] = book
83
84 for book in data['added']['books']:
85     # gather parents' tags
86     parental = []
87     b = book
88     while 'parent' in b:
89         b = books_by_id[b['parent']]
90         parental += b['tags']
91     parental = set(parental)
92
93     for tag in book['tags']:
94         if tag not in parental:
95             tagged.setdefault(tag, []).append(book)
96
97 del books_by_id
98
99
100 for book in data['added']['books']:
101     if 'html' not in book:
102         book['html'] = None
103     if 'html_size' not in book:
104         book['html_size'] = None
105     if 'parent' not in book:
106         book['parent'] = None
107     if 'parent_number' not in book:
108         book['parent_number'] = None
109     for t in book['tags']:
110         db1.execute(add_book_tag, {"book": book['id'], "tag": t})
111         db2.execute(add_book_tag, {"book": book['id'], "tag": t})
112
113     db2.execute(add_book, book)
114     utf8ize(book)
115     db1.execute(add_book, book)
116
117 for tag in data['added']['tags']:
118     tag['category'] = categories[tag['category']]
119     tag['_books'] = ",".join(str(book['id']) for book in sorted(tagged.get(tag['id'], []), key=lambda b: b['title']))
120
121     if tag['category'] == 'theme':
122         continue
123     
124     db2.execute(add_tag, tag)
125     utf8ize(tag)
126     db1.execute(add_tag, tag)
127
128
129 db1.commit()
130 db1.close()
131 db2.commit()
132 db2.close()