聊天样式微调
This commit is contained in:
1 parent
fafcdfe742
commit
efae286f5c
12 files changed
+442
-293
No files matched your search
Executable
+258
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Check schema drift between SQLAlchemy models and the current database.
|
||||
|
||||
Exit code:
|
||||
0 -> no drift
|
||||
1 -> drift found
|
||||
2 -> runtime/config error
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Set, Tuple
|
||||
|
||||
from sqlalchemy import inspect
|
||||
|
||||
# Ensure backend root is importable when this script runs from backend/scripts.
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
|
||||
@dataclass
|
||||
class DriftIssue:
|
||||
category: str
|
||||
table: str
|
||||
detail: str
|
||||
|
||||
|
||||
def _normalize_type(raw: str) -> str:
|
||||
s = (raw or "").upper().replace(" ", "")
|
||||
s = s.replace("CHARACTERVARYING", "VARCHAR")
|
||||
s = s.replace("DOUBLEPRECISION", "FLOAT")
|
||||
if s == "INT":
|
||||
s = "INTEGER"
|
||||
return s
|
||||
|
||||
|
||||
def _types_equivalent(model_type: str, db_type: str) -> bool:
|
||||
m = _normalize_type(model_type)
|
||||
d = _normalize_type(db_type)
|
||||
if m == d:
|
||||
return True
|
||||
|
||||
# Numeric families (cross-dialect aliases)
|
||||
float_family = {"FLOAT", "REAL", "NUMERIC"}
|
||||
int_family = {"INTEGER", "BIGINT", "SMALLINT"}
|
||||
if m in float_family and d in float_family:
|
||||
return True
|
||||
if m in int_family and d in int_family:
|
||||
return m == d
|
||||
return False
|
||||
|
||||
|
||||
def _collect_model_uniques(table) -> Set[Tuple[str, ...]]:
|
||||
unique_sets: Set[Tuple[str, ...]] = set()
|
||||
for col in table.columns:
|
||||
if col.unique:
|
||||
unique_sets.add((col.name,))
|
||||
for cons in table.constraints:
|
||||
if cons.__class__.__name__ == "UniqueConstraint":
|
||||
cols = tuple(col.name for col in cons.columns)
|
||||
if cols:
|
||||
unique_sets.add(cols)
|
||||
return unique_sets
|
||||
|
||||
|
||||
def _collect_db_uniques(insp, table_name: str) -> Set[Tuple[str, ...]]:
|
||||
unique_sets: Set[Tuple[str, ...]] = set()
|
||||
for uc in insp.get_unique_constraints(table_name):
|
||||
cols = tuple(uc.get("column_names") or [])
|
||||
if cols:
|
||||
unique_sets.add(cols)
|
||||
for idx in insp.get_indexes(table_name):
|
||||
if idx.get("unique"):
|
||||
cols = tuple(idx.get("column_names") or [])
|
||||
if cols:
|
||||
unique_sets.add(cols)
|
||||
return unique_sets
|
||||
|
||||
|
||||
def _collect_model_indexes(table) -> Set[Tuple[str, ...]]:
|
||||
return {tuple(col.name for col in idx.columns) for idx in table.indexes}
|
||||
|
||||
|
||||
def _collect_db_indexes(insp, table_name: str) -> Set[Tuple[str, ...]]:
|
||||
idx_sets: Set[Tuple[str, ...]] = set()
|
||||
for idx in insp.get_indexes(table_name):
|
||||
cols = tuple(idx.get("column_names") or [])
|
||||
if cols:
|
||||
idx_sets.add(cols)
|
||||
return idx_sets
|
||||
|
||||
|
||||
def _collect_model_fks(table) -> Set[Tuple[str, str, str]]:
|
||||
model_fks: Set[Tuple[str, str, str]] = set()
|
||||
for col in table.columns:
|
||||
for fk in col.foreign_keys:
|
||||
model_fks.add((col.name, fk.column.table.name, fk.column.name))
|
||||
return model_fks
|
||||
|
||||
|
||||
def _collect_db_fks(insp, table_name: str) -> Set[Tuple[str, str, str]]:
|
||||
db_fks: Set[Tuple[str, str, str]] = set()
|
||||
for fk in insp.get_foreign_keys(table_name):
|
||||
constrained_cols = fk.get("constrained_columns") or []
|
||||
referred_cols = fk.get("referred_columns") or []
|
||||
referred_table = fk.get("referred_table")
|
||||
for constrained, referred in zip(constrained_cols, referred_cols):
|
||||
db_fks.add((constrained, referred_table, referred))
|
||||
return db_fks
|
||||
|
||||
|
||||
def _format_tuple_set(values: Iterable[Tuple[str, ...]]) -> str:
|
||||
parts = [f"({', '.join(v)})" for v in sorted(values)]
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Check SQLAlchemy schema drift.")
|
||||
parser.add_argument(
|
||||
"--database-url",
|
||||
default="",
|
||||
help="Override DATABASE_URL for this check.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.database_url:
|
||||
os.environ["DATABASE_URL"] = args.database_url
|
||||
|
||||
try:
|
||||
from app import create_app, db
|
||||
import app.models # noqa: F401 - ensure model metadata is registered
|
||||
except Exception as exc:
|
||||
print(f"[drift-check] Failed to import app/models: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
app = create_app("development")
|
||||
issues: List[DriftIssue] = []
|
||||
|
||||
with app.app_context():
|
||||
insp = inspect(db.engine)
|
||||
metadata = db.Model.metadata
|
||||
|
||||
model_tables = set(metadata.tables.keys())
|
||||
db_tables = set(insp.get_table_names())
|
||||
|
||||
missing_tables = sorted(model_tables - db_tables)
|
||||
for table in missing_tables:
|
||||
issues.append(DriftIssue("table_missing_in_db", table, "table does not exist"))
|
||||
|
||||
extra_tables = sorted((db_tables - model_tables) - {"alembic_version"})
|
||||
for table in extra_tables:
|
||||
issues.append(DriftIssue("table_extra_in_db", table, "table not found in models"))
|
||||
|
||||
common_tables = sorted(model_tables & db_tables)
|
||||
for table_name in common_tables:
|
||||
model_table = metadata.tables[table_name]
|
||||
model_cols: Dict[str, object] = {c.name: c for c in model_table.columns}
|
||||
db_cols = {c["name"]: c for c in insp.get_columns(table_name)}
|
||||
|
||||
missing_cols = sorted(set(model_cols) - set(db_cols))
|
||||
if missing_cols:
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"column_missing_in_db",
|
||||
table_name,
|
||||
", ".join(missing_cols),
|
||||
)
|
||||
)
|
||||
|
||||
extra_cols = sorted(set(db_cols) - set(model_cols))
|
||||
if extra_cols:
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"column_extra_in_db",
|
||||
table_name,
|
||||
", ".join(extra_cols),
|
||||
)
|
||||
)
|
||||
|
||||
for col_name in sorted(set(model_cols) & set(db_cols)):
|
||||
model_col = model_cols[col_name]
|
||||
db_col = db_cols[col_name]
|
||||
|
||||
model_nullable = model_col.nullable
|
||||
db_nullable = db_col.get("nullable", True)
|
||||
if model_nullable != db_nullable:
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"nullable_mismatch",
|
||||
table_name,
|
||||
f"{col_name}: model={model_nullable}, db={db_nullable}",
|
||||
)
|
||||
)
|
||||
|
||||
model_type = str(model_col.type)
|
||||
db_type = str(db_col.get("type"))
|
||||
if not _types_equivalent(model_type, db_type):
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"type_mismatch",
|
||||
table_name,
|
||||
f"{col_name}: model={model_type}, db={db_type}",
|
||||
)
|
||||
)
|
||||
|
||||
model_uniques = _collect_model_uniques(model_table)
|
||||
db_uniques = _collect_db_uniques(insp, table_name)
|
||||
missing_uniques = model_uniques - db_uniques
|
||||
if missing_uniques:
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"unique_missing_in_db",
|
||||
table_name,
|
||||
_format_tuple_set(missing_uniques),
|
||||
)
|
||||
)
|
||||
|
||||
model_indexes = _collect_model_indexes(model_table)
|
||||
db_indexes = _collect_db_indexes(insp, table_name)
|
||||
missing_indexes = model_indexes - db_indexes
|
||||
if missing_indexes:
|
||||
issues.append(
|
||||
DriftIssue(
|
||||
"index_missing_in_db",
|
||||
table_name,
|
||||
_format_tuple_set(missing_indexes),
|
||||
)
|
||||
)
|
||||
|
||||
model_fks = _collect_model_fks(model_table)
|
||||
db_fks = _collect_db_fks(insp, table_name)
|
||||
missing_fks = model_fks - db_fks
|
||||
if missing_fks:
|
||||
fk_detail = ", ".join(
|
||||
f"({col} -> {ref_table}.{ref_col})"
|
||||
for col, ref_table, ref_col in sorted(missing_fks)
|
||||
)
|
||||
issues.append(DriftIssue("fk_missing_in_db", table_name, fk_detail))
|
||||
|
||||
if not issues:
|
||||
print("[drift-check] OK: models and database schema are aligned.")
|
||||
return 0
|
||||
|
||||
print("[drift-check] DRIFT FOUND:")
|
||||
for issue in issues:
|
||||
print(f" - [{issue.category}] {issue.table}: {issue.detail}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
BACKEND_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
MIGRATIONS_DIR="${BACKEND_DIR}/migrations/versions"
|
||||
FLASK_BIN="${BACKEND_DIR}/venv/bin/flask"
|
||||
PYTHON_BIN="${BACKEND_DIR}/venv/bin/python3"
|
||||
BASELINE_DB="${BACKEND_DIR}/local_test.db"
|
||||
|
||||
if [[ ! -x "${FLASK_BIN}" ]]; then
|
||||
echo "[ci-check] missing flask executable: ${FLASK_BIN}"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ ! -x "${PYTHON_BIN}" ]]; then
|
||||
echo "[ci-check] missing python executable: ${PYTHON_BIN}"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
TMP_DB="/tmp/hxops_ci_migration_${RANDOM}_$$.db"
|
||||
TMP_LOG="/tmp/hxops_ci_migration_${RANDOM}_$$.log"
|
||||
BEFORE_LIST="/tmp/hxops_ci_before_${RANDOM}_$$.txt"
|
||||
AFTER_LIST="/tmp/hxops_ci_after_${RANDOM}_$$.txt"
|
||||
|
||||
cleanup() {
|
||||
rm -f "${TMP_DB}" "${TMP_LOG}" "${BEFORE_LIST}" "${AFTER_LIST}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
cd "${BACKEND_DIR}"
|
||||
find "${MIGRATIONS_DIR}" -maxdepth 1 -type f -name "*.py" | sort > "${BEFORE_LIST}"
|
||||
|
||||
export DATABASE_URL="sqlite:///${TMP_DB}"
|
||||
echo "[ci-check] DATABASE_URL=${DATABASE_URL}"
|
||||
|
||||
if [[ -f "${BASELINE_DB}" ]]; then
|
||||
echo "[ci-check] step0: seed temp db from baseline local_test.db"
|
||||
cp "${BASELINE_DB}" "${TMP_DB}"
|
||||
else
|
||||
echo "[ci-check] step0: baseline local_test.db not found, using empty temp db"
|
||||
fi
|
||||
|
||||
echo "[ci-check] step1: upgrade temp db to head"
|
||||
if ! "${FLASK_BIN}" --app manage.py db upgrade; then
|
||||
echo "[ci-check] db upgrade failed."
|
||||
if [[ -f "${BASELINE_DB}" ]]; then
|
||||
echo "[ci-check] baseline exists but upgrade still failed. Please inspect migration chain."
|
||||
else
|
||||
echo "[ci-check] this repo's historical migrations may not support empty-db bootstrap."
|
||||
echo "[ci-check] add/commit backend/local_test.db as baseline, or fix early revisions."
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[ci-check] step2: schema drift check"
|
||||
"${PYTHON_BIN}" scripts/check_schema_drift.py --database-url "${DATABASE_URL}"
|
||||
|
||||
echo "[ci-check] step3: autogenerate dry-check"
|
||||
if ! "${FLASK_BIN}" --app manage.py db migrate -m "__ci_drift_check__" > "${TMP_LOG}" 2>&1; then
|
||||
cat "${TMP_LOG}"
|
||||
echo "[ci-check] migrate command failed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
find "${MIGRATIONS_DIR}" -maxdepth 1 -type f -name "*.py" | sort > "${AFTER_LIST}"
|
||||
NEW_FILES="$(comm -13 "${BEFORE_LIST}" "${AFTER_LIST}" || true)"
|
||||
|
||||
if [[ -n "${NEW_FILES}" ]]; then
|
||||
echo "[ci-check] DRIFT: autogenerate produced new migration(s):"
|
||||
echo "${NEW_FILES}"
|
||||
while IFS= read -r f; do
|
||||
[[ -z "${f}" ]] && continue
|
||||
rm -f "${f}"
|
||||
done <<< "${NEW_FILES}"
|
||||
echo "[ci-check] removed temporary generated migration file(s); please add a real migration."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[ci-check] OK: no schema drift detected."
|
||||
Reference in new issue
Block a user