feat: take a backup of the sqlite db before executing schema migrations
All checks were successful
/ test (push) Successful in 1m26s
/ codestyle (push) Successful in 1m0s

This commit is contained in:
s3lph 2024-12-07 22:02:00 +01:00
parent 43ac5d656f
commit 8879add39b
Signed by: s3lph
GPG key ID: 0AA29A52FB33CFB5
3 changed files with 19 additions and 9 deletions

1
.gitignore vendored
View file

@ -9,5 +9,6 @@
*.sqlite3
*.db
*.bak
static/upload/
./matemat.conf

View file

@ -60,23 +60,31 @@ class DatabaseWrapper(object):
def _setup(self) -> None:
# Create or update schemas if necessary
with self.transaction() as c:
version: int = self._user_version
if version < 1:
# Don't use executescript, as it issues a COMMIT first
version: int = self._user_version
if version < 1:
# Don't use executescript, as it issues a COMMIT first
with self.transaction() as c:
for command in SCHEMAS[self.SCHEMA_VERSION]:
c.execute(command)
elif version < self.SCHEMA_VERSION:
self._upgrade(from_version=version, to_version=self.SCHEMA_VERSION)
elif version > self.SCHEMA_VERSION:
raise RuntimeError('Database schema is newer than supported by this version of Matemat.')
self._user_version = self.SCHEMA_VERSION
elif version < self.SCHEMA_VERSION:
self._upgrade(from_version=version, to_version=self.SCHEMA_VERSION)
elif version > self.SCHEMA_VERSION:
raise RuntimeError('Database schema is newer than supported by this version of Matemat.')
self._user_version = self.SCHEMA_VERSION
# Enable foreign key enforcement
cursor = self._sqlite_db.cursor()
cursor.execute('PRAGMA foreign_keys=ON')
def _upgrade(self, from_version: int, to_version: int) -> None:
if from_version >= to_version:
return
if self._filename != ':memory:':
bakfile = f'{self._filename}_{from_version}_{to_version}.bak'
bak = sqlite3.connect(bakfile)
with bak:
self._sqlite_db.backup(bak, pages=1)
bak.close()
with self.transaction() as c:
c.execute('PRAGMA foreign_keys=OFF')
c.execute('PRAGMA legacy_alter_table=ON')

View file

@ -16,6 +16,7 @@ if [[ "$1" == "configure" ]]; then
chmod 0750 /var/lib/matemat
ln -sf /var/lib/matemat/upload /usr/lib/matemat/static/upload
systemctl daemon-reload || true
deb-systemd-helper enable matemat.service
deb-systemd-invoke restart matemat.service