swiftapi-kernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of swiftapi-kernel might be problematic. Click here for more details.

Files changed (187) hide show
  1. swiftapi/__init__.py +22 -0
  2. swiftapi/app/__init__.py +0 -0
  3. swiftapi/app/factory.py +200 -0
  4. swiftapi/app/lifespan.py +167 -0
  5. swiftapi/app/routers.py +58 -0
  6. swiftapi/cli/__init__.py +0 -0
  7. swiftapi/cli/admin.py +198 -0
  8. swiftapi/cli/appref.py +51 -0
  9. swiftapi/cli/audit.py +45 -0
  10. swiftapi/cli/db.py +185 -0
  11. swiftapi/cli/endpoint.py +169 -0
  12. swiftapi/cli/logs.py +100 -0
  13. swiftapi/cli/main.py +238 -0
  14. swiftapi/cli/new.py +113 -0
  15. swiftapi/cli/openapi.py +69 -0
  16. swiftapi/cli/resource.py +657 -0
  17. swiftapi/cli/scaffold.py +168 -0
  18. swiftapi/config/__init__.py +0 -0
  19. swiftapi/config/constants.py +51 -0
  20. swiftapi/config/environments.py +38 -0
  21. swiftapi/config/settings.py +764 -0
  22. swiftapi/core/__init__.py +0 -0
  23. swiftapi/core/admin/__init__.py +0 -0
  24. swiftapi/core/admin/accounts.py +385 -0
  25. swiftapi/core/admin/audit.py +203 -0
  26. swiftapi/core/admin/maintenance.py +53 -0
  27. swiftapi/core/admin/registry.py +53 -0
  28. swiftapi/core/admin/security.py +94 -0
  29. swiftapi/core/admin/session.py +154 -0
  30. swiftapi/core/admin/views.py +2428 -0
  31. swiftapi/core/cache/__init__.py +0 -0
  32. swiftapi/core/cache/base.py +29 -0
  33. swiftapi/core/cache/decorators.py +51 -0
  34. swiftapi/core/cache/factory.py +30 -0
  35. swiftapi/core/cache/keys.py +24 -0
  36. swiftapi/core/cache/memory.py +60 -0
  37. swiftapi/core/cache/null.py +28 -0
  38. swiftapi/core/cache/redis.py +50 -0
  39. swiftapi/core/container.py +209 -0
  40. swiftapi/core/db/__init__.py +0 -0
  41. swiftapi/core/db/base_model.py +122 -0
  42. swiftapi/core/db/crud.py +242 -0
  43. swiftapi/core/db/dialects/__init__.py +8 -0
  44. swiftapi/core/db/dialects/base.py +106 -0
  45. swiftapi/core/db/dialects/mysql.py +47 -0
  46. swiftapi/core/db/dialects/pg.py +51 -0
  47. swiftapi/core/db/dialects/registry.py +30 -0
  48. swiftapi/core/db/dialects/sqlite.py +47 -0
  49. swiftapi/core/db/engine.py +209 -0
  50. swiftapi/core/db/health.py +84 -0
  51. swiftapi/core/db/migrate/__init__.py +1 -0
  52. swiftapi/core/db/migrate/ddl.py +162 -0
  53. swiftapi/core/db/migrate/render.py +84 -0
  54. swiftapi/core/db/migrate/runner.py +159 -0
  55. swiftapi/core/db/migrate/schema.py +248 -0
  56. swiftapi/core/db/mixins.py +53 -0
  57. swiftapi/core/db/session.py +54 -0
  58. swiftapi/core/db/snapshot.py +33 -0
  59. swiftapi/core/db/tenant_model.py +43 -0
  60. swiftapi/core/db/tenant_router.py +114 -0
  61. swiftapi/core/db/types.py +109 -0
  62. swiftapi/core/db/unit_of_work.py +65 -0
  63. swiftapi/core/docs/__init__.py +0 -0
  64. swiftapi/core/docs/router.py +26 -0
  65. swiftapi/core/docs/tsgen.py +93 -0
  66. swiftapi/core/docs/ui.py +132 -0
  67. swiftapi/core/errors/__init__.py +0 -0
  68. swiftapi/core/errors/base.py +168 -0
  69. swiftapi/core/errors/codes.py +117 -0
  70. swiftapi/core/errors/handlers.py +155 -0
  71. swiftapi/core/errors/problem.py +58 -0
  72. swiftapi/core/errors/validation.py +11 -0
  73. swiftapi/core/framework_models.py +22 -0
  74. swiftapi/core/http/__init__.py +47 -0
  75. swiftapi/core/http/app.py +247 -0
  76. swiftapi/core/http/cors.py +100 -0
  77. swiftapi/core/http/idempotency.py +148 -0
  78. swiftapi/core/http/middleware/__init__.py +82 -0
  79. swiftapi/core/http/middleware/access_log.py +57 -0
  80. swiftapi/core/http/middleware/auth.py +105 -0
  81. swiftapi/core/http/middleware/body_limit.py +76 -0
  82. swiftapi/core/http/middleware/rate_limit.py +103 -0
  83. swiftapi/core/http/middleware/request_body.py +122 -0
  84. swiftapi/core/http/middleware/request_id.py +46 -0
  85. swiftapi/core/http/middleware/security_headers.py +46 -0
  86. swiftapi/core/http/middleware/tenant.py +93 -0
  87. swiftapi/core/http/middleware/timing.py +57 -0
  88. swiftapi/core/http/multipart.py +116 -0
  89. swiftapi/core/http/multipart_stream.py +216 -0
  90. swiftapi/core/http/openapi.py +148 -0
  91. swiftapi/core/http/pagination.py +55 -0
  92. swiftapi/core/http/params.py +302 -0
  93. swiftapi/core/http/request.py +145 -0
  94. swiftapi/core/http/responses.py +127 -0
  95. swiftapi/core/http/routing.py +200 -0
  96. swiftapi/core/http/types.py +86 -0
  97. swiftapi/core/http/uploads.py +222 -0
  98. swiftapi/core/messaging/__init__.py +0 -0
  99. swiftapi/core/messaging/base.py +33 -0
  100. swiftapi/core/messaging/consumer.py +57 -0
  101. swiftapi/core/messaging/factory.py +30 -0
  102. swiftapi/core/messaging/idempotency.py +61 -0
  103. swiftapi/core/messaging/inprocess.py +30 -0
  104. swiftapi/core/messaging/outbox.py +106 -0
  105. swiftapi/core/messaging/rabbitmq.py +186 -0
  106. swiftapi/core/messaging/relay.py +151 -0
  107. swiftapi/core/messaging/streams.py +141 -0
  108. swiftapi/core/observability/__init__.py +0 -0
  109. swiftapi/core/observability/archive.py +136 -0
  110. swiftapi/core/observability/context.py +102 -0
  111. swiftapi/core/observability/logging.py +192 -0
  112. swiftapi/core/observability/masking.py +74 -0
  113. swiftapi/core/observability/metrics.py +101 -0
  114. swiftapi/core/observability/volume.py +67 -0
  115. swiftapi/core/resilience/__init__.py +0 -0
  116. swiftapi/core/resilience/bulkhead.py +50 -0
  117. swiftapi/core/resilience/circuit_breaker.py +97 -0
  118. swiftapi/core/resilience/client.py +179 -0
  119. swiftapi/core/resilience/retry.py +59 -0
  120. swiftapi/core/security/__init__.py +0 -0
  121. swiftapi/core/security/jwt.py +78 -0
  122. swiftapi/core/security/principal.py +78 -0
  123. swiftapi/core/tenant/__init__.py +1 -0
  124. swiftapi/core/tenant/catalog.py +89 -0
  125. swiftapi/core/tenant/context.py +75 -0
  126. swiftapi/core/tenant/isolation.py +48 -0
  127. swiftapi/core/tenant/resolver.py +48 -0
  128. swiftapi/core/validation/__init__.py +0 -0
  129. swiftapi/core/validation/base.py +32 -0
  130. swiftapi/db.py +50 -0
  131. swiftapi/modules/__init__.py +0 -0
  132. swiftapi/modules/users/__init__.py +11 -0
  133. swiftapi/modules/users/api/__init__.py +0 -0
  134. swiftapi/modules/users/api/users.py +110 -0
  135. swiftapi/modules/users/crud/__init__.py +0 -0
  136. swiftapi/modules/users/crud/user.py +23 -0
  137. swiftapi/modules/users/errors.py +24 -0
  138. swiftapi/modules/users/mappers.py +19 -0
  139. swiftapi/modules/users/model/__init__.py +0 -0
  140. swiftapi/modules/users/model/user.py +37 -0
  141. swiftapi/modules/users/policies.py +19 -0
  142. swiftapi/modules/users/schema/__init__.py +0 -0
  143. swiftapi/modules/users/schema/user.py +40 -0
  144. swiftapi/modules/users/service/__init__.py +0 -0
  145. swiftapi/modules/users/service/user.py +107 -0
  146. swiftapi/py.typed +0 -0
  147. swiftapi/templates/__init__.py +0 -0
  148. swiftapi/templates/app_skeleton/README.md +17 -0
  149. swiftapi/templates/app_skeleton/__init__.py +1 -0
  150. swiftapi/templates/app_skeleton/api/__init__.py +23 -0
  151. swiftapi/templates/app_skeleton/api/health.py +12 -0
  152. swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
  153. swiftapi/templates/app_skeleton/model/__init__.py +1 -0
  154. swiftapi/templates/app_skeleton/router.py +16 -0
  155. swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
  156. swiftapi/templates/app_skeleton/service/__init__.py +1 -0
  157. swiftapi/templates/project/__init__.py +0 -0
  158. swiftapi/templates/project/api.py +135 -0
  159. swiftapi/templates/project/app.py +57 -0
  160. swiftapi/templates/project/endpoints/__init__.py +25 -0
  161. swiftapi/templates/project/events.py +43 -0
  162. swiftapi/templates/project/models.py +79 -0
  163. swiftapi/templates/project/resources/__init__.py +35 -0
  164. swiftapi/templates/project/schemas.py +45 -0
  165. swiftapi/templates/project/service.py +125 -0
  166. swiftapi/templates/project/settings.py +17 -0
  167. swiftapi/templates/project_skeleton/.env.example +5 -0
  168. swiftapi/templates/project_skeleton/.gitignore +6 -0
  169. swiftapi/templates/project_skeleton/README.md +25 -0
  170. swiftapi/templates/project_skeleton/__init__.py +1 -0
  171. swiftapi/templates/project_skeleton/app.py +26 -0
  172. swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
  173. swiftapi/templates/project_skeleton/common/__init__.py +4 -0
  174. swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
  175. swiftapi/templates/project_skeleton/conf/settings.py +73 -0
  176. swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
  177. swiftapi/templates/project_skeleton/models.py +12 -0
  178. swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
  179. swiftapi/templates/project_skeleton/router.py +46 -0
  180. swiftapi/templates/project_skeleton/script/start.sh +13 -0
  181. swiftapi/templates/project_skeleton/start.py +35 -0
  182. swiftapi/version.py +8 -0
  183. swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
  184. swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
  185. swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
  186. swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
  187. swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,209 @@
