You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.7 KiB

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