1 # Mimic the sqlite3 console shell's .dump command
2 # Author: Paul Kippes <kippesp@gmail.com>
4 # Every identifier in sql is quoted based on a comment in sqlite
5 # documentation "SQLite adds new keywords from time to time when it
6 # takes on new features. So to prevent your code from being broken by
7 # future enhancements, you should normally quote any identifier that
8 # is an English language word, even if you do not have to."
10 def _iterdump(connection):
12 Returns an iterator to the dump of the database in an SQL text format.
14 Used to produce an SQL dump of the database. Useful to save an in-memory
15 database for later restoration. This function should not be called
16 directly but instead called from the Connection method, iterdump().
19 cu = connection.cursor()
20 yield('BEGIN TRANSACTION;')
22 # sqlite_master table contains the SQL CREATE statements for the database.
24 SELECT "name", "type", "sql"
26 WHERE "sql" NOT NULL AND
29 schema_res = cu.execute(q)
30 for table_name, type, sql in sorted(schema_res.fetchall()):
31 if table_name == 'sqlite_sequence':
32 yield('DELETE FROM "sqlite_sequence";')
33 elif table_name == 'sqlite_stat1':
34 yield('ANALYZE "sqlite_master";')
35 elif table_name.startswith('sqlite_'):
37 # NOTE: Virtual table support not implemented
38 #elif sql.startswith('CREATE VIRTUAL TABLE'):
39 # qtable = table_name.replace("'", "''")
40 # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
41 # "VALUES('table','{0}','{0}',0,'{1}');".format(
45 yield('{0};'.format(sql))
47 # Build the insert statement for each row of the current table
48 table_name_ident = table_name.replace('"', '""')
49 res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
50 column_names = [str(table_info[1]) for table_info in res.fetchall()]
51 q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
53 ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
54 query_res = cu.execute(q)
56 yield("{0};".format(row[0]))
58 # Now when the type is 'index', 'trigger', or 'view'
60 SELECT "name", "type", "sql"
62 WHERE "sql" NOT NULL AND
63 "type" IN ('index', 'trigger', 'view')
65 schema_res = cu.execute(q)
66 for name, type, sql in schema_res.fetchall():
67 yield('{0};'.format(sql))