Debian Codegraph @

dbbackup/db/django.py

raw
1 """
2 Django native serializer connector for database backup and restore.
3
4 This connector uses Django's built-in dumpdata and loaddata commands
5 for database-agnostic backup and restore operations. It works with
6 any Django-supported database backend.
7 """
8
9 import codecs
10 import contextlib
11 import os
12 import tempfile
13 from tempfile import SpooledTemporaryFile
14
15 from django.core.management import call_command
16
17 from dbbackup.db.base import BaseDBConnector
18
19
20 class DjangoConnector(BaseDBConnector):
21 """
22 Django native connector that uses dumpdata/loaddata commands.
23
24 This connector provides database-agnostic backup and restore functionality
25 by leveraging Django's built-in serialization system. It supports any
26 database backend that Django supports and handles model-level backups
27 with proper foreign key relationships preserved.
28 """
29
30 extension = "json"
31
32 def _create_dump(self):
33 """
34 Create a database dump using Django's dumpdata command.
35
36 Returns a file-like object containing the serialized database data
37 in JSON format.
38 """
39
40 binary_dump_file = SpooledTemporaryFile(mode="w+b")
41
42 # Wrap Binary SpooledTemporaryFile in text mode for direct use with dumpdata
43 dump_file = codecs.getwriter("utf-8")(binary_dump_file)
44
45 # Prepare arguments for dumpdata command
46 dump_args = []
47 dump_kwargs = {
48 "format": "json",
49 "stdout": dump_file,
50 "verbosity": 0,
51 "use_natural_foreign_keys": True,
52 "use_natural_primary_keys": True,
53 }
54
55 # Handle exclude parameter if specified
56 if self.exclude:
57 exclude_list = []
58 for item in self.exclude:
59 if "." in item:
60 # Already in app.model format - validate it exists before adding
61 # Skip invalid app.model combinations silently
62 # This allows for graceful handling of non-existent models
63 with contextlib.suppress(LookupError, ValueError):
64 from django.apps import apps
65
66 app_label, model_name = item.split(".", 1)
67 apps.get_model(app_label, model_name)
68 exclude_list.append(item)
69 else:
70 # Handle table name format - convert only well-known Django patterns
71 # For unknown table names, skip them rather than risk errors
72 converted = None
73 if item.startswith("auth_"):
74 # Handle Django auth tables (only if auth app is available)
75 with contextlib.suppress(LookupError):
76 from django.apps import apps
77
78 apps.get_app_config("auth") # Check if auth app exists
79 model_name = item[5:] # Remove 'auth_' prefix
80 if model_name == "group":
81 converted = "auth.Group"
82 elif model_name == "permission":
83 converted = "auth.Permission"
84 elif model_name == "user":
85 converted = "auth.User"
86 elif item.startswith("django_"):
87 # Handle Django internal tables (only if apps are available)
88 model_name = item[7:] # Remove 'django_' prefix
89 # Required app not installed, skip
90 with contextlib.suppress(LookupError):
91 from django.apps import apps
92
93 if model_name == "admin_log":
94 apps.get_app_config("admin")
95 converted = "admin.LogEntry"
96 elif model_name == "content_type":
97 apps.get_app_config("contenttypes")
98 converted = "contenttypes.ContentType"
99 elif model_name == "session":
100 apps.get_app_config("sessions")
101 converted = "sessions.Session"
102 # Only add converted names that we're confident about
103 # For unknown table names, we skip them to avoid Django validation errors
104 # This is safer than trying to guess the correct app.model format
105 if converted:
106 exclude_list.append(converted)
107
108 if exclude_list:
109 dump_kwargs["exclude"] = exclude_list
110
111 # Run dumpdata command - this streams directly to the text file
112 call_command("dumpdata", *dump_args, **dump_kwargs)
113
114 # Reset file position to beginning for reading
115 binary_dump_file.seek(0)
116 return binary_dump_file
117
118 def _restore_dump(self, dump):
119 """
120 Restore a database dump using Django's loaddata command.
121
122 Args:
123 dump: File-like object containing JSON fixture data
124 """
125 # Create a temporary file for loaddata to read from
126 with tempfile.NamedTemporaryFile(mode="w+t", suffix=".json", encoding="utf-8", delete=False) as temp_file:
127 # Stream copy dump content to temporary file to avoid loading everything into memory
128 dump.seek(0)
129 # Use chunked reading for memory efficiency
130 while True:
131 chunk = dump.read(8192) # 8KB chunks
132 if not chunk:
133 break
134 if isinstance(chunk, bytes):
135 chunk = chunk.decode("utf-8")
136 temp_file.write(chunk)
137 temp_file_path = temp_file.name
138
139 try:
140 # Run loaddata command
141 call_command("loaddata", temp_file_path, verbosity=0)
142 finally:
143 # Best effort clean-up of temporary file
144 with contextlib.suppress(OSError):
145 os.unlink(temp_file_path)