dump.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. for table_name, type, sql in schema_res.fetchall():
  27. if table_name == 'sqlite_sequence':
  28. yield('DELETE FROM "sqlite_sequence";')
  29. elif table_name == 'sqlite_stat1':
  30. yield('ANALYZE "sqlite_master";')
  31. elif table_name.startswith('sqlite_'):
  32. continue
  33. # NOTE: Virtual table support not implemented
  34. #elif sql.startswith('CREATE VIRTUAL TABLE'):
  35. # qtable = table_name.replace("'", "''")
  36. # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
  37. # "VALUES('table','{0}','{0}',0,'{1}');".format(
  38. # qtable,
  39. # sql.replace("''")))
  40. else:
  41. yield('{0};'.format(sql))
  42. # Build the insert statement for each row of the current table
  43. table_name_ident = table_name.replace('"', '""')
  44. res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
  45. column_names = [str(table_info[1]) for table_info in res.fetchall()]
  46. q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
  47. table_name_ident,
  48. ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
  49. query_res = cu.execute(q)
  50. for row in query_res:
  51. yield("{0};".format(row[0]))
  52. # Now when the type is 'index', 'trigger', or 'view'
  53. q = """
  54. SELECT "name", "type", "sql"
  55. FROM "sqlite_master"
  56. WHERE "sql" NOT NULL AND
  57. "type" IN ('index', 'trigger', 'view')
  58. """
  59. schema_res = cu.execute(q)
  60. for name, type, sql in schema_res.fetchall():
  61. yield('{0};'.format(sql))
  62. yield('COMMIT;')