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,242 @@
1
+ """CRUD 基类:数据访问的唯一入口(架构文档 §8.4)。
2
+
3
+ 三条硬约束:
4
+ 1. **不含业务规则**:校验、事件、授权都在 service;
5
+ 2. **不提交事务**:提交权归 UnitOfWork;
6
+ 3. **租户过滤失败即拒绝**:租户表的任何查询都必须给出 tenant_id,
7
+ 给不出来就抛 `TenantRequired`(fail closed,不接受"忘了传")。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping, Sequence
13
+ from typing import Any, cast
14
+ from uuid import UUID
15
+
16
+ from pydantic import BaseModel as PydanticModel
17
+ from sqlalchemy import Select, func, select, update
18
+ from sqlalchemy.engine import CursorResult
19
+ from sqlalchemy.ext.asyncio import AsyncSession
20
+
21
+ from swiftapi.core.db.base_model import BaseModel
22
+ from swiftapi.core.errors.base import InvalidArgument, NotFound, TenantRequired, VersionConflict
23
+ from swiftapi.core.observability.logging import CRUD_LOGGER, get_logger
24
+
25
+ MAX_LIMIT = 100
26
+
27
+ logger = get_logger(CRUD_LOGGER)
28
+
29
+
30
+ class CRUDBase[ModelT: BaseModel]:
31
+ model: type[ModelT]
32
+
33
+ def __init__(self, model: type[ModelT]) -> None:
34
+ self.model = model
35
+ self._entity: Any = model # 动态列访问(mypy 无法推断 Mapped[])
36
+ self._columns = {column.name for column in model.__table__.columns}
37
+
38
+ # ---------------- 租户 ----------------
39
+
40
+ def _tenant_id(self, tenant_id: UUID | None) -> UUID | None:
41
+ if self.model.__tenant_scoped__:
42
+ if tenant_id is None:
43
+ raise TenantRequired(
44
+ f"{self.model.__name__} 是租户表,查询必须提供 tenant_id(fail closed)"
45
+ )
46
+ return tenant_id
47
+ return None
48
+
49
+ def _scoped(self, stmt: Select[Any], tenant_id: UUID | None) -> Select[Any]:
50
+ scoped_tenant = self._tenant_id(tenant_id)
51
+ if scoped_tenant is None:
52
+ return stmt
53
+ return stmt.where(self._entity.tenant_id == scoped_tenant)
54
+
55
+ def _filtered(self, stmt: Select[Any], filters: Mapping[str, Any] | None) -> Select[Any]:
56
+ for key, value in (filters or {}).items():
57
+ if key not in self._columns:
58
+ raise InvalidArgument(f"未知过滤字段: {key}({self.model.__name__})")
59
+ stmt = stmt.where(getattr(self._entity, key) == value)
60
+ return stmt
61
+
62
+ def _sorted(self, stmt: Select[Any], order_by: str | Sequence[str] | None) -> Select[Any]:
63
+ if not order_by:
64
+ return stmt
65
+ clauses = [order_by] if isinstance(order_by, str) else list(order_by)
66
+ for clause in clauses:
67
+ descending = clause.startswith("-")
68
+ name = clause[1:] if descending else clause
69
+ if name not in self._columns:
70
+ raise InvalidArgument(f"未知排序字段: {name}({self.model.__name__})")
71
+ column = getattr(self._entity, name)
72
+ stmt = stmt.order_by(column.desc() if descending else column.asc())
73
+ return stmt
74
+
75
+ def _not_deleted(self, stmt: Select[Any], include_deleted: bool) -> Select[Any]:
76
+ if not include_deleted and "deleted_at" in self._columns:
77
+ stmt = stmt.where(self._entity.deleted_at.is_(None))
78
+ return stmt
79
+
80
+ # ---------------- 读 ----------------
81
+
82
+ async def get(
83
+ self,
84
+ session: AsyncSession,
85
+ obj_id: Any,
86
+ *,
87
+ tenant_id: UUID | None = None,
88
+ include_deleted: bool = False,
89
+ ) -> ModelT | None:
90
+ stmt = select(self.model).where(self._entity.id == obj_id)
91
+ stmt = self._not_deleted(self._scoped(stmt, tenant_id), include_deleted)
92
+ return (await session.execute(stmt)).scalar_one_or_none()
93
+
94
+ async def get_or_raise(
95
+ self,
96
+ session: AsyncSession,
97
+ obj_id: Any,
98
+ *,
99
+ tenant_id: UUID | None = None,
100
+ include_deleted: bool = False,
101
+ ) -> ModelT:
102
+ instance = await self.get(
103
+ session, obj_id, tenant_id=tenant_id, include_deleted=include_deleted
104
+ )
105
+ if instance is None:
106
+ raise NotFound(f"{self.model.__name__} {obj_id} 不存在")
107
+ return instance
108
+
109
+ async def list(
110
+ self,
111
+ session: AsyncSession,
112
+ *,
113
+ tenant_id: UUID | None = None,
114
+ filters: Mapping[str, Any] | None = None,
115
+ order_by: str | Sequence[str] | None = None,
116
+ limit: int = 20,
117
+ offset: int = 0,
118
+ include_deleted: bool = False,
119
+ ) -> tuple[list[ModelT], int]:
120
+ limit = max(1, min(limit, MAX_LIMIT))
121
+ offset = max(0, offset)
122
+ base = select(self.model)
123
+ base = self._not_deleted(self._scoped(base, tenant_id), include_deleted)
124
+ base = self._filtered(base, filters)
125
+
126
+ total = (
127
+ await session.execute(select(func.count()).select_from(base.subquery()))
128
+ ).scalar_one()
129
+ page_stmt = self._sorted(base, order_by).limit(limit).offset(offset)
130
+ rows = list((await session.execute(page_stmt)).scalars())
131
+ return rows, int(total)
132
+
133
+ async def exists(self, session: AsyncSession, **filters: Any) -> bool:
134
+ tenant_id = filters.pop("tenant_id", None)
135
+ stmt = self._filtered(select(self.model), filters)
136
+ stmt = self._scoped(stmt, tenant_id).limit(1)
137
+ return (await session.execute(stmt)).first() is not None
138
+
139
+ # ---------------- 写 ----------------
140
+
141
+ async def create(
142
+ self,
143
+ session: AsyncSession,
144
+ values: Mapping[str, Any] | PydanticModel,
145
+ *,
146
+ tenant_id: UUID | None = None,
147
+ ) -> ModelT:
148
+ data = (
149
+ values.model_dump(exclude_unset=True)
150
+ if isinstance(values, PydanticModel)
151
+ else dict(values)
152
+ )
153
+ unknown = set(data) - self._columns
154
+ if unknown:
155
+ raise InvalidArgument(f"未知字段: {sorted(unknown)}({self.model.__name__})")
156
+ scoped_tenant = self._tenant_id(tenant_id)
157
+ if scoped_tenant is not None:
158
+ data.setdefault("tenant_id", scoped_tenant)
159
+ instance = self.model(**data)
160
+ session.add(instance)
161
+ await session.flush()
162
+ logger.info(
163
+ "crud.create",
164
+ model=self.model.__name__,
165
+ id=str(getattr(instance, "id", "")),
166
+ tenant_id=str(tenant_id) if tenant_id else None,
167
+ fields=sorted(data),
168
+ )
169
+ return instance
170
+
171
+ async def update(
172
+ self,
173
+ session: AsyncSession,
174
+ instance: ModelT,
175
+ values: Mapping[str, Any] | PydanticModel,
176
+ ) -> ModelT:
177
+ data = (
178
+ values.model_dump(exclude_unset=True)
179
+ if isinstance(values, PydanticModel)
180
+ else dict(values)
181
+ )
182
+ protected = {"id", "tenant_id", "created_at", "version"}
183
+ unknown = set(data) - self._columns
184
+ if unknown:
185
+ raise InvalidArgument(f"未知字段: {sorted(unknown)}({self.model.__name__})")
186
+ data = {key: value for key, value in data.items() if key not in protected}
187
+
188
+ if "version" in self._columns:
189
+ # 乐观锁:`WHERE version = 读取时的值`,0 行即并发冲突。
190
+ # 只靠 ORM setattr + flush 是 last-write-wins,会静默覆盖别人的修改。
191
+ current = cast(Any, instance)
192
+ expected = int(current.version)
193
+ conditions = [self._entity.id == current.id]
194
+ if "tenant_id" in self._columns:
195
+ conditions.append(self._entity.tenant_id == current.tenant_id)
196
+ statement = (
197
+ update(self.model)
198
+ .where(*conditions, self._entity.version == expected)
199
+ .values(**data, version=expected + 1)
200
+ )
201
+ result = await session.execute(statement)
202
+ if not cast(CursorResult[Any], result).rowcount:
203
+ raise VersionConflict(
204
+ f"{self.model.__name__} {getattr(instance, 'id', '')} 已被其他请求修改"
205
+ f"(期望 version={expected})"
206
+ )
207
+ await session.refresh(instance)
208
+ else:
209
+ for key, value in data.items():
210
+ setattr(instance, key, value)
211
+ await session.flush()
212
+
213
+ logger.info(
214
+ "crud.update",
215
+ model=self.model.__name__,
216
+ id=str(getattr(instance, "id", "")),
217
+ fields=sorted(data),
218
+ )
219
+ return instance
220
+
221
+ async def delete(self, session: AsyncSession, instance: ModelT, *, soft: bool = True) -> None:
222
+ if soft and "deleted_at" in self._columns:
223
+ from datetime import UTC, datetime
224
+
225
+ cast(Any, instance).deleted_at = datetime.now(UTC)
226
+ await session.flush()
227
+ logger.info(
228
+ "crud.soft_delete",
229
+ model=self.model.__name__,
230
+ id=str(getattr(instance, "id", "")),
231
+ )
232
+ return
233
+ await session.delete(instance)
234
+ await session.flush()
235
+ logger.info(
236
+ "crud.delete",
237
+ model=self.model.__name__,
238
+ id=str(getattr(instance, "id", "")),
239
+ )
240
+
241
+
242
+ __all__ = ["MAX_LIMIT", "CRUDBase"]
@@ -0,0 +1,8 @@
1
+ """方言适配器包。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from swiftapi.core.db.dialects.base import Capability, DialectAdapter, UnsupportedDialectError
6
+ from swiftapi.core.db.dialects.registry import capabilities_of, get_adapter
7
+
8
+ __all__ = ["Capability", "DialectAdapter", "UnsupportedDialectError", "capabilities_of", "get_adapter"]
@@ -0,0 +1,106 @@
1
+ """方言适配器:把 PG / MySQL / SQLite 的差异收敛到唯一出口。
2
+
3
+ 业务代码禁止出现 `if dialect == ...`;需要差异时问适配器要能力(capability)。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from abc import ABC, abstractmethod
9
+ from enum import StrEnum
10
+ from typing import Any
11
+
12
+
13
+ class UnsupportedDialectError(RuntimeError):
14
+ """连接串方言不在支持列表:启动期失败,不做"猜一个方言试试"。"""
15
+
16
+
17
+ class Capability(StrEnum):
18
+ SKIP_LOCKED = "skip_locked"
19
+ PARTIAL_INDEX = "partial_index"
20
+ EXPRESSIVE_INDEX = "expressive_index"
21
+ DDL_TRANSACTION = "ddl_transaction"
22
+ ADVISORY_LOCK = "advisory_lock"
23
+ NATIVE_UUID = "native_uuid"
24
+ JSON_TYPE = "json_type"
25
+ ARRAY = "array"
26
+ UPSERT = "upsert"
27
+ SCHEMA = "schema"
28
+ CONCURRENT_INDEX = "concurrent_index"
29
+
30
+
31
+ class DialectAdapter(ABC):
32
+ name: str
33
+ capabilities: frozenset[Capability]
34
+
35
+ # ---------------- 类型编译 ----------------
36
+
37
+ @abstractmethod
38
+ def dialect_cls(self) -> Any:
39
+ """返回 SQLAlchemy 方言实例,用于把抽象类型编译成方言 SQL。"""
40
+
41
+ # ---------------- 标识符 ----------------
42
+
43
+ @property
44
+ @abstractmethod
45
+ def quote_char(self) -> str: ...
46
+
47
+ @property
48
+ @abstractmethod
49
+ def namespace_separator(self) -> str: ...
50
+
51
+ def quote(self, identifier: str) -> str:
52
+ escaped = identifier.replace(self.quote_char, self.quote_char * 2)
53
+ return f"{self.quote_char}{escaped}{self.quote_char}"
54
+
55
+ def qualify(self, namespace: str, table: str) -> str:
56
+ """物理表名。
57
+
58
+ 历史设计曾把 namespace 拼进物理名(PG schema / MySQL 前缀),但运行期
59
+ SQLAlchemy 生成的 SQL 用的是裸表名 —— 两者不一致会导致
60
+ "迁移建了 helpdesk__ticket,查询却在找 ticket"(cleanroom 验证发现)。
61
+ 现在统一为:**命名空间只是逻辑元数据**,物理名就是表名。
62
+ 真正的 schema 隔离属于 P3(需要 model 层按方言声明 schema)。
63
+ """
64
+ return self.quote(table)
65
+
66
+ def physical_location(self, namespace: str, table: str) -> tuple[str, str | None]:
67
+ """返回 (物理表名, schema)。当前命名空间不参与物理命名。"""
68
+ return table, None
69
+
70
+ # ---------------- 默认值 ----------------
71
+
72
+ @property
73
+ def current_timestamp_sql(self) -> str:
74
+ """`func.now()` 在各方言的字面量。SQLite 只认 CURRENT_TIMESTAMP。"""
75
+ return "now()"
76
+
77
+ # ---------------- 能力 ----------------
78
+
79
+ def has(self, capability: Capability) -> bool:
80
+ return capability in self.capabilities
81
+
82
+ @property
83
+ def supports_ddl_transaction(self) -> bool:
84
+ return self.has(Capability.DDL_TRANSACTION)
85
+
86
+ # ---------------- 迁移辅助 ----------------
87
+
88
+ @property
89
+ def max_identifier_length(self) -> int:
90
+ return 63
91
+
92
+ def lock_sql(self, key: str) -> str | None:
93
+ """迁移互斥锁;None 表示该方言没有可用的库级锁。"""
94
+ return None
95
+
96
+ def namespace_sql(self, namespace: str) -> str | None:
97
+ """当前不做物理 schema 隔离,恒为 None(保留接口给 P3)。"""
98
+ return None
99
+
100
+ @abstractmethod
101
+ def create_index_sql(
102
+ self, *, name: str, qualified_table: str, columns: list[str], unique: bool, where: str | None
103
+ ) -> str: ...
104
+
105
+
106
+ __all__ = ["Capability", "DialectAdapter", "UnsupportedDialectError"]
@@ -0,0 +1,47 @@
1
+ """MySQL 8:Tier 2,无部分索引/数组/原生 UUID,DDL 隐式提交。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from sqlalchemy.dialects.mysql import dialect as mysql_dialect
8
+
9
+ from swiftapi.core.db.dialects.base import Capability, DialectAdapter
10
+
11
+
12
+ class MySQLAdapter(DialectAdapter):
13
+ name = "mysql"
14
+ quote_char = "`"
15
+ namespace_separator = "__"
16
+ capabilities = frozenset(
17
+ {
18
+ Capability.SKIP_LOCKED,
19
+ Capability.EXPRESSIVE_INDEX,
20
+ Capability.ADVISORY_LOCK,
21
+ Capability.JSON_TYPE,
22
+ Capability.UPSERT,
23
+ }
24
+ )
25
+
26
+ @property
27
+ def current_timestamp_sql(self) -> str:
28
+ return "CURRENT_TIMESTAMP(6)"
29
+
30
+ def dialect_cls(self) -> Any:
31
+ return mysql_dialect()
32
+
33
+ @property
34
+ def max_identifier_length(self) -> int:
35
+ return 64
36
+
37
+ def lock_sql(self, key: str) -> str | None:
38
+ return f"SELECT GET_LOCK({self.quote(key)}, 30)"
39
+
40
+ def create_index_sql(
41
+ self, *, name: str, qualified_table: str, columns: list[str], unique: bool, where: str | None
42
+ ) -> str:
43
+ if where:
44
+ raise NotImplementedError("MySQL 不支持部分索引;请改写为生成列 + 唯一索引(架构文档 §16.3)")
45
+ unique_sql = "UNIQUE " if unique else ""
46
+ target = ", ".join(self.quote(column) for column in columns)
47
+ return f"CREATE {unique_sql}INDEX {self.quote(name)} ON {qualified_table} ({target})"
@@ -0,0 +1,51 @@
1
+ """PostgreSQL:Tier 1,全能力。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from sqlalchemy.dialects.postgresql import dialect as pg_dialect
8
+
9
+ from swiftapi.core.db.dialects.base import Capability, DialectAdapter
10
+
11
+
12
+ class PostgresAdapter(DialectAdapter):
13
+ name = "postgresql"
14
+ quote_char = '"'
15
+ namespace_separator = "."
16
+ capabilities = frozenset(
17
+ {
18
+ Capability.SKIP_LOCKED,
19
+ Capability.PARTIAL_INDEX,
20
+ Capability.EXPRESSIVE_INDEX,
21
+ Capability.DDL_TRANSACTION,
22
+ Capability.ADVISORY_LOCK,
23
+ Capability.NATIVE_UUID,
24
+ Capability.JSON_TYPE,
25
+ Capability.ARRAY,
26
+ Capability.UPSERT,
27
+ Capability.SCHEMA,
28
+ Capability.CONCURRENT_INDEX,
29
+ }
30
+ )
31
+
32
+ def dialect_cls(self) -> Any:
33
+ return pg_dialect() # type: ignore[no-untyped-call]
34
+
35
+ @property
36
+ def max_identifier_length(self) -> int:
37
+ return 63
38
+
39
+ def lock_sql(self, key: str) -> str | None:
40
+ # 64-bit 哈希避免超长 key 报错
41
+ return f"SELECT pg_advisory_lock(hashtext({self.quote(key)}))"
42
+
43
+ def create_index_sql(
44
+ self, *, name: str, qualified_table: str, columns: list[str], unique: bool, where: str | None
45
+ ) -> str:
46
+ unique_sql = "UNIQUE " if unique else ""
47
+ target = ", ".join(self.quote(column) for column in columns)
48
+ sql = f"CREATE {unique_sql}INDEX {self.quote(name)} ON {qualified_table} ({target})"
49
+ if where:
50
+ sql += f" WHERE {where}"
51
+ return sql
@@ -0,0 +1,30 @@
1
+ """按方言取适配器:唯一的选择入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from swiftapi.core.db.dialects.base import Capability, DialectAdapter, UnsupportedDialectError
6
+ from swiftapi.core.db.dialects.mysql import MySQLAdapter
7
+ from swiftapi.core.db.dialects.pg import PostgresAdapter
8
+ from swiftapi.core.db.dialects.sqlite import SQLiteAdapter
9
+
10
+ _ADAPTERS: dict[str, DialectAdapter] = {
11
+ "postgresql": PostgresAdapter(),
12
+ "mysql": MySQLAdapter(),
13
+ "sqlite": SQLiteAdapter(),
14
+ }
15
+
16
+
17
+ def get_adapter(dialect: str) -> DialectAdapter:
18
+ try:
19
+ return _ADAPTERS[dialect]
20
+ except KeyError as exc:
21
+ raise UnsupportedDialectError(
22
+ f"不支持的数据库方言: {dialect!r};仅支持 {sorted(_ADAPTERS)}"
23
+ ) from exc
24
+
25
+
26
+ def capabilities_of(dialect: str) -> frozenset[Capability]:
27
+ return get_adapter(dialect).capabilities
28
+
29
+
30
+ __all__ = ["capabilities_of", "get_adapter"]
@@ -0,0 +1,47 @@
1
+ """SQLite:Tier 3,单写者,无 SKIP LOCKED / 无并发建索引。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from sqlalchemy.dialects.sqlite import dialect as sqlite_dialect
8
+
9
+ from swiftapi.core.db.dialects.base import Capability, DialectAdapter
10
+
11
+
12
+ class SQLiteAdapter(DialectAdapter):
13
+ name = "sqlite"
14
+ quote_char = '"'
15
+ namespace_separator = "__"
16
+ capabilities = frozenset(
17
+ {
18
+ Capability.PARTIAL_INDEX,
19
+ Capability.EXPRESSIVE_INDEX,
20
+ Capability.DDL_TRANSACTION,
21
+ Capability.UPSERT,
22
+ }
23
+ )
24
+
25
+ @property
26
+ def current_timestamp_sql(self) -> str:
27
+ return "CURRENT_TIMESTAMP"
28
+
29
+ def dialect_cls(self) -> Any:
30
+ return sqlite_dialect()
31
+
32
+ @property
33
+ def max_identifier_length(self) -> int:
34
+ return 255
35
+
36
+ def lock_sql(self, key: str) -> str | None:
37
+ return None # 无库级锁:迁移由单实例 + 文件锁保证
38
+
39
+ def create_index_sql(
40
+ self, *, name: str, qualified_table: str, columns: list[str], unique: bool, where: str | None
41
+ ) -> str:
42
+ unique_sql = "UNIQUE " if unique else ""
43
+ target = ", ".join(self.quote(column) for column in columns)
44
+ sql = f"CREATE {unique_sql}INDEX {self.quote(name)} ON {qualified_table} ({target})"
45
+ if where:
46
+ sql += f" WHERE {where}"
47
+ return sql