feat(rohs-check): 新增 RoHS 检核工具 API 及相关功能
This commit is contained in:
1 parent
8a541211b7
commit
24551e9a9a
39 files changed
+3128
-189
No files matched your search
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/app/services/db_sequence.py
|
||||
文件用途:修复 PostgreSQL 主键序列与 MAX(id) 不同步导致的 UniqueViolation。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
def repair_pg_id_sequence(table_name: str) -> None:
|
||||
"""将 PostgreSQL 自增序列对齐到 MAX(id),修复手工导入或迁移后的主键冲突。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
qualified = f"public.{table_name}"
|
||||
db.session.execute(
|
||||
text(
|
||||
"SELECT setval("
|
||||
"pg_get_serial_sequence(:qualified, 'id'), "
|
||||
f"COALESCE((SELECT MAX(id) FROM {table_name}), 0), true)"
|
||||
),
|
||||
{"qualified": qualified},
|
||||
)
|
||||
|
||||
|
||||
def is_pk_sequence_conflict(exc: IntegrityError, table_name: str) -> bool:
|
||||
orig = getattr(exc, "orig", exc)
|
||||
return f"{table_name}_pkey" in str(orig)
|
||||
|
||||
|
||||
def add_and_flush_with_sequence_retry(instance, table_name: str) -> None:
|
||||
"""插入并 flush;若主键序列落后则修复后重试一次。
|
||||
|
||||
使用 SAVEPOINT 隔离单次插入失败,避免全局 rollback 把同事务中已创建的
|
||||
前置对象一并回滚。
|
||||
"""
|
||||
try:
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.add(instance)
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
except IntegrityError as exc:
|
||||
if not is_pk_sequence_conflict(exc, table_name):
|
||||
raise
|
||||
repair_pg_id_sequence(table_name)
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.add(instance)
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
Reference in new issue
Block a user