1
+ """数据库引擎生命周期(多方言)。
2
+
3
+ 设计要点:
4
+ - 方言由 URL scheme 决定,池参数按方言给不同默认(SQLite 用 NullPool + WAL);
5
+ - 只读副本按 `read_replica_urls` 建引擎,未配置时读请求回落主库;
6
+ - `Database.aclose()` 统一释放,交由容器/生命周期调用。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from sqlalchemy import event, text
16
+ from sqlalchemy.ext.asyncio import (
17
+ AsyncEngine,
18
+ AsyncSession,
19
+ async_sessionmaker,
20
+ create_async_engine,
21
+ )
22
+ from sqlalchemy.orm import Session
23
+ from sqlalchemy.pool import NullPool
24
+
25
+ from swiftapi.config.settings import Settings
26
+ from swiftapi.core.observability.logging import SQL_LOGGER, get_logger
27
+
28
+
29
+ @dataclass
30
+ class Database:
31
+ """引擎与会话工厂的持有者(单例)。"""
32
+
33
+ engine: AsyncEngine
34
+ session_factory: async_sessionmaker[AsyncSession]
35
+ read_engines: list[AsyncEngine] = field(default_factory=list)
36
+ _read_cursor: int = 0
37
+
38
+ @property
39
+ def dialect(self) -> str:
40
+ return self.engine.dialect.name
41
+
42
+ def read_engine(self) -> AsyncEngine:
43
+ if not self.read_engines:
44
+ return self.engine
45
+ self._read_cursor = (self._read_cursor + 1) % len(self.read_engines)
46
+ return self.read_engines[self._read_cursor]
47
+
48
+ async def aclose(self) -> None:
49
+ for engine in [self.engine, *self.read_engines]:
50
+ await engine.dispose()
51
+
52
+
53
+ def _sqlite_pragmas(engine: AsyncEngine, *, wal: bool, busy_timeout_ms: int) -> None:
54
+ @event.listens_for(engine.sync_engine, "connect")
55
+ def _on_connect(dbapi_connection: Any, _record: Any) -> None: # pragma: no cover - 驱动回调
56
+ cursor = dbapi_connection.cursor()
57
+ try:
58
+ if wal:
59
+ cursor.execute("PRAGMA journal_mode=WAL")
60
+ cursor.execute("PRAGMA foreign_keys=ON")
61
+ cursor.execute(f"PRAGMA busy_timeout={busy_timeout_ms}")
62
+ finally:
63
+ cursor.close()
64
+
65
+
66
+ def _engine_kwargs(settings: Settings) -> dict[str, Any]:
67
+ database = settings.database
68
+ if database.dialect == "sqlite":
69
+ return {
70
+ "echo": database.echo,
71
+ "poolclass": NullPool,
72
+ "connect_args": {"timeout": database.sqlite.busy_timeout_ms / 1000},
73
+ }
74
+ return {
75
+ "echo": database.echo,
76
+ "pool_size": database.pool_size,
77
+ "max_overflow": database.max_overflow,
78
+ "pool_timeout": database.pool_timeout_s,
79
+ "pool_recycle": database.pool_recycle_s,
80
+ "pool_pre_ping": database.pool_pre_ping,
81
+ }
82
+
83
+
84
+ def _install_sql_logging(engine: AsyncEngine, settings: Settings) -> None:
85
+ """把执行过的 SQL 写到 `logs/sql.log`(由 `observability.log_sql` 控制)。
86
+
87
+ 只记语句、耗时、行数与参数个数——**不记参数值**,避免密码/手机号进日志。
88
+ """
89
+ if not settings.observability.log_sql:
90
+ return
91
+ logger = get_logger(SQL_LOGGER)
92
+ limit = settings.observability.log_sql_max_chars
93
+
94
+ @event.listens_for(engine.sync_engine, "before_cursor_execute")
95
+ def _before(conn, cursor, statement, parameters, context, executemany): # type: ignore[no-untyped-def]
96
+ conn.info["sql_started"] = time.perf_counter()
97
+
98
+ @event.listens_for(engine.sync_engine, "after_cursor_execute")
99
+ def _after(conn, cursor, statement, parameters, context, executemany): # type: ignore[no-untyped-def]
100
+ started = conn.info.pop("sql_started", None)
101
+ duration_ms = round((time.perf_counter() - started) * 1000, 3) if started else None
102
+ logger.info(
103
+ "sql.execute",
104
+ statement=statement[:limit],
105
+ duration_ms=duration_ms,
106
+ rowcount=getattr(cursor, "rowcount", None),
107
+ param_count=len(parameters) if hasattr(parameters, "__len__") else None,
108
+ dialect=engine.dialect.name,
109
+ )
110
+
111
+
112
+ def create_engine_for(
113
+ url: str,
114
+ settings: Settings,
115
+ *,
116
+ connect_args: dict[str, Any] | None = None,
117
+ pool_size: int | None = None,
118
+ ) -> AsyncEngine:
119
+ """按 URL 建引擎(租户库/schema 用)。
120
+
121
+ 传 `pool_size` 时使用租户口径(`tenant.pool_size_per_tenant`),避免每个租户
122
+ 都按主库池大小建连接。
123
+ """
124
+ from sqlalchemy.engine import make_url
125
+
126
+ backend = make_url(url).get_backend_name()
127
+ kwargs = _engine_kwargs(settings)
128
+ if pool_size is not None and backend != "sqlite":
129
+ kwargs["pool_size"] = pool_size
130
+ kwargs["max_overflow"] = 0
131
+ if connect_args:
132
+ kwargs["connect_args"] = {**kwargs.get("connect_args", {}), **connect_args}
133
+ engine = create_async_engine(url, **kwargs)
134
+ _install_sql_logging(engine, settings)
135
+ if backend == "sqlite":
136
+ _sqlite_pragmas(
137
+ engine,
138
+ wal=settings.database.sqlite.wal,
139
+ busy_timeout_ms=settings.database.sqlite.busy_timeout_ms,
140
+ )
141
+ return engine
142
+
143
+
144
+ def _make_engine(
145
+ url: str, settings: Settings, *, connect_args: dict[str, Any] | None = None
146
+ ) -> AsyncEngine:
147
+ return create_engine_for(url, settings, connect_args=connect_args)
148
+
149
+
150
+ @event.listens_for(Session, "before_flush")
151
+ def _mark_orm_write(session: Session, _ctx: object, _instances: object) -> None:
152
+ session.info["swiftapi_wrote"] = True
153
+
154
+
155
+ @event.listens_for(Session, "do_orm_execute")
156
+ def _mark_dml_write(state: object) -> None:
157
+ if getattr(state, "is_insert", False) or getattr(state, "is_update", False) or getattr(state, "is_delete", False):
158
+ state.session.info["swiftapi_wrote"] = True # type: ignore[attr-defined]
159
+
160
+
161
+ def create_database(
162
+ settings: Settings,
163
+ *,
164
+ url: str | None = None,
165
+ connect_args: dict[str, Any] | None = None,
166
+ ) -> Database:
167
+ """构建引擎(不建立连接——连接在首次使用时才创建)。
168
+
169
+ `url` / `connect_args` 用于租户独立库、schema search_path 等迁移场景。
170
+ """
171
+ engine = _make_engine(
172
+ url or settings.database.url.get_secret_value(), settings, connect_args=connect_args
173
+ )
174
+ session_factory = async_sessionmaker(
175
+ bind=engine,
176
+ class_=AsyncSession,
177
+ expire_on_commit=False,
178
+ autoflush=False,
179
+ info={"swiftapi_wrote": False},
180
+ )
181
+ read_engines = [
182
+ _make_engine(url.get_secret_value(), settings) for url in settings.database.read_replica_urls
183
+ ]
184
+ return Database(engine=engine, session_factory=session_factory, read_engines=read_engines)
185
+
186
+
187
+ async def ping(database: Database) -> None:
188
+ """就绪探针用:执行一次最轻量查询。"""
189
+ async with database.engine.connect() as connection:
190
+ await connection.execute(text("SELECT 1"))
191
+
192
+
193
+ def statement_timeout_sql(settings: Settings) -> str | None:
194
+ """各方言的语句超时设置语句(用于连接初始化)。"""
195
+ ms = settings.database.statement_timeout_ms
196
+ if settings.database.dialect == "postgresql":
197
+ return f"SET statement_timeout = {ms}"
198
+ if settings.database.dialect == "mysql":
199
+ return f"SET SESSION max_execution_time = {ms}"
200
+ return None
201
+
202
+
203
+ __all__ = [
204
+ "Database",
205
+ "create_database",
206
+ "create_engine_for",
207
+ "ping",
208
+ "statement_timeout_sql",
209
+ ]
@@ -0,0 +1,84 @@
1
+ """存活/就绪探针的检查注册表。
2
+
3
+ 约定(架构文档 §26):
4
+ - `/livez` 只看进程是否能响应,**不查依赖**(否则 DB 抖动会导致 K8s 重启雪崩);
5
+ - `/readyz` 检查依赖,带超时与结果缓存,失败只摘流量不重启。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import time
12
+ from collections.abc import Awaitable, Callable
13
+ from dataclasses import dataclass
14
+
15
+ HealthCheck = Callable[[], Awaitable[None]]
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class CheckResult:
20
+ name: str
21
+ healthy: bool
22
+ latency_ms: float
23
+ detail: str | None = None
24
+
25
+
26
+ class HealthRegistry:
27
+ def __init__(self, *, timeout_s: float = 1.0, cache_ttl_s: float = 5.0) -> None:
28
+ self._checks: dict[str, HealthCheck] = {}
29
+ self._timeout_s = timeout_s
30
+ self._cache_ttl_s = cache_ttl_s
31
+ self._cached_at: float = 0.0
32
+ self._cached: tuple[CheckResult, ...] = ()
33
+
34
+ def register(self, name: str, check: HealthCheck) -> None:
35
+ self._checks[name] = check
36
+
37
+ @property
38
+ def checks(self) -> tuple[str, ...]:
39
+ return tuple(self._checks)
40
+
41
+ async def run(self, *, use_cache: bool = True) -> tuple[CheckResult, ...]:
42
+ now = time.monotonic()
43
+ if use_cache and self._cached and now - self._cached_at < self._cache_ttl_s:
44
+ return self._cached
45
+
46
+ results: list[CheckResult] = []
47
+ for name, check in self._checks.items():
48
+ started = time.perf_counter()
49
+ try:
50
+ await asyncio.wait_for(check(), timeout=self._timeout_s)
51
+ except TimeoutError:
52
+ results.append(
53
+ CheckResult(
54
+ name=name,
55
+ healthy=False,
56
+ latency_ms=round((time.perf_counter() - started) * 1000, 3),
57
+ detail=f"timeout>{self._timeout_s}s",
58
+ )
59
+ )
60
+ except Exception as exc: # 依赖检查自身异常不能打挂探针
61
+ results.append(
62
+ CheckResult(
63
+ name=name,
64
+ healthy=False,
65
+ latency_ms=round((time.perf_counter() - started) * 1000, 3),
66
+ detail=f"{type(exc).__name__}: {exc}",
67
+ )
68
+ )
69
+ else:
70
+ results.append(
71
+ CheckResult(
72
+ name=name,
73
+ healthy=True,
74
+ latency_ms=round((time.perf_counter() - started) * 1000, 3),
75
+ )
76
+ )
77
+
78
+ self._cached = tuple(results)
79
+ self._cached_at = now
80
+ return self._cached
81
+
82
+ def invalidate(self) -> None:
83
+ self._cached_at = 0.0
84
+ self._cached = ()
@@ -0,0 +1 @@
1
+ """迁移引擎包。"""
@@ -0,0 +1,162 @@
1
+ """DDL 生成与结构 diff(确定性:同一快照必产出同一批语句)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from swiftapi.core.db.dialects.base import DialectAdapter
8
+ from swiftapi.core.db.migrate.schema import (
9
+ ColumnSpec,
10
+ IndexSpec,
11
+ SchemaSnapshot,
12
+ TableSpec,
13
+ type_sql_for,
14
+ )
15
+
16
+
17
+ class MigrationUnsupported(RuntimeError):
18
+ """当前方言不支持自动生成该变更:必须手写迁移。"""
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class Statement:
23
+ sql: str
24
+ description: str
25
+ destructive: bool = False
26
+
27
+
28
+ def _qualified(table: TableSpec, adapter: DialectAdapter) -> str:
29
+ return adapter.qualify(table.namespace, table.name)
30
+
31
+
32
+ def _normalized_default(default: str | None, adapter: DialectAdapter) -> str | None:
33
+ if not default:
34
+ return None
35
+ lowered = default.lower()
36
+ if "now()" in lowered or "current_timestamp" in lowered:
37
+ return adapter.current_timestamp_sql
38
+ return default
39
+
40
+
41
+ def _column_sql(column: ColumnSpec, adapter: DialectAdapter) -> str:
42
+ sql = f"{adapter.quote(column.name)} {type_sql_for(column, adapter.dialect_cls())}"
43
+ default = _normalized_default(column.default, adapter)
44
+ if default:
45
+ sql += f" DEFAULT {default}"
46
+ if not column.nullable and not column.primary_key:
47
+ sql += " NOT NULL"
48
+ return sql
49
+
50
+
51
+ def create_table(table: TableSpec, adapter: DialectAdapter) -> list[Statement]:
52
+ columns = ",\n ".join(_column_sql(column, adapter) for column in table.columns)
53
+ primary_key = table.primary_key
54
+ pk_sql = (
55
+ f",\n PRIMARY KEY ({', '.join(adapter.quote(name) for name in primary_key)})"
56
+ if primary_key
57
+ else ""
58
+ )
59
+ statements = [
60
+ Statement(
61
+ sql=f"CREATE TABLE {_qualified(table, adapter)} (\n {columns}{pk_sql}\n)",
62
+ description=f"建表 {table.key}",
63
+ )
64
+ ]
65
+ statements.extend(create_index(table, index, adapter) for index in table.indexes)
66
+ return statements
67
+
68
+
69
+ def create_index(table: TableSpec, index: IndexSpec, adapter: DialectAdapter) -> Statement:
70
+ return Statement(
71
+ sql=adapter.create_index_sql(
72
+ name=index.name,
73
+ qualified_table=_qualified(table, adapter),
74
+ columns=list(index.columns),
75
+ unique=index.unique,
76
+ where=index.where,
77
+ ),
78
+ description=f"建索引 {index.name}",
79
+ )
80
+
81
+
82
+ def drop_index(table: TableSpec, index: IndexSpec, adapter: DialectAdapter) -> Statement:
83
+ return Statement(
84
+ sql=f"DROP INDEX {adapter.quote(index.name)}",
85
+ description=f"删索引 {index.name}",
86
+ destructive=True,
87
+ )
88
+
89
+
90
+ def add_column(table: TableSpec, column: ColumnSpec, adapter: DialectAdapter) -> Statement:
91
+ return Statement(
92
+ sql=f"ALTER TABLE {_qualified(table, adapter)} ADD COLUMN {_column_sql(column, adapter)}",
93
+ description=f"加列 {table.key}.{column.name}",
94
+ )
95
+
96
+
97
+ def drop_column(table: TableSpec, column: ColumnSpec, adapter: DialectAdapter) -> Statement:
98
+ if adapter.name == "sqlite":
99
+ raise MigrationUnsupported(
100
+ f"SQLite 不支持 DROP COLUMN({table.key}.{column.name}):请改用 batch 重建(规划中)或手写迁移"
101
+ )
102
+ return Statement(
103
+ sql=f"ALTER TABLE {_qualified(table, adapter)} DROP COLUMN {adapter.quote(column.name)}",
104
+ description=f"删列 {table.key}.{column.name}",
105
+ destructive=True,
106
+ )
107
+
108
+
109
+ def _column_changes(existing: TableSpec, table: TableSpec, adapter: DialectAdapter) -> list[Statement]:
110
+ statements: list[Statement] = []
111
+ existing_columns = {column.name: column for column in existing.columns}
112
+ target_columns = {column.name: column for column in table.columns}
113
+
114
+ for column in table.columns:
115
+ previous = existing_columns.get(column.name)
116
+ if previous is None:
117
+ statements.append(add_column(table, column, adapter))
118
+ elif type_sql_for(previous, adapter.dialect_cls()).lower() != type_sql_for(
119
+ column, adapter.dialect_cls()
120
+ ).lower():
121
+ raise MigrationUnsupported(
122
+ f"列类型变更需要手写迁移:{table.key}.{column.name} "
123
+ f"{type_sql_for(previous, adapter.dialect_cls())} → "
124
+ f"{type_sql_for(column, adapter.dialect_cls())}"
125
+ )
126
+ for column in existing.columns:
127
+ if column.name not in target_columns:
128
+ statements.append(drop_column(table, column, adapter))
129
+ return statements
130
+
131
+
132
+ def _index_changes(existing: TableSpec, table: TableSpec, adapter: DialectAdapter) -> list[Statement]:
133
+ statements: list[Statement] = []
134
+ existing_indexes = {index.name: index for index in existing.indexes}
135
+ target_indexes = {index.name: index for index in table.indexes}
136
+
137
+ for name, index in sorted(target_indexes.items()):
138
+ previous = existing_indexes.get(name)
139
+ if previous is None:
140
+ statements.append(create_index(table, index, adapter))
141
+ elif previous != index:
142
+ statements.append(drop_index(table, previous, adapter))
143
+ statements.append(create_index(table, index, adapter))
144
+ for name, index in sorted(existing_indexes.items()):
145
+ if name not in target_indexes:
146
+ statements.append(drop_index(table, index, adapter))
147
+ return statements
148
+
149
+
150
+ def diff(current: SchemaSnapshot, target: SchemaSnapshot, adapter: DialectAdapter) -> list[Statement]:
151
+ """确定性 diff:新建表 → 列变更 → 索引变更。"""
152
+ statements: list[Statement] = []
153
+ for key, table in sorted(target.tables.items()):
154
+ if key not in current.tables:
155
+ statements.extend(create_table(table, adapter))
156
+ for key, table in sorted(target.tables.items()):
157
+ existing = current.tables.get(key)
158
+ if existing is None:
159
+ continue
160
+ statements.extend(_column_changes(existing, table, adapter))
161
+ statements.extend(_index_changes(existing, table, adapter))
162
+ return statements
@@ -0,0 +1,84 @@
1
+ """迁移文件:生成、加载、校验和。
2
+
3
+ 迁移文件只存"目标结构(快照)",DDL 在 apply 时由 diff 生成——
4
+ 这样同一份迁移可以在 PG / MySQL / SQLite 上执行,而不必为每个方言各写一份。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import importlib.util
11
+ import secrets
12
+ from dataclasses import dataclass
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+
16
+ from swiftapi.core.db.migrate.schema import SchemaSnapshot
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Revision:
21
+ revision: str
22
+ message: str
23
+ previous: str | None
24
+ target: SchemaSnapshot
25
+ checksum: str
26
+
27
+
28
+ def new_revision_id() -> str:
29
+ stamp = datetime.now(UTC).strftime("%Y%m%d%H%M%S")
30
+ return f"{stamp}_{secrets.token_hex(3)}"
31
+
32
+
33
+ def checksum_of(target: SchemaSnapshot) -> str:
34
+ return hashlib.sha256(target.to_json().encode()).hexdigest()[:16]
35
+
36
+
37
+ def render(revision: str, message: str, previous: str | None, target: SchemaSnapshot) -> str:
38
+ payload = target.to_json()
39
+ return f'''"""Auto-generated by swiftapi db revision. 修改会被 checksum 检出。"""
40
+
41
+ import json
42
+
43
+ REVISION = "{revision}"
44
+ MESSAGE = {message!r}
45
+ PREVIOUS = {previous!r}
46
+ CHECKSUM = "{checksum_of(target)}"
47
+
48
+ TARGET = json.loads({payload!r})
49
+ '''
50
+
51
+
52
+ def write_revision(
53
+ directory: Path, *, message: str, previous: str | None, target: SchemaSnapshot
54
+ ) -> Path:
55
+ directory.mkdir(parents=True, exist_ok=True)
56
+ revision = new_revision_id()
57
+ path = directory / f"{revision}.py"
58
+ path.write_text(render(revision, message, previous, target), encoding="utf-8")
59
+ return path
60
+
61
+
62
+ def load_chain(directory: Path) -> list[Revision]:
63
+ if not directory.exists():
64
+ return []
65
+ revisions: list[Revision] = []
66
+ for path in sorted(directory.glob("*.py")):
67
+ if path.name.startswith("_"):
68
+ continue
69
+ spec = importlib.util.spec_from_file_location(f"swiftapi_migration_{path.stem}", path)
70
+ if spec is None or spec.loader is None: # pragma: no cover
71
+ continue
72
+ module = importlib.util.module_from_spec(spec)
73
+ spec.loader.exec_module(module)
74
+ target = SchemaSnapshot.from_json(module.TARGET)
75
+ revisions.append(
76
+ Revision(
77
+ revision=str(module.REVISION),
78
+ message=str(module.MESSAGE),
79
+ previous=module.PREVIOUS,
80
+ target=target,
81
+ checksum=str(getattr(module, "CHECKSUM", checksum_of(target))),
82
+ )
83
+ )
84
+ return revisions
@@ -0,0 +1,159 @@
1
+ """迁移执行器:加锁 → 校验 → 反射 → diff → 执行 → 记录。
2
+
3
+ 不变量:
4
+ 1. 已应用的迁移文件被修改(checksum 不符)→ 拒绝执行;
5
+ 2. 破坏性变更默认拒绝,必须显式 `--allow-destructive`;
6
+ 3. 每次只执行"当前库 → 目标快照"的差量,天然幂等。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import UTC, datetime
13
+ from typing import Any
14
+
15
+ from swiftapi.core.db.dialects.base import DialectAdapter
16
+ from swiftapi.core.db.engine import Database
17
+ from swiftapi.core.db.migrate.ddl import Statement, diff
18
+ from swiftapi.core.db.migrate.render import Revision
19
+ from swiftapi.core.db.migrate.schema import reflect
20
+
21
+ HISTORY_NAMESPACE = "platform"
22
+ HISTORY_TABLE = "schema_migrations"
23
+
24
+
25
+ class MigrationError(RuntimeError):
26
+ """迁移失败基类。"""
27
+
28
+
29
+ class MigrationChecksumMismatch(MigrationError):
30
+ pass
31
+
32
+
33
+ class MigrationDestructive(MigrationError):
34
+ pass
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class AppliedRevision:
39
+ revision: str
40
+ checksum: str
41
+ message: str
42
+ applied_at: str
43
+
44
+
45
+ class MigrationRunner:
46
+ def __init__(self, database: Database, adapter: DialectAdapter) -> None:
47
+ self.database = database
48
+ self.adapter = adapter
49
+ self._history_qualified = adapter.qualify(HISTORY_NAMESPACE, HISTORY_TABLE)
50
+
51
+ async def ensure_namespaces(self, namespaces: set[str]) -> None:
52
+ async with self.database.engine.begin() as connection:
53
+ for namespace in sorted(namespaces):
54
+ statement = self.adapter.namespace_sql(namespace)
55
+ if statement:
56
+ await connection.exec_driver_sql(statement)
57
+
58
+ async def ensure_history(self) -> None:
59
+ await self.ensure_namespaces({HISTORY_NAMESPACE})
60
+ # 表名来自适配器的 quote()(受控常量),不是用户输入
61
+ sql = (
62
+ f"CREATE TABLE IF NOT EXISTS {self._history_qualified} (" # nosec B608
63
+ "revision VARCHAR(64) PRIMARY KEY, "
64
+ "checksum VARCHAR(64) NOT NULL, "
65
+ "message VARCHAR(255) NOT NULL, "
66
+ "applied_at VARCHAR(32) NOT NULL)"
67
+ )
68
+ async with self.database.engine.begin() as connection:
69
+ await connection.exec_driver_sql(sql)
70
+
71
+ async def applied(self) -> list[AppliedRevision]:
72
+ sql = (
73
+ f"SELECT revision, checksum, message, applied_at FROM {self._history_qualified}" # nosec B608
74
+ )
75
+ async with self.database.engine.connect() as connection:
76
+ result = await connection.exec_driver_sql(sql)
77
+ rows = [tuple(row) for row in result.fetchall()]
78
+ return [AppliedRevision(*row) for row in rows]
79
+
80
+ async def upgrade(
81
+ self,
82
+ chain: list[Revision],
83
+ *,
84
+ allow_destructive: bool = False,
85
+ dry_run: bool = False,
86
+ ) -> list[Statement]:
87
+ await self.ensure_history()
88
+ applied = {item.revision: item.checksum for item in await self.applied()}
89
+
90
+ for revision in chain:
91
+ recorded = applied.get(revision.revision)
92
+ if recorded is not None and recorded != revision.checksum:
93
+ raise MigrationChecksumMismatch(
94
+ f"迁移 {revision.revision} 已应用但文件被修改(checksum {recorded} ≠ {revision.checksum})"
95
+ )
96
+
97
+ executed: list[Statement] = []
98
+ pending = [revision for revision in chain if revision.revision not in applied]
99
+ for revision in pending:
100
+ statements = await self._statements_for(revision)
101
+ destructive = [statement for statement in statements if statement.destructive]
102
+ if destructive and not allow_destructive:
103
+ joined = "\n".join(f" - {item.description}" for item in destructive)
104
+ raise MigrationDestructive(
105
+ f"迁移 {revision.revision} 包含破坏性变更,需 --allow-destructive:\n{joined}"
106
+ )
107
+ if dry_run:
108
+ executed.extend(statements)
109
+ continue
110
+ await self._execute(revision, statements)
111
+ executed.extend(statements)
112
+ return executed
113
+
114
+ async def _statements_for(self, revision: Revision) -> list[Statement]:
115
+ async with self.database.engine.connect() as connection:
116
+ live = await connection.run_sync(
117
+ lambda sync_connection: reflect(sync_connection, self.adapter, revision.target)
118
+ )
119
+ return diff(live, revision.target, self.adapter)
120
+
121
+ async def _execute(self, revision: Revision, statements: list[Statement]) -> None:
122
+ await self.ensure_namespaces({table.namespace for table in revision.target.tables.values()})
123
+ async with self.database.engine.begin() as connection:
124
+ for statement in statements:
125
+ await connection.exec_driver_sql(statement.sql)
126
+ await self._record(connection, revision)
127
+
128
+ async def _record(self, connection: Any, revision: Revision) -> None:
129
+ from sqlalchemy import text
130
+
131
+ # 表名是受控常量;迁移说明是用户输入,必须走绑定参数而不是拼字符串
132
+ sql = text(
133
+ f"INSERT INTO {self._history_qualified} " # nosec B608 - 表名受控,值走绑定参数
134
+ "(revision, checksum, message, applied_at) "
135
+ "VALUES (:revision, :checksum, :message, :applied_at)"
136
+ )
137
+ await connection.execute(
138
+ sql,
139
+ {
140
+ "revision": revision.revision,
141
+ "checksum": revision.checksum,
142
+ "message": revision.message[:250],
143
+ "applied_at": datetime.now(UTC).isoformat(),
144
+ },
145
+ )
146
+
147
+
148
+ def describe(statements: list[Statement]) -> str:
149
+ return "\n".join(f"[{'DESTRUCTIVE' if s.destructive else 'OK'}] {s.sql}" for s in statements)
150
+
151
+
152
+ __all__ = [
153
+ "AppliedRevision",
154
+ "MigrationChecksumMismatch",
155
+ "MigrationDestructive",
156
+ "MigrationError",
157
+ "MigrationRunner",
158
+ "describe",
159
+ ]