dump.py 3.2 KB

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