~ubuntu-branches/ubuntu/maverick/yokadi/maverick

« back to all changes in this revision

Viewing changes to update/dump.py

  • Committer: Bazaar Package Importer
  • Author(s): Harald Sitter
  • Date: 2009-07-19 13:01:35 UTC
  • Revision ID: james.westby@ubuntu.com-20090719130135-eonczddb1s21ux1v
Tags: upstream-0.10.0
Import upstream version 0.10.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
 
3
"""
 
4
Generates a data-only sqlite dump, with insert statements including column
 
5
names.
 
6
 
 
7
@author: Aurélien Gâteau <aurelien.gateau@free.fr>
 
8
@license: GPLv3
 
9
"""
 
10
 
 
11
import os
 
12
import re
 
13
import subprocess
 
14
import sys
 
15
try:
 
16
    # Seems to be the Python 2.6 way to get sqlite
 
17
    from sqlite3 import dbapi2 as sqlite
 
18
except ImportError:
 
19
    from pysqlite2 import dbapi2 as sqlite
 
20
 
 
21
 
 
22
def getTableList(cx):
 
23
    cursor = cx.cursor()
 
24
    cursor.execute("select name from sqlite_master where type='table'")
 
25
    return [x[0] for x in cursor.fetchall()]
 
26
 
 
27
 
 
28
def getTableColumnList(cx, table):
 
29
    cursor = cx.cursor()
 
30
    cursor.execute("select * from %s" % table)
 
31
    return [x[0] for x in cursor.description]
 
32
 
 
33
 
 
34
def dumpTable(cx, dbFileName, table, fl):
 
35
    rx = re.compile(u"^insert into %s values" % table, re.IGNORECASE)
 
36
 
 
37
    columnList = getTableColumnList(cx, table)
 
38
    newText = u"insert into %s(%s) values" % (table, ",".join(columnList))
 
39
 
 
40
    child = subprocess.Popen(["sqlite3", dbFileName], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
 
41
    child.stdin.write(".mode insert %s\nselect * from %s;\n" % (table, table))
 
42
    child.stdin.close()
 
43
 
 
44
    for line in child.stdout.readlines():
 
45
        line = unicode(line, "utf-8")
 
46
        line = rx.sub(newText, line)
 
47
        fl.write(line.encode("utf-8"))
 
48
 
 
49
 
 
50
def dumpDatabase(dbFileName, dumpFile):
 
51
    cx = sqlite.connect(os.path.abspath(dbFileName))
 
52
    for table in getTableList(cx):
 
53
        dumpTable(cx, dbFileName, table, dumpFile)
 
54
 
 
55
 
 
56
def main():
 
57
    dbFileName = sys.argv[1]
 
58
    dumpFileName = sys.argv[2]
 
59
    dumpFile = file(dumpFileName, "w")
 
60
    dumpDatabase(dbFileName, dumpFile)
 
61
 
 
62
 
 
63
if __name__ == "__main__":
 
64
    main()
 
65
# vi: ts=4 sw=4 et