Skip to content

Commit c1683ff

Browse files
authored
Add automatic database migration support via Alembic (#537)
* Add automatic database migration support via Alembic * Move some stuff around * Fix test implementation * Create backup of database file before performing migrations * Ignore migrations directory with pylint
1 parent 16ad2a2 commit c1683ff

15 files changed

Lines changed: 561 additions & 35 deletions

File tree

server/.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
public/
22
static/
3+
conf/
34
digiscript.sqlite
45
digiscript.json
5-
conf/digiscript.sqlite
6-
conf/digiscript.json
76

87
# Byte-compiled / optimized / DLL files
98
__pycache__/

server/.pylintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
[MASTER]
22
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"
3+
ignore-paths=^alembic_config/versions/.*$,
34

45
[MESSAGES CONTROL]
56
disable=

server/alembic.ini

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = alembic_config
6+
7+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8+
# Uncomment the line below if you want the files to be prepended with date and time
9+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
10+
# for all available tokens
11+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
12+
13+
# sys.path path, will be prepended to sys.path if present.
14+
# defaults to the current working directory.
15+
prepend_sys_path = .
16+
17+
# timezone to use when rendering the date within the migration file
18+
# as well as the filename.
19+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
20+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
21+
# string value is passed to ZoneInfo()
22+
# leave blank for localtime
23+
# timezone =
24+
25+
# max length of characters to apply to the
26+
# "slug" field
27+
# truncate_slug_length = 40
28+
29+
# set to 'true' to run the environment during
30+
# the 'revision' command, regardless of autogenerate
31+
# revision_environment = false
32+
33+
# set to 'true' to allow .pyc and .pyo files without
34+
# a source .py file to be detected as revisions in the
35+
# versions/ directory
36+
# sourceless = false
37+
38+
# version location specification; This defaults
39+
# to alembic/versions. When using multiple version
40+
# directories, initial revisions must be specified with --version-path.
41+
# The path separator used here should be the separator specified by "version_path_separator" below.
42+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
43+
44+
# version path separator; As mentioned above, this is the character used to split
45+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47+
# Valid values for version_path_separator are:
48+
#
49+
# version_path_separator = :
50+
# version_path_separator = ;
51+
# version_path_separator = space
52+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
53+
54+
# set to 'true' to search source files recursively
55+
# in each "version_locations" directory
56+
# new in Alembic version 1.10
57+
# recursive_version_locations = false
58+
59+
# the output encoding used when revision files
60+
# are written from script.py.mako
61+
# output_encoding = utf-8
62+
63+
# The relative location of the DigiScript config file to this ini file
64+
digiscript.config = ./conf/digiscript.json
65+
# Whether to configure logging or not
66+
configure_logging = True
67+
68+
69+
[post_write_hooks]
70+
# post_write_hooks defines scripts or Python functions that are run
71+
# on newly generated revision scripts. See the documentation for further
72+
# detail and examples
73+
74+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
75+
# hooks = black
76+
# black.type = console_scripts
77+
# black.entrypoint = black
78+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
79+
80+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
81+
# hooks = ruff
82+
# ruff.type = exec
83+
# ruff.executable = %(here)s/.venv/bin/ruff
84+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
85+
86+
# Logging configuration
87+
[loggers]
88+
keys = root,sqlalchemy,alembic
89+
90+
[handlers]
91+
keys = console
92+
93+
[formatters]
94+
keys = generic
95+
96+
[logger_root]
97+
level = WARN
98+
handlers = console
99+
qualname =
100+
101+
[logger_sqlalchemy]
102+
level = WARN
103+
handlers =
104+
qualname = sqlalchemy.engine
105+
106+
[logger_alembic]
107+
level = INFO
108+
handlers =
109+
qualname = alembic
110+
111+
[handler_console]
112+
class = StreamHandler
113+
args = (sys.stderr,)
114+
level = NOTSET
115+
formatter = generic
116+
117+
[formatter_generic]
118+
format = %(levelname)-5.5s [%(name)s] %(message)s
119+
datefmt = %H:%M:%S

server/alembic_config/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

server/alembic_config/__init__.py

Whitespace-only changes.

server/alembic_config/env.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import json
2+
import os
3+
from logging.config import fileConfig
4+
5+
from sqlalchemy import engine_from_config
6+
from sqlalchemy import pool
7+
8+
from alembic import context
9+
10+
from models import models
11+
12+
# this is the Alembic Config object, which provides
13+
# access to the values within the .ini file in use.
14+
config = context.config
15+
16+
# Interpret the config file for Python logging.
17+
# This line sets up loggers basically.
18+
if config.config_file_name is not None:
19+
if config.get_main_option("configure_logging").lower() == "true":
20+
fileConfig(config.config_file_name)
21+
22+
# add your model's MetaData object here
23+
# for 'autogenerate' support
24+
models.import_all_models()
25+
target_metadata = models.db.metadata
26+
27+
# other values from the config, defined by the needs of env.py,
28+
# can be acquired:
29+
# my_important_option = config.get_main_option("my_important_option")
30+
# ... etc.
31+
32+
33+
def get_digiscript_db_url():
34+
rel_path = config.get_main_option("digiscript.config")
35+
if not os.path.isabs(rel_path):
36+
abs_path = os.path.join(os.path.dirname(__file__), "..", rel_path)
37+
else:
38+
abs_path = rel_path
39+
with open(abs_path, "r") as config_file:
40+
ds_config = json.load(config_file)
41+
return ds_config["db_path"]
42+
43+
44+
def include_name(name, type_, parent_names):
45+
if type_ == "table":
46+
return name in target_metadata.tables
47+
return True
48+
49+
50+
def run_migrations_offline() -> None:
51+
"""Run migrations in 'offline' mode.
52+
53+
This configures the context with just a URL
54+
and not an Engine, though an Engine is acceptable
55+
here as well. By skipping the Engine creation
56+
we don't even need a DBAPI to be available.
57+
58+
Calls to context.execute() here emit the given string to the
59+
script output.
60+
61+
"""
62+
url = get_digiscript_db_url()
63+
context.configure(
64+
url=url,
65+
target_metadata=target_metadata,
66+
literal_binds=True,
67+
dialect_opts={"paramstyle": "named"},
68+
include_schemas=False,
69+
include_name=include_name,
70+
)
71+
72+
with context.begin_transaction():
73+
context.run_migrations()
74+
75+
76+
def run_migrations_online() -> None:
77+
"""Run migrations in 'online' mode.
78+
79+
In this scenario we need to create an Engine
80+
and associate a connection with the context.
81+
82+
"""
83+
connectable = engine_from_config(
84+
config.get_section(config.config_ini_section, {}),
85+
prefix="sqlalchemy.",
86+
poolclass=pool.NullPool,
87+
url=get_digiscript_db_url(),
88+
)
89+
90+
with connectable.connect() as connection:
91+
context.configure(
92+
connection=connection,
93+
target_metadata=target_metadata,
94+
include_schemas=False,
95+
include_name=include_name,
96+
render_as_batch=True
97+
)
98+
99+
with context.begin_transaction():
100+
context.run_migrations()
101+
102+
103+
if context.is_offline_mode():
104+
run_migrations_offline()
105+
else:
106+
run_migrations_online()
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
${upgrades if upgrades else "pass"}
23+
24+
25+
def downgrade() -> None:
26+
${downgrades if downgrades else "pass"}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""Initial Alembic Revision
2+
3+
Revision ID: d4f66f58158b
4+
Revises:
5+
Create Date: 2024-06-02 15:50:23.550851
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = 'd4f66f58158b'
16+
down_revision: Union[str, None] = None
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade() -> None:
22+
pass
23+
24+
25+
def downgrade() -> None:
26+
pass

0 commit comments

Comments
 (0)