|
| 1 | +import sqlite3 |
1 | 2 | import warnings |
2 | 3 | from io import BytesIO |
3 | 4 | from shutil import copyfileobj |
4 | | -from tempfile import SpooledTemporaryFile |
| 5 | +from tempfile import SpooledTemporaryFile, NamedTemporaryFile |
5 | 6 |
|
6 | 7 | from django.db import IntegrityError, OperationalError |
7 | 8 |
|
@@ -108,3 +109,38 @@ def restore_dump(self, dump): |
108 | 109 | path = self.connection.settings_dict["NAME"] |
109 | 110 | with open(path, "wb") as db_file: |
110 | 111 | copyfileobj(dump, db_file) |
| 112 | + |
| 113 | + |
| 114 | +class SqliteBackupConnector(BaseDBConnector): |
| 115 | + """ |
| 116 | + Create a dump using the SQLite backup command, |
| 117 | + which is safe to execute when the database is |
| 118 | + in use (unlike simply copying the database file). |
| 119 | + Restore by copying the backup file over the |
| 120 | + database file. |
| 121 | + """ |
| 122 | + extension = 'sqlite3' |
| 123 | + |
| 124 | + def _write_dump(self, fileobj): |
| 125 | + pass |
| 126 | + |
| 127 | + def create_dump(self): |
| 128 | + if not self.connection.is_usable(): |
| 129 | + self.connection.connect() |
| 130 | + # Important: ensure the connection to the DB |
| 131 | + # has been established. |
| 132 | + self.connection.ensure_connection() |
| 133 | + src_db_connection = self.connection.connection |
| 134 | + |
| 135 | + bkp_db_file = NamedTemporaryFile() |
| 136 | + bkp_path = bkp_db_file.name |
| 137 | + with sqlite3.connect(bkp_path) as bkp_db_connection: |
| 138 | + src_db_connection.backup(bkp_db_connection) |
| 139 | + |
| 140 | + bkp_db_file.seek(0) |
| 141 | + return bkp_db_file |
| 142 | + |
| 143 | + def restore_dump(self, dump): |
| 144 | + path = self.connection.settings_dict["NAME"] |
| 145 | + with open(path, "wb") as db_file: |
| 146 | + copyfileobj(dump, db_file) |
0 commit comments