fix: handle legacy databases in entrypoint Alembic migration

Three-way detection in entrypoint:
  - alembic_version exists → normal incremental upgrade
  - no tables → fresh upgrade from scratch
  - tables exist but no alembic_version → stamp head (legacy DB created
    by create_all(), mark all migrations as current without running them)

This fixes 'relation already exists' errors when Alembic tries to CREATE
TABLE on databases that already have tables from previous deployments.
This commit is contained in:
2026-05-26 19:58:31 +03:00
parent d870fe18d3
commit 1a57f33606

View File

@@ -151,9 +151,33 @@ install_playwright() {
install_certificates
install_playwright
echo "[entrypoint] Running Alembic migrations..."
alembic upgrade head 2>&1 | sed 's/^/[entrypoint] /'
echo "[entrypoint] ✅ Alembic migrations applied"
# Check DB state: empty, legacy (tables exist but no alembic), or managed
python3 -c "
import os
from sqlalchemy import create_engine, inspect
e = create_engine(os.environ['DATABASE_URL'])
insp = inspect(e)
if 'alembic_version' in insp.get_table_names():
exit(0) # managed → normal upgrade
if not insp.get_table_names():
exit(1) # empty → fresh upgrade
exit(2) # legacy → stamp head
" 2>/dev/null
_db_state=$?
if [ $_db_state -eq 0 ]; then
echo "[entrypoint] Running Alembic migrations (incremental)..."
alembic upgrade head 2>&1 | sed 's/^/[entrypoint] /'
echo "[entrypoint] ✅ Alembic migrations applied"
elif [ $_db_state -eq 1 ]; then
echo "[entrypoint] Empty database — running full Alembic upgrade..."
alembic upgrade head 2>&1 | sed 's/^/[entrypoint] /'
echo "[entrypoint] ✅ Alembic initial migration applied"
else
echo "[entrypoint] Legacy database — stamping Alembic head (tables already exist)..."
alembic stamp head 2>&1 | sed 's/^/[entrypoint] /'
echo "[entrypoint] ✅ Alembic stamped head, schema assumed up to date"
fi
bootstrap_admin