django-cloud-backup 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,273 @@
1
+ import base64
2
+ import datetime
3
+ import json
4
+ from functools import cached_property
5
+ from io import BytesIO
6
+
7
+ from ajax_helpers.mixins import AjaxHelpers, AjaxTaskMixin
8
+ from django.contrib.auth.mixins import PermissionRequiredMixin
9
+ from django.template.loader import render_to_string
10
+ from django.utils.safestring import mark_safe
11
+ from django_datatables.columns import DateTimeColumn, DatatableColumn, ColumnLink, ColumnBase
12
+ from django_datatables.datatables import DatatableView
13
+ from django_datatables.helpers import row_button, overwrite_cell
14
+ from django_menus.menu import MenuMixin
15
+ from django_modals.datatables import ModalLink
16
+ from django_modals.decorators import ConfirmAjaxMethod
17
+ from django_modals.helper import reverse_modal
18
+ from openpyxl import Workbook
19
+
20
+ from cloud_backup.backup import Backup
21
+ from .sql_functions import get_schemas, get_schema_tables, get_table_column_names, get_table_data
22
+ from .tasks import ajax_backup
23
+ from .utils import allowed_to_restore, RESTORE_BLOCKED_MESSAGE
24
+
25
+
26
+ def restore_table_button(text):
27
+ return ModalLink(row=True, base64=True, modal_name='cloud_backup:confirm_restore_db',
28
+ css_class='btn btn-danger btn-sm', title='Restore', button_text=text,
29
+ enabled=allowed_to_restore())
30
+
31
+
32
+ class TableBackup(AjaxTaskMixin, AjaxHelpers):
33
+
34
+ tasks = {'backup': ajax_backup}
35
+
36
+ @cached_property
37
+ def backup(self):
38
+ return Backup()
39
+
40
+ # noinspection PyUnresolvedReferences
41
+ def set_cell_commands(self, table_id, row_no, html):
42
+ self.setup_tables()
43
+ self.add_command(overwrite_cell(
44
+ self.tables[table_id], row_no, 'Backup', f'<span class="text-success">{html}</span>')
45
+ )
46
+
47
+ def row_backup_schema(self, *, row_no, table_id, **_kwargs):
48
+ self.set_cell_commands(table_id, row_no, '<div class="spinner-border spinner-border-sm"></div> Backing up')
49
+ if table_id == 'schema_tables':
50
+ if hasattr(self, 'schema'):
51
+ # noinspection PyUnresolvedReferences
52
+ task_kwargs = dict(schema=self.schema, table=row_no[1:])
53
+ else:
54
+ # noinspection PyUnresolvedReferences
55
+ task_kwargs = dict(schema=self.kwargs['schema'], table=row_no[1:])
56
+ else:
57
+ # noinspection PyUnresolvedReferences
58
+ task_kwargs = dict(schema=row_no[1:])
59
+ return self.start_task('backup', task_kwargs=task_kwargs, result_kwargs=dict(table_id=table_id, row_no=row_no))
60
+
61
+ def task_state_success(self, *, table_id, row_no, **_kwargs):
62
+ self.set_cell_commands(table_id, row_no, '<i class="fas fa-check-circle"></i> Backup Complete')
63
+ self.add_command('reload_table', table_id='files')
64
+ return self.command_response()
65
+
66
+
67
+ class BackupContentMixin:
68
+ """Renders the menus and datatables to a single HTML string in
69
+ context['backup_content'] using content_template, so the backup UI can be
70
+ embedded in a host project's own branded template. That template must still
71
+ include the ajax_helpers/datatables/modals libs and {{ ajax_helpers_script }}."""
72
+
73
+ content_template = 'cloud_backup/backup_content.html'
74
+
75
+ def render_to_response(self, context, **response_kwargs):
76
+ # with a single table (no trash on S3/Azure, one schema) DatatableView only
77
+ # sets the singular 'datatable' key, but the content template always uses
78
+ # 'datatables'
79
+ context['datatables'] = self.tables
80
+ context['backup_content'] = mark_safe(
81
+ render_to_string(self.content_template, context, request=self.request))
82
+ return super().render_to_response(context, **response_kwargs)
83
+
84
+
85
+ class BackupBaseView(BackupContentMixin, TableBackup, PermissionRequiredMixin, MenuMixin, DatatableView):
86
+
87
+ permission_required = 'access_admin'
88
+
89
+ def setup_menu(self):
90
+ self.add_menu('buttons', menu_type='buttons')
91
+ if self.schema:
92
+ self.add_menu('breadcrumbs', menu_type='breadcrumb').add_items(
93
+ ('cloud_backup:backup_info', 'backup'),
94
+ ('cloud_backup:schema_info', self.schema, {'url_args': [self.schema]}),
95
+ )
96
+ self.menus['buttons'].add_items(
97
+ (f'cloud_backup:confirm_backup,schema-{self.schema}', f'BACKUP {self.schema}'),
98
+ ('cloud_backup:schema_tables', 'View Tables', {'url_args': [self.schema]}),
99
+ )
100
+ else:
101
+ self.menus['buttons'].add_items(
102
+ ('cloud_backup:confirm_backup,-', 'Backup database'),
103
+ ('cloud_backup:confirm_backup,all_schemas-True', 'Backup All Schemas',
104
+ {'visible': len(self.schemas) > 1}),
105
+ (f'cloud_backup:schema_info,{self.schemas[0][0]}', f'View {self.schemas[0][0]}',
106
+ {'visible': len(self.schemas) == 1}),
107
+ ('cloud_backup:confirm_empty_trash', 'Empty Trash',
108
+ {'css_classes': 'btn btn-warning', 'visible': self.backup.storage.supports_trash}),
109
+ ('cloud_backup:confirm_drop_schema,-', 'Drop Public Schema',
110
+ {'css_classes': 'btn btn-danger', 'visible': allowed_to_restore()}),
111
+ )
112
+
113
+ # noinspection PyAttributeOutsideInit
114
+ def dispatch(self, request, *args, schema=None, **kwargs):
115
+ self.schema = schema
116
+ self.schemas = get_schemas()
117
+ return super().dispatch(request, *args, **kwargs)
118
+
119
+ def add_tables(self):
120
+ self.add_table('files')
121
+ if self.backup.storage.supports_trash:
122
+ self.add_table('deleted_files')
123
+ if not self.schema and len(self.schemas) > 1:
124
+ self.add_table('schemas')
125
+
126
+ @staticmethod
127
+ def setup_files(table):
128
+ table.add_columns('.id', 'ip_address', 'table', 'name', 'size',
129
+ DateTimeColumn(title='Backup Date', field='created'),
130
+ DatatableColumn(column_name='drop_restore', enabled=allowed_to_restore(),
131
+ render=[row_button('drop_restore', 'Drop Restore',
132
+ button_classes='btn btn-warning btn-sm',)]),
133
+ restore_table_button('Restore DB'))
134
+ table.sort('-created')
135
+ table.table_options['stateSave'] = False
136
+
137
+ @ConfirmAjaxMethod(message='This will overwrite the current database and data could be lost')
138
+ def row_drop_restore(self, row_data, **_kwargs):
139
+ if not allowed_to_restore():
140
+ return self.command_response('message', text=RESTORE_BLOCKED_MESSAGE)
141
+ table_row = json.loads(row_data)
142
+ return self.command_response('show_modal',
143
+ modal=reverse_modal('cloud_backup:restore_db'
144
+ ,base64={'pk': table_row[0], 'drop_schema': 'public'}))
145
+
146
+ @staticmethod
147
+ def setup_deleted_files(table):
148
+ table.add_columns('.id', 'name', 'size', DateTimeColumn(title='Backup Date', field='created'),
149
+ DatatableColumn(column_name='Undelete', render=[row_button(
150
+ 'undelete', 'Undelete', button_classes='btn btn-secondary btn-sm'
151
+ )]))
152
+ table.sort('-created')
153
+ table.table_options['stateSave'] = False
154
+
155
+ def row_undelete(self, row_no, **_kwargs):
156
+ self.backup.storage.restore_deleted(row_no[1:])
157
+ return self.command_response('reload')
158
+
159
+ def setup_schemas(self, table):
160
+ table.add_columns(
161
+ 'schema', 'size',
162
+ ColumnLink(
163
+ column_name='view_schema', link_ref_column='schema', url_name='cloud_backup:schema_info',
164
+ link_html='<button class="btn btn-sm btn-outline-dark">VIEW</button>'
165
+ ),
166
+ ColumnBase(column_name='Backup',
167
+ render=[row_button('backup_schema', 'Backup', button_classes='btn btn-success btn-sm',)])
168
+ )
169
+ table.table_data = [{'schema': s[0], 'size': s[1]} for s in self.schemas]
170
+ table.table_options['column_id'] = 0
171
+ table.sort('schema')
172
+ table.table_options['stateSave'] = False
173
+
174
+ def get_context_data(self, **kwargs):
175
+ self.add_page_command('ajax_post', data={'ajax': 'read_storage_info'})
176
+ context = super().get_context_data(**kwargs)
177
+ context['schema'] = self.schema
178
+ return context
179
+
180
+ def ajax_read_storage_info(self, **_kwargs):
181
+ db = self.backup.get_backup_db(schema=self.schema)
182
+ info = db.storage.storage_info(db.base_backup_dir)
183
+ if info['web_link']:
184
+ location = '<a target="_blank" href="{}">{}</a>'.format(info['web_link'], info['name'])
185
+ else:
186
+ location = info['name']
187
+ html = f'Backup Folder {location}'
188
+ if info['used'] is not None and info['limit'] is not None:
189
+ gb = 1024 * 1024 * 1024
190
+ html += '<br>{:.1f} GB Used of {:.1f} GB'.format(info['used'] / gb, info['limit'] / gb)
191
+ badge_colours = {'Enabled': 'success', 'Disabled': 'danger', 'Suspended': 'warning'}
192
+ for p in db.storage.protection_info():
193
+ colour = badge_colours.get(p['status'], 'secondary')
194
+ html += f'<br>{p["label"]} <span class="badge badge-{colour}">{p["status"]}</span>'
195
+ if p.get('detail'):
196
+ html += f' <small class="text-muted">{p["detail"]}</small>'
197
+ return self.command_response('html', selector='#storage_info', html=html)
198
+
199
+ def get_table_query(self, table, **kwargs):
200
+ files = self.backup.get_backup_db(schema=self.schema).get_db_backup_files(
201
+ deleted=table.table_id != 'files')
202
+ return [dict(**f, **f.get('metadata', {})) for f in files if not f.get('metadata', {}).get('table')]
203
+
204
+
205
+ class BackupView(BackupBaseView):
206
+
207
+ template_name = 'cloud_backup/backup.html'
208
+
209
+
210
+ class SchemaTableBaseView(BackupContentMixin, TableBackup, PermissionRequiredMixin, MenuMixin, DatatableView):
211
+
212
+ permission_required = 'access_admin'
213
+
214
+ def setup_menu(self):
215
+ self.add_menu('breadcrumbs', menu_type='breadcrumb').add_items(
216
+ ('cloud_backup:backup_info', 'backup'),
217
+ ('cloud_backup:schema_info', self.kwargs['schema'], {'url_args': [self.kwargs['schema']]}),
218
+ ('cloud_backup:schema_tables', 'tables', {'url_args': [self.kwargs['schema']]}),
219
+ )
220
+
221
+ def add_tables(self):
222
+ self.add_table('files')
223
+ self.add_table('schema_tables')
224
+
225
+ @staticmethod
226
+ def setup_files(table):
227
+ table.add_columns('.id', 'ip_address', 'table', 'name', 'size',
228
+ DateTimeColumn(title='Backup Date', field='created'),
229
+ restore_table_button('Restore Table'))
230
+ table.sort('-created')
231
+ table.table_options['stateSave'] = False
232
+
233
+ def row_download_xls(self, **kwargs):
234
+ workbook = Workbook()
235
+ sheet = workbook.active
236
+ sheet.append(get_table_column_names(self.kwargs['schema'], table_name=kwargs['row_no'][1:]))
237
+ for r in get_table_data(self.kwargs['schema'], table_name=kwargs['row_no'][1:]):
238
+ sheet.append([c.replace(tzinfo=None) if isinstance(c, datetime.datetime) else c for c in r])
239
+ output = BytesIO()
240
+ workbook.save(output)
241
+ output.seek(0)
242
+ filename = f'{kwargs["row_no"][1:]}.xlsx'
243
+ return self.command_response('save_file', data=base64.b64encode(output.read()).decode('ascii'),
244
+ filename=filename)
245
+
246
+ def setup_schema_tables(self, table):
247
+ table.add_columns(
248
+ 'table', 'size', ('rows', {'title': 'No. Rows (Approx)'}),
249
+ ColumnBase(column_name='Download',
250
+ render=[row_button('download_xls', '<i class="far fa-file-excel"></i>',
251
+ button_classes='btn btn-outline-secondary btn-sm', )]),
252
+ ColumnBase(column_name='Backup',
253
+ render=[row_button('backup_schema', 'Backup', button_classes='btn btn-success btn-sm', )])
254
+ )
255
+ table.table_data = [{'table': s[0], 'size': s[1], 'rows': s[2]}
256
+ for s in get_schema_tables(self.kwargs['schema'])]
257
+ table.table_options['column_id'] = 0
258
+ table.sort('table')
259
+ table.table_options['stateSave'] = False
260
+
261
+ def get_context_data(self, **kwargs):
262
+ context = super().get_context_data(**kwargs)
263
+ context['schema'] = self.kwargs['schema']
264
+ return context
265
+
266
+ def get_table_query(self, table, **kwargs):
267
+ files = self.backup.get_backup_db(schema=self.kwargs.get('schema')).get_db_backup_files()
268
+ return [dict(**f, **f['metadata']) for f in files if f.get('metadata', {}).get('table')]
269
+
270
+
271
+ class SchemaTableView(SchemaTableBaseView):
272
+
273
+ template_name = 'cloud_backup/backup.html'
File without changes
File without changes
@@ -0,0 +1,77 @@
1
+ from django.core.management.base import BaseCommand
2
+
3
+ from cloud_backup.backup import Backup
4
+
5
+
6
+ class Logger:
7
+ @staticmethod
8
+ def info(text):
9
+ print(text)
10
+
11
+ @staticmethod
12
+ def warning(text):
13
+ print('WARNING: ' + text)
14
+
15
+ @staticmethod
16
+ def error(text):
17
+ print('ERROR: ' + text)
18
+
19
+
20
+ class Command(BaseCommand):
21
+
22
+ def add_arguments(self, parser):
23
+ parser.add_argument('--schema',
24
+ nargs='?',
25
+ help='Specifies which schema to backup')
26
+
27
+ parser.add_argument('--table',
28
+ nargs='?',
29
+ help='Specifies which table to backup. Must also include schema.')
30
+
31
+ parser.add_argument('--all_schemas',
32
+ action='store_true',
33
+ default=False)
34
+
35
+ parser.add_argument('--db_only',
36
+ action='store_true',
37
+ default=False)
38
+
39
+ parser.add_argument('--s3_folders_only',
40
+ action='store_true',
41
+ default=False)
42
+
43
+ parser.add_argument('--folders_only',
44
+ action='store_true',
45
+ default=False)
46
+
47
+ parser.add_argument('-sub_folder',
48
+ type=str)
49
+
50
+ parser.add_argument('--extend_retention',
51
+ action='store_true',
52
+ default=False,
53
+ help='Extend object-lock retention on existing backups instead of backing up')
54
+
55
+ parser.add_argument('--config',
56
+ type=str,
57
+ help='Which BACKUP_CONFIGS entry to use (default: the default config)')
58
+
59
+ def handle(self, *args, **options):
60
+ if options['extend_retention']:
61
+ Backup(logger=Logger(), config=options['config']).extend_file_retention()
62
+ return
63
+ folder_kwargs = {}
64
+ if options['db_only']:
65
+ folder_kwargs['include_folders'] = False
66
+ folder_kwargs['include_s3_folders'] = False
67
+ elif options['s3_folders_only']:
68
+ folder_kwargs['include_db'] = False
69
+ folder_kwargs['include_folders'] = False
70
+ elif options['folders_only']:
71
+ folder_kwargs['include_db'] = False
72
+ folder_kwargs['include_s3_folders'] = False
73
+ Backup(logger=Logger(), config=options['config']).backup_db_and_folders(all_schemas=options['all_schemas'],
74
+ schema=options['schema'],
75
+ table=options['table'],
76
+ sub_folder=options['sub_folder'],
77
+ **folder_kwargs)
@@ -0,0 +1,23 @@
1
+ from django.core.management.base import BaseCommand
2
+ from ...backup import Backup
3
+
4
+
5
+ class Command(BaseCommand):
6
+
7
+ def add_arguments(self, parser):
8
+ parser.add_argument('--local_file', type=str)
9
+ parser.add_argument('--schema', type=str)
10
+ parser.add_argument('--config', type=str,
11
+ help='Which BACKUP_CONFIGS entry to restore from (default: the default config)')
12
+
13
+ def handle(self, *args, **options):
14
+ db = Backup(config=options['config']).get_backup_db(schema=options['schema'])
15
+ if options['local_file'] is not None:
16
+ db.postgres_backup.restore_db(options['local_file'])
17
+ else:
18
+ latest_db = db.get_latest_db_backup()
19
+ print('Found: ' + latest_db['name'])
20
+ confirm = input('Do you want to restore which will overwrite current database (yes/no)? ')
21
+ if confirm.lower() == 'yes':
22
+ print('Restoring..')
23
+ db.restore_db_from_storage(file_id=latest_db['id'])
cloud_backup/modals.py ADDED
@@ -0,0 +1,107 @@
1
+ import json
2
+
3
+ from django.contrib.auth.mixins import UserPassesTestMixin
4
+ from django.db import connection
5
+ from django_modals.helper import modal_button, ajax_modal_redirect, modal_button_method
6
+ from django_modals.modals import Modal
7
+ from django_modals.task_modals import TaskModal
8
+ from ajax_helpers.utils import is_ajax
9
+
10
+ from cloud_backup.backup import Backup
11
+ from cloud_backup.utils import allowed_to_restore, RESTORE_BLOCKED_MESSAGE
12
+
13
+
14
+ class SuperUserMixin(UserPassesTestMixin):
15
+ def test_func(self):
16
+ return self.request.user.is_superuser
17
+
18
+
19
+ class RestoreAllowedMixin(SuperUserMixin):
20
+ """Server-side enforcement of BACKUP_ALLOW_RESTORE — hiding the buttons is not enough."""
21
+
22
+ def dispatch(self, request, *args, **kwargs):
23
+ if not allowed_to_restore():
24
+ return self.command_response('message', text=RESTORE_BLOCKED_MESSAGE)
25
+ return super().dispatch(request, *args, **kwargs)
26
+
27
+
28
+ class ConfirmRestoreModal(RestoreAllowedMixin, Modal):
29
+
30
+ modal_title = 'Warning'
31
+
32
+ def get_modal_buttons(self):
33
+ return [
34
+ modal_button('Confirm', ajax_modal_redirect(
35
+ 'cloud_backup:restore_db', base64={'pk': self.slug['base64'][0]}
36
+ ), 'btn-danger'),
37
+ modal_button('Cancel', 'close', 'btn-secondary')
38
+ ]
39
+
40
+ def modal_content(self):
41
+ return 'This will overwrite the current database and data could be lost.'
42
+
43
+
44
+ class ConfirmBackupModal(SuperUserMixin, Modal):
45
+
46
+ modal_title = 'Warning'
47
+
48
+ def get_modal_buttons(self):
49
+ return [
50
+ modal_button('Yes', ajax_modal_redirect('cloud_backup:django_backup', slug=self.kwargs['slug']),
51
+ 'btn-warning'),
52
+ modal_button('Cancel', 'close', 'btn-secondary')
53
+ ]
54
+
55
+ def modal_content(self):
56
+ return 'Are you sure you want to backup?'
57
+
58
+
59
+ class SuperUserTaskModal(SuperUserMixin, TaskModal):
60
+ refresh_ms = 500
61
+
62
+ def dispatch(self, request, *args, **kwargs):
63
+ if is_ajax(request) and request.content_type == 'application/json':
64
+ response = json.loads(request.body)
65
+ if response.get('ajax') == 'check_result':
66
+ self.test_func = lambda: True
67
+ return super().dispatch(request, *args, **kwargs)
68
+
69
+
70
+ class RestoreTaskModal(RestoreAllowedMixin, SuperUserTaskModal):
71
+ pass
72
+
73
+
74
+ class ConfirmEmptyTrashModal(SuperUserMixin, Modal):
75
+
76
+ modal_title = 'Warning'
77
+
78
+ def modal_content(self):
79
+ return 'Are you sure you want to permanently remove deleted items?'
80
+
81
+ def button_empty_trash(self, **_kwargs):
82
+ Backup().storage.empty_trash()
83
+ return self.command_response('reload')
84
+
85
+ def get_modal_buttons(self):
86
+ return [modal_button_method('Confirm', 'empty_trash'),
87
+ modal_button('Cancel', 'close', 'btn-secondary')]
88
+
89
+
90
+ class ConfirmDropSchemaModal(RestoreAllowedMixin, Modal):
91
+
92
+ modal_title = 'Warning'
93
+
94
+ def modal_content(self):
95
+ return ('<div class="alert alert-danger"><strong>This will delete all data in the '
96
+ 'database and render the whole site unusable</strong><br>'
97
+ 'If the page is not refreshed a database can be restored after this process</div>')
98
+
99
+ def button_drop_schema(self, **_kwargs):
100
+ with connection.cursor() as cursor:
101
+ cursor.execute("DROP SCHEMA public CASCADE")
102
+ cursor.execute("CREATE SCHEMA public")
103
+ return self.command_response('close')
104
+
105
+ def get_modal_buttons(self):
106
+ return [modal_button_method('Confirm', 'drop_schema', 'btn-danger'),
107
+ modal_button('Cancel', 'close', 'btn-success')]
@@ -0,0 +1,43 @@
1
+ import datetime
2
+
3
+
4
+ class PruneBackups:
5
+
6
+ def __init__(self, backup_dict):
7
+ self.keep = []
8
+ self.backup_dict = backup_dict
9
+
10
+ def backups_to_remove(self, recipe):
11
+ # an empty recipe keeps nothing in self.keep, which would remove every backup
12
+ if not recipe:
13
+ return {}
14
+ for r in recipe:
15
+ if 'months' in r:
16
+ self.keep_monthly_backups(r['months'], r['number'])
17
+ elif 'days' in r:
18
+ self.keep_backups(datetime.timedelta(days=r['days']), r['number'])
19
+ elif 'hours' in r:
20
+ self.keep_backups(datetime.timedelta(hours=r['hours']), r['number'])
21
+ return {k: v for k, v in self.backup_dict.items() if k not in self.keep}
22
+
23
+ def keep_backups(self, period, number):
24
+ period_dict = {}
25
+ start_time = datetime.datetime(2000, 1, 1) + int((datetime.datetime.today() -
26
+ datetime.datetime(2000, 1, 1)) / period) * period + period
27
+ for b in self.backup_dict:
28
+ period_dict.setdefault(int((start_time - b) / period), []).append(b)
29
+ for k in sorted(period_dict.keys()):
30
+ self.keep.append(max(period_dict[k]))
31
+ number -= 1
32
+ if number < 1:
33
+ break
34
+
35
+ def keep_monthly_backups(self, period, number):
36
+ period_dict = {}
37
+ for b in self.backup_dict:
38
+ period_dict.setdefault(int(int(b.strftime('%Y%m')) / period), []).append(b)
39
+ for k in sorted(period_dict.keys(), reverse=True):
40
+ self.keep.append(max(period_dict[k]))
41
+ number -= 1
42
+ if number < 1:
43
+ break
@@ -0,0 +1,46 @@
1
+ from django.db import connection
2
+
3
+
4
+ def get_schemas():
5
+ with connection.cursor() as cursor:
6
+ # cursor.execute('SELECT schema.schema_name, Count(tables.table_name)'
7
+ # 'FROM information_schema.schemata as schema '
8
+ # 'Left Join information_schema.tables as tables on tables.table_schema = schema.schema_name '
9
+ # 'GROUP BY schema.schema_name')
10
+
11
+ cursor.execute(
12
+ 'SELECT pg_catalog.pg_namespace.nspname, pg_size_pretty(SUM(pg_relation_size(pg_catalog.pg_class.oid))) '
13
+ 'FROM pg_catalog.pg_class '
14
+ 'LEFT JOIN pg_catalog.pg_namespace ON relnamespace = pg_catalog.pg_namespace.oid '
15
+ 'GROUP BY pg_catalog.pg_namespace.nspname'
16
+ )
17
+ return [schema for schema in cursor.fetchall() if not schema[0].startswith('pg_')
18
+ and schema[0] not in ['information_schema']]
19
+
20
+
21
+ def get_schema_tables(schema):
22
+ with connection.cursor() as cursor:
23
+ cursor.execute(
24
+ f" SELECT relname , pg_relation_size(relfilenode), reltuples FROM pg_catalog.pg_class "
25
+ f"LEFT JOIN pg_catalog.pg_namespace ON relnamespace = pg_catalog.pg_namespace.oid "
26
+ f"WHERE pg_catalog.pg_namespace.nspname = 'public' AND relkind='r' "
27
+ )
28
+ return cursor.fetchall()
29
+
30
+
31
+ def get_table_column_names(schema, table_name):
32
+ with connection.cursor() as cursor:
33
+ cursor.execute(f"SELECT column_name from INFORMATION_SCHEMA.COLUMNS WHERE "
34
+ f"table_name='{table_name}' and table_schema='{schema}'")
35
+ return [c[0] for c in cursor.fetchall()]
36
+
37
+
38
+ def get_table_data(schema, table_name):
39
+ with connection.cursor() as cursor:
40
+ cursor.execute(f'SELECT * from {schema}."{table_name}"')
41
+ return cursor.fetchall()
42
+
43
+
44
+ def delete_table(schema, table_name):
45
+ with connection.cursor() as cursor:
46
+ cursor.execute(f'DELETE from {schema}.{table_name}')
@@ -0,0 +1,51 @@
1
+ from django.conf import settings
2
+ from django.core.exceptions import ImproperlyConfigured
3
+
4
+ from .base import BackupStorage, StorageFileNotFound # noqa: F401
5
+
6
+
7
+ def storage_settings():
8
+ """The BACKUP_STORAGE dict, defaulting to the original Google Drive behaviour so
9
+ existing installations keep working without any settings changes."""
10
+ return getattr(settings, 'BACKUP_STORAGE', None) or {'backend': 'gdrive'}
11
+
12
+
13
+ def backup_root():
14
+ """Root folder/prefix that backups go under, for the legacy global settings
15
+ (kept for external callers - per-config roots live on BackupConfig.root)."""
16
+ return storage_settings().get('root', getattr(settings, 'BACKUP_ROOT', 'django_backup'))
17
+
18
+
19
+ def get_storage(config=None):
20
+ """
21
+ Build the configured BackupStorage. Config keys other than 'backend' and 'root' are
22
+ passed to the backend constructor:
23
+
24
+ gdrive: credentials (CREDENTIAL_FILES key, default 'drive'),
25
+ shared_drive (defaults to settings.BACKUP_TEAM_DRIVE)
26
+ s3: bucket, access_key_id, secret_key, endpoint_url, region, b2
27
+ (endpoint_url unset = AWS; b2=True discovers the Backblaze endpoint;
28
+ R2 uses the account endpoint_url with region='auto')
29
+ lock: {'mode', 'db_days', 'file_days', 'min_days'} - Object Lock retention
30
+ stamped on uploads (bucket must have Object Lock enabled)
31
+ azure: container, connection_string or account_url + credential
32
+ """
33
+ config = dict(config if config is not None else storage_settings())
34
+ backend = config.pop('backend', 'gdrive')
35
+ config.pop('root', None)
36
+ lock = config.pop('lock', None)
37
+ if backend == 's3':
38
+ config['lock'] = lock # only the s3 backend supports object lock
39
+ if backend == 'gdrive':
40
+ from encrypted_credentials import django_credentials
41
+ from .gdrive import GDriveStorage
42
+ credentials = django_credentials.get_credentials(config.pop('credentials', 'drive'))
43
+ config.setdefault('shared_drive', getattr(settings, 'BACKUP_TEAM_DRIVE', None))
44
+ return GDriveStorage(credentials, **config)
45
+ if backend == 's3':
46
+ from .s3 import S3Storage
47
+ return S3Storage(**config)
48
+ if backend == 'azure':
49
+ from .azure import AzureStorage
50
+ return AzureStorage(**config)
51
+ raise ImproperlyConfigured(f'Unknown BACKUP_STORAGE backend {backend!r}')