dump.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. cu.row_factory = None # Make sure we get predictable results.
  18. yield('BEGIN TRANSACTION;')
  19. # sqlite_master table contains the SQL CREATE statements for the database.
  20. q = """
  21. SELECT "name", "type", "sql"
  22. FROM "sqlite_master"
  23. WHERE "sql" NOT NULL AND
  24. "type" == 'table'
  25. ORDER BY "name"
  26. """
  27. schema_res = cu.execute(q)
  28. sqlite_sequence = []
  29. for table_name, type, sql in schema_res.fetchall():
  30. if table_name == 'sqlite_sequence':
  31. rows = cu.execute('SELECT * FROM "sqlite_sequence";').fetchall()
  32. sqlite_sequence = ['DELETE FROM "sqlite_sequence"']
  33. sqlite_sequence += [
  34. f'INSERT INTO "sqlite_sequence" VALUES(\'{row[0]}\',{row[1]})'
  35. for row in rows
  36. ]
  37. continue
  38. elif table_name == 'sqlite_stat1':
  39. yield('ANALYZE "sqlite_master";')
  40. elif table_name.startswith('sqlite_'):
  41. continue
  42. elif sql.startswith('CREATE VIRTUAL TABLE'):
  43. if not writeable_schema:
  44. writeable_schema = True
  45. yield('PRAGMA writable_schema=ON;')
  46. yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  47. "VALUES('table','{0}','{0}',0,'{1}');".format(
  48. table_name.replace("'", "''"),
  49. sql.replace("'", "''"),
  50. ))
  51. else:
  52. yield('{0};'.format(sql))
  53. # Build the insert statement for each row of the current table
  54. table_name_ident = table_name.replace('"', '""')
  55. res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
  56. column_names = [str(table_info[1]) for table_info in res.fetchall()]
  57. q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
  58. table_name_ident,
  59. ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
  60. query_res = cu.execute(q)
  61. for row in query_res:
  62. yield("{0};".format(row[0]))
  63. # Now when the type is 'index', 'trigger', or 'view'
  64. q = """
  65. SELECT "name", "type", "sql"
  66. FROM "sqlite_master"
  67. WHERE "sql" NOT NULL AND
  68. "type" IN ('index', 'trigger', 'view')
  69. """
  70. schema_res = cu.execute(q)
  71. for name, type, sql in schema_res.fetchall():
  72. yield('{0};'.format(sql))
  73. if writeable_schema:
  74. yield('PRAGMA writable_schema=OFF;')
  75. # gh-79009: Yield statements concerning the sqlite_sequence table at the
  76. # end of the transaction.
  77. for row in sqlite_sequence:
  78. yield('{0};'.format(row))
  79. yield('COMMIT;')