diff options
| author | Dennis Fink | 2026-10-27 23:16:27 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-10-27 23:18:45 +0100 |
| commit | 17ab56a3c7d3dbb3d66edf380ab637a61cefe50c (patch) | |
| tree | 1626e3e1d402a6614a1cec4c2c6719d301f39bac /webmentions_ssg/cli/database.py | |
| parent | 5afb245d13b91047d68d7b7343245c41b6460953 (diff) | |
| download | webmentions-ssg-17ab56a3c7d3dbb3d66edf380ab637a61cefe50c.tar.gz webmentions-ssg-17ab56a3c7d3dbb3d66edf380ab637a61cefe50c.zip | |
feat(core): add database CLI
Make database initialization and upgrades explicit so new installations
cannot silently modify an existing or unversioned schema.
Keep Flask-Migrate commands available separately and package the
migration environment with the application for reliable deployment.
Diffstat (limited to 'webmentions_ssg/cli/database.py')
| -rw-r--r-- | webmentions_ssg/cli/database.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/webmentions_ssg/cli/database.py b/webmentions_ssg/cli/database.py new file mode 100644 index 0000000..e918600 --- /dev/null +++ b/webmentions_ssg/cli/database.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Simple database commands built on Flask-Migrate.""" + +import click +from flask.cli import AppGroup +from flask_migrate import upgrade as migrate_upgrade +from sqlalchemy import inspect + +from .. import DATABASE + +DB_CLI = AppGroup("db", help="Handle database") + + +def _table_names() -> set[str]: + """Return existing table names without modifying the database schema.""" + with DATABASE.engine.connect() as connection: + return set(inspect(connection).get_table_names()) + + +@DB_CLI.command("create-db", help="Create a new database using all migrations") +def create_db() -> None: + """Initialize an empty database and record its Alembic revision.""" + if _table_names(): + raise click.ClickException( + "The database already contains tables. " + "Use 'flask db upgrade' for an existing migrated database." + ) + + # Applying migrations (rather than create_all()) keeps alembic_version in sync. + migrate_upgrade() + click.echo("Database created at the latest migration revision.") + + +@DB_CLI.command("upgrade", help="Upgrade an existing database to the latest revision") +def upgrade_db() -> None: + """Apply pending migrations to a previously initialized database.""" + if "alembic_version" not in _table_names(): + raise click.ClickException( + "No Flask-Migrate revision table found. " + "For a new, empty database run 'flask db create-db'. " + "For a legacy database, inspect its schema and use " + "'flask migrate stamp' only if appropriate." + ) + + migrate_upgrade() + click.echo("Database upgraded to the latest migration revision.") |
