"""Capture structural contracts without starting the API, DB or model clients. This is used by the engineering refactor checks. It intentionally excludes runtime rows, private settings and callable memory addresses. """ from __future__ import annotations from sqlalchemy.dialects import mysql def _default_value(column): if column.default is None: return None argument = column.default.arg if callable(argument): return {"callable": getattr(argument, "__name__", type(argument).__name__)} return {"value": str(argument)} def capture_contract(): from app.main import create_app from app.models import Base application = create_app() # OpenAPI also resolves routers included lazily by newer FastAPI versions. # Walking application.routes alone can silently miss every business route. specification = application.openapi() routes = sorted( [ {"path": path, "method": method.upper(), "responses": sorted(operation["responses"])} for path, operations in specification["paths"].items() for method, operation in operations.items() if method in {"get", "post", "put", "patch", "delete", "head", "options"} ], key=lambda row: (row["path"], row["method"]), ) dialect = mysql.dialect() tables = {} for name, table in sorted(Base.metadata.tables.items()): tables[name] = { "columns": [ { "name": column.name, "type": str(column.type.compile(dialect=dialect)), "nullable": column.nullable, "primary_key": column.primary_key, "default": _default_value(column), "server_default": str(column.server_default.arg) if column.server_default else None, "foreign_keys": sorted(key.target_fullname for key in column.foreign_keys), } for column in table.columns ], "indexes": sorted( [ { "name": index.name, "unique": index.unique, "columns": [c.name for c in index.columns], } for index in table.indexes ], key=lambda row: row["name"], ), "unique_constraints": sorted( [ sorted(c.name for c in constraint.columns) for constraint in table.constraints if constraint.__class__.__name__ == "UniqueConstraint" ] ), } # 目录重排允许改变函数模块名和接口说明,字段、校验及响应结构必须保留。 http_contract = { "operations": { path: { method: { key: operation[key] for key in ("parameters", "requestBody", "responses", "security") if key in operation } for method, operation in operations.items() if method in {"get", "post", "put", "patch", "delete", "head", "options"} } for path, operations in specification["paths"].items() }, "components": specification.get("components", {}), } return {"routes": routes, "tables": tables, "http_contract": http_contract}