| 1 |
import contextlib |
| 2 |
import os |
| 3 |
import sqlite3 |
| 4 |
import warnings |
| 5 |
from io import BytesIO |
| 6 |
from shutil import copyfileobj |
| 7 |
from tempfile import NamedTemporaryFile, SpooledTemporaryFile |
| 8 |
|
| 9 |
from django.db import IntegrityError, OperationalError |
| 10 |
|
| 11 |
from dbbackup.db.base import BaseDBConnector |
| 12 |
|
| 13 |
DUMP_TABLES = """ |
| 14 |
SELECT "name", "type", "sql" |
| 15 |
FROM "sqlite_master" |
| 16 |
WHERE "sql" NOT NULL AND "type" == 'table' |
| 17 |
ORDER BY "name" |
| 18 |
""" |
| 19 |
DUMP_ETC = """ |
| 20 |
SELECT "name", "type", "sql" |
| 21 |
FROM "sqlite_master" |
| 22 |
WHERE "sql" NOT NULL AND "type" IN ('index', 'trigger', 'view') |
| 23 |
""" |
| 24 |
|
| 25 |
|
| 26 |
class SqliteConnector(BaseDBConnector): |
| 27 |
""" |
| 28 |
Create a dump at SQL layer like could make ``.dumps`` in sqlite3. |
| 29 |
Restore by evaluate the created SQL. |
| 30 |
""" |
| 31 |
|
| 32 |
def _write_dump(self, fileobj): |
| 33 |
cursor = self.connection.cursor() |
| 34 |
cursor.execute(DUMP_TABLES) |
| 35 |
for table_name, _, sql in cursor.fetchall(): |
| 36 |
if table_name.startswith("sqlite_") or table_name in self.exclude: |
| 37 |
continue |
| 38 |
if sql.startswith("CREATE TABLE"): |
| 39 |
sql = sql.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS") |
| 40 |
# Make SQL commands in 1 line |
| 41 |
sql = sql.replace("\n ", "") |
| 42 |
sql = sql.replace("\n)", ")") |
| 43 |
fileobj.write(f"{sql};\n".encode()) |
| 44 |
|
| 45 |
table_name_ident = table_name.replace('"', '""') |
| 46 |
cursor.execute(f'PRAGMA table_info("{table_name_ident}")') |
| 47 |
column_names = [str(table_info[1]) for table_info in cursor.fetchall()] |
| 48 |
q = """SELECT 'INSERT OR REPLACE INTO "{0}" VALUES({1})' FROM "{0}";\n""".format( |
| 49 |
table_name_ident, |
| 50 |
",".join(f"""'||quote("{col.replace('"', '""')}")||'""" for col in column_names), |
| 51 |
) |
| 52 |
cursor.execute(q) |
| 53 |
for row in cursor: |
| 54 |
fileobj.write(f"{row[0]};\n".encode()) |
| 55 |
|
| 56 |
# Dump indexes, triggers, and views after all tables are created |
| 57 |
cursor.execute(DUMP_ETC) |
| 58 |
for _name, _, sql in cursor.fetchall(): |
| 59 |
if sql.startswith("CREATE INDEX"): |
| 60 |
sql = sql.replace("CREATE INDEX", "CREATE INDEX IF NOT EXISTS", 1) |
| 61 |
elif sql.startswith("CREATE TRIGGER"): |
| 62 |
sql = sql.replace("CREATE TRIGGER", "CREATE TRIGGER IF NOT EXISTS", 1) |
| 63 |
elif sql.startswith("CREATE VIEW"): |
| 64 |
sql = sql.replace("CREATE VIEW", "CREATE VIEW IF NOT EXISTS", 1) |
| 65 |
fileobj.write(f"{sql};\n".encode()) |
| 66 |
cursor.close() |
| 67 |
|
| 68 |
def create_dump(self): |
| 69 |
if not self.connection.is_usable(): |
| 70 |
self.connection.connect() |
| 71 |
dump_file = SpooledTemporaryFile(max_size=10 * 1024 * 1024) |
| 72 |
self._write_dump(dump_file) |
| 73 |
dump_file.seek(0) |
| 74 |
return dump_file |
| 75 |
|
| 76 |
def _is_sql_command_complete(self, sql_command_bytes): |
| 77 |
""" |
| 78 |
Check if an SQL command is complete by ensuring that any closing ");\n" |
| 79 |
is not within a quoted string literal. |
| 80 |
""" |
| 81 |
sql_str = sql_command_bytes.decode("UTF-8") |
| 82 |
if not sql_str.endswith(");\n"): |
| 83 |
return False |
| 84 |
|
| 85 |
# Parse the SQL to check if we're inside a quoted string at the end |
| 86 |
in_quotes = False |
| 87 |
i = 0 |
| 88 |
while i < len(sql_str) - 3: # -3 to avoid checking the final ");\n" |
| 89 |
char = sql_str[i] |
| 90 |
if char == "'": |
| 91 |
if i + 1 < len(sql_str) and sql_str[i + 1] == "'": |
| 92 |
# Escaped single quote (''), skip both |
| 93 |
i += 2 |
| 94 |
else: |
| 95 |
# Toggle quote state |
| 96 |
in_quotes = not in_quotes |
| 97 |
i += 1 |
| 98 |
else: |
| 99 |
i += 1 |
| 100 |
|
| 101 |
# The command is complete if we're not inside quotes when we reach ");\n" |
| 102 |
return not in_quotes |
| 103 |
|
| 104 |
def restore_dump(self, dump): |
| 105 |
if not self.connection.is_usable(): |
| 106 |
self.connection.connect() |
| 107 |
cursor = self.connection.cursor() |
| 108 |
sql_command = b"" |
| 109 |
sql_is_complete = True |
| 110 |
for line in dump.readlines(): |
| 111 |
sql_command = sql_command + line |
| 112 |
line_str = line.decode("UTF-8") |
| 113 |
if line_str.startswith("INSERT") and not line_str.endswith(");\n"): |
| 114 |
sql_is_complete = False |
| 115 |
continue |
| 116 |
if not sql_is_complete: |
| 117 |
# Check if the accumulated command is now complete |
| 118 |
sql_is_complete = self._is_sql_command_complete(sql_command) |
| 119 |
|
| 120 |
if sql_is_complete: |
| 121 |
try: |
| 122 |
cursor.execute(sql_command.decode("UTF-8")) |
| 123 |
except (OperationalError, IntegrityError) as err: |
| 124 |
err_str = str(err) |
| 125 |
if not self._should_suppress_error(err_str): |
| 126 |
warnings.warn(f"Error in db restore: {err}") |
| 127 |
|
| 128 |
sql_command = b"" |
| 129 |
|
| 130 |
@staticmethod |
| 131 |
def _should_suppress_error(msg: str): |
| 132 |
return (msg.startswith(("index", "trigger", "view"))) and msg.endswith("already exists") |
| 133 |
|
| 134 |
|
| 135 |
class SqliteCPConnector(BaseDBConnector): |
| 136 |
""" |
| 137 |
Create a dump by copy the binary data file. |
| 138 |
Restore by simply copy to the good location. |
| 139 |
""" |
| 140 |
|
| 141 |
def create_dump(self): |
| 142 |
path = self.connection.settings_dict["NAME"] |
| 143 |
dump = BytesIO() |
| 144 |
with open(path, "rb") as db_file: |
| 145 |
copyfileobj(db_file, dump) |
| 146 |
dump.seek(0) |
| 147 |
return dump |
| 148 |
|
| 149 |
def restore_dump(self, dump): |
| 150 |
path = self.connection.settings_dict["NAME"] |
| 151 |
with open(path, "wb") as db_file: |
| 152 |
copyfileobj(dump, db_file) |
| 153 |
|
| 154 |
|
| 155 |
class SqliteBackupConnector(BaseDBConnector): |
| 156 |
""" |
| 157 |
Create a dump using the SQLite backup command, |
| 158 |
which is safe to execute when the database is |
| 159 |
in use (unlike simply copying the database file). |
| 160 |
Restore by copying the backup file over the |
| 161 |
database file. |
| 162 |
""" |
| 163 |
|
| 164 |
extension = "sqlite3" |
| 165 |
|
| 166 |
def _write_dump(self, fileobj): |
| 167 |
pass |
| 168 |
|
| 169 |
def create_dump(self): |
| 170 |
if not self.connection.is_usable(): |
| 171 |
self.connection.connect() |
| 172 |
# Important: ensure the connection to the DB |
| 173 |
# has been established. |
| 174 |
self.connection.ensure_connection() |
| 175 |
src_db_connection = self.connection.connection |
| 176 |
|
| 177 |
# On Windows sqlite3 cannot open a NamedTemporaryFile that is still |
| 178 |
# open by another handle. Use delete=False then reopen. |
| 179 |
bkp_db_file = NamedTemporaryFile(delete=False) |
| 180 |
bkp_path = bkp_db_file.name |
| 181 |
bkp_db_file.close() # Close so sqlite can open it on Windows. |
| 182 |
try: |
| 183 |
with sqlite3.connect(bkp_path) as bkp_db_connection: |
| 184 |
src_db_connection.backup(bkp_db_connection) |
| 185 |
with open(bkp_path, "rb") as reopened: |
| 186 |
spooled = SpooledTemporaryFile() |
| 187 |
copyfileobj(reopened, spooled) |
| 188 |
spooled.seek(0) |
| 189 |
return spooled |
| 190 |
finally: # pragma: no cover - cleanup best effort |
| 191 |
with contextlib.suppress(Exception): |
| 192 |
os.remove(bkp_path) |
| 193 |
|
| 194 |
def restore_dump(self, dump): |
| 195 |
path = self.connection.settings_dict["NAME"] |
| 196 |
with open(path, "wb") as db_file: |
| 197 |
copyfileobj(dump, db_file) |