Harden PostgreSQL deploy: auto-rollback on SQL errors, clean DB on migrate.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -534,6 +534,7 @@ def sync_admin_from_env():
|
||||
set_setting("admin_password_hash", generate_password_hash(env_password))
|
||||
|
||||
|
||||
if os.getenv("QIHUO_SKIP_INIT_DB") != "1":
|
||||
init_db()
|
||||
app.logger.info("数据库: %s", database_label())
|
||||
|
||||
|
||||
@@ -197,7 +197,11 @@ class DbConnection:
|
||||
|
||||
def execute(self, sql: str, params: Sequence[Any] | None = None) -> DbCursor:
|
||||
cur = self.cursor()
|
||||
try:
|
||||
return cur.execute(sql, params)
|
||||
except Exception:
|
||||
rollback_if_postgres(self)
|
||||
raise
|
||||
|
||||
def cursor(self) -> DbCursor:
|
||||
if self._backend == "sqlite":
|
||||
|
||||
@@ -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 迁移数据..."
|
||||
|
||||
Reference in New Issue
Block a user