Harden PostgreSQL deploy: auto-rollback on SQL errors, clean DB on migrate.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-01 08:13:51 +08:00
parent bc79ad308c
commit a1f22624de
3 changed files with 19 additions and 3 deletions
+3 -2
View File
@@ -534,8 +534,9 @@ def sync_admin_from_env():
set_setting("admin_password_hash", generate_password_hash(env_password)) set_setting("admin_password_hash", generate_password_hash(env_password))
init_db() if os.getenv("QIHUO_SKIP_INIT_DB") != "1":
app.logger.info("数据库: %s", database_label()) init_db()
app.logger.info("数据库: %s", database_label())
def sync_ths_token(): def sync_ths_token():
+5 -1
View File
@@ -197,7 +197,11 @@ class DbConnection:
def execute(self, sql: str, params: Sequence[Any] | None = None) -> DbCursor: def execute(self, sql: str, params: Sequence[Any] | None = None) -> DbCursor:
cur = self.cursor() 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: def cursor(self) -> DbCursor:
if self._backend == "sqlite": if self._backend == "sqlite":
+11
View File
@@ -66,10 +66,21 @@ echo "==> Python 依赖..."
source "$APP_DIR/venv/bin/activate" source "$APP_DIR/venv/bin/activate"
pip install -q -r "$APP_DIR/requirements.txt" 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 表结构..." echo "==> 初始化 PostgreSQL 表结构..."
cd "$APP_DIR" cd "$APP_DIR"
export DATABASE_URL 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())" 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 if [ "$MIGRATE_SQLITE" = "1" ] && [ -f "$APP_DIR/futures.db" ]; then
echo "==> 从 SQLite 迁移数据..." echo "==> 从 SQLite 迁移数据..."