ยปCore Development>Code coverage>Lib/sqlite3/dump.py

Python code coverage for Lib/sqlite3/dump.py

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