dump.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Mimic the sqlite3 console shell's .dump command
  2. # Author: Paul Kippes <kippesp@gmail.com>
  3. def _iterdump(connection):
  4. """
  5. Returns an iterator to the dump of the database in an SQL text format.
  6. Used to produce an SQL dump of the database. Useful to save an in-memory
  7. database for later restoration. This function should not be called
  8. directly but instead called from the Connection method, iterdump().
  9. """
  10. cu = connection.cursor()
  11. yield('BEGIN TRANSACTION;')
  12. # sqlite_master table contains the SQL CREATE statements for the database.
  13. q = """
  14. SELECT name, type, sql
  15. FROM sqlite_master
  16. WHERE sql NOT NULL AND
  17. type == 'table'
  18. """
  19. schema_res = cu.execute(q)
  20. for table_name, type, sql in schema_res.fetchall():
  21. if table_name == 'sqlite_sequence':
  22. yield('DELETE FROM sqlite_sequence;')
  23. elif table_name == 'sqlite_stat1':
  24. yield('ANALYZE sqlite_master;')
  25. elif table_name.startswith('sqlite_'):
  26. continue
  27. # NOTE: Virtual table support not implemented
  28. #elif sql.startswith('CREATE VIRTUAL TABLE'):
  29. # qtable = table_name.replace("'", "''")
  30. # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
  31. # "VALUES('table','%s','%s',0,'%s');" %
  32. # qtable,
  33. # qtable,
  34. # sql.replace("''"))
  35. else:
  36. yield('%s;' % sql)
  37. # Build the insert statement for each row of the current table
  38. res = cu.execute("PRAGMA table_info('%s')" % table_name)
  39. column_names = [str(table_info[1]) for table_info in res.fetchall()]
  40. q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES("
  41. q += ",".join(["'||quote(" + col + ")||'" for col in column_names])
  42. q += ")' FROM '%(tbl_name)s'"
  43. query_res = cu.execute(q % {'tbl_name': table_name})
  44. for row in query_res:
  45. yield("%s;" % row[0])
  46. # Now when the type is 'index', 'trigger', or 'view'
  47. q = """
  48. SELECT name, type, sql
  49. FROM sqlite_master
  50. WHERE sql NOT NULL AND
  51. type IN ('index', 'trigger', 'view')
  52. """
  53. schema_res = cu.execute(q)
  54. for name, type, sql in schema_res.fetchall():
  55. yield('%s;' % sql)
  56. yield('COMMIT;')