OpenSlides/server/openslides/core/management/commands/backupdb.py

53 lines
1.7 KiB
Python
Raw Normal View History

2015-01-16 14:18:34 +01:00
import shutil
from django.core.management.base import BaseCommand, CommandError
2015-01-16 14:18:34 +01:00
from django.db import connection, transaction
from openslides.utils.main import get_database_path_from_settings
class Command(BaseCommand):
2015-01-16 14:18:34 +01:00
"""
Command to backup the SQLite3 database.
2015-01-16 14:18:34 +01:00
"""
2019-01-06 16:22:33 +01:00
help = "Backups the SQLite3 database."
2015-01-16 14:18:34 +01:00
def add_arguments(self, parser):
parser.add_argument(
2019-01-06 16:22:33 +01:00
"--path",
default="database_backup.sqlite",
help="Path for the backup file (Default: database_backup.sqlite).",
)
def handle(self, *args, **options):
2019-01-06 16:22:33 +01:00
path = options.get("path")
2015-01-16 14:18:34 +01:00
@transaction.atomic
def do_backup(src_path, dest_path):
# perform a simple file-copy backup of the database
# first we need a shared lock on the database, issuing a select()
# will do this for us
cursor = connection.cursor()
cursor.execute("SELECT count(*) from sqlite_master")
# now copy the file
try:
shutil.copy(src_path, dest_path)
except IOError:
# TODO: use the IOError message as message for the user
raise CommandError("Database backup failed.")
database_path = get_database_path_from_settings()
if database_path:
do_backup(database_path, path)
2019-01-06 16:22:33 +01:00
self.stdout.write(
2019-03-19 20:26:12 +01:00
self.style.SUCCESS(
f"Database {database_path} successfully stored at {path}."
)
2019-01-06 16:22:33 +01:00
)
2015-01-16 14:18:34 +01:00
else:
raise CommandError(
2019-01-06 16:22:33 +01:00
"Default database is not SQLite3. Only SQLite3 databases"
"can currently be backuped."
)