]> git.phdru.name Git - xsetbg.git/blob - reload_db.py
Feat(reload_db): Update existing row if the full name was changed
[xsetbg.git] / reload_db.py
1 #! /usr/bin/env python
2 """Reload a dump into DB
3
4 This file is a part of XSetBg.
5
6 """
7
8 import sys
9 from sqlobject import SQLObjectNotFound
10 from sqlobject.sqlbuilder import Insert
11 from xsetbg_conf import xsetbg_conf
12 from xsetbg_db import recreate_db, SQLiteMassInsert
13
14
15 def convert_str(s):
16     if s == "None":
17         return None
18     else:
19         return int(float(s))
20
21
22 dump_file = open(sys.argv[1], 'r')
23 xsetbg_db = recreate_db()
24 count_new = count_old = count_updated = 0
25 fs_encoding = xsetbg_conf.get("images", "fs_encoding")
26
27 with SQLiteMassInsert() as txn:
28     for line in dump_file:
29         id, timestamp, filename = line.strip().split(None, 2)
30         id = convert_str(id)
31         timestamp = convert_str(timestamp)
32         filename = filename.decode(fs_encoding)
33         try:
34             if id:
35                 row = xsetbg_db.get(id)
36             else:
37                 row = xsetbg_db.byFull_name(filename)
38         except SQLObjectNotFound:
39             values = {'last_shown': timestamp,
40                       'full_name': filename.encode('utf-8')}
41             if id:
42                 values['id'] = id
43             query = txn.sqlrepr(Insert(xsetbg_db.sqlmeta.table, values=values))
44             txn.query(query)
45             count_new += 1
46         else:
47             assert id is None or row.id == id
48             if row.last_shown is not None:
49                 assert row.last_shown == timestamp
50             if row.full_name == filename:
51                 count_old += 1
52             else:
53                 row.full_name = filename
54                 count_updated += 1
55
56 dump_file.close()
57
58 print "New images:", count_new
59 print "Existing images:", count_old
60 print "Updated images:", count_updated