dump.py 3.4 KB

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