diff --git a/app.py b/app.py index f7221aa..1b8cbba 100644 --- a/app.py +++ b/app.py @@ -534,8 +534,9 @@ def sync_admin_from_env(): set_setting("admin_password_hash", generate_password_hash(env_password)) -init_db() -app.logger.info("数据库: %s", database_label()) +if os.getenv("QIHUO_SKIP_INIT_DB") != "1": + init_db() + app.logger.info("数据库: %s", database_label()) def sync_ths_token(): diff --git a/db_conn.py b/db_conn.py index 60a295a..89fa593 100644 --- a/db_conn.py +++ b/db_conn.py @@ -197,7 +197,11 @@ class DbConnection: def execute(self, sql: str, params: Sequence[Any] | None = None) -> DbCursor: cur = self.cursor() - return cur.execute(sql, params) + try: + return cur.execute(sql, params) + except Exception: + rollback_if_postgres(self) + raise def cursor(self) -> DbCursor: if self._backend == "sqlite": diff --git a/scripts/deploy_postgres.sh b/scripts/deploy_postgres.sh index 15540d1..93db2e5 100644 --- a/scripts/deploy_postgres.sh +++ b/scripts/deploy_postgres.sh @@ -66,10 +66,21 @@ echo "==> Python 依赖..." source "$APP_DIR/venv/bin/activate" pip install -q -r "$APP_DIR/requirements.txt" +if [ "$MIGRATE_SQLITE" = "1" ]; then + echo "==> 重置 PostgreSQL 库(迁移模式)..." + sudo -u postgres psql -v ON_ERROR_STOP=0 -c \ + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${PG_DB}' AND pid <> pg_backend_pid();" \ + >/dev/null 2>&1 || true + sudo -u postgres dropdb --if-exists "${PG_DB}" + sudo -u postgres createdb -O "${PG_USER}" "${PG_DB}" +fi + echo "==> 初始化 PostgreSQL 表结构..." cd "$APP_DIR" export DATABASE_URL +export QIHUO_SKIP_INIT_DB=1 python3 -c "from app import init_db; init_db(); from db_conn import database_label; print('OK:', database_label())" +unset QIHUO_SKIP_INIT_DB if [ "$MIGRATE_SQLITE" = "1" ] && [ -f "$APP_DIR/futures.db" ]; then echo "==> 从 SQLite 迁移数据..."