yimo-kit 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.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
yimo/kit/db/audit.py ADDED
@@ -0,0 +1,625 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-10-20
21
+ """审计字段与删除标记的自动填充(仿 MyBatis-Plus MetaObjectHandler)
22
+
23
+ 填充字段(默认列名;时间槽位有内置别名,其余可用 set_fields 覆盖):
24
+
25
+ - ``created_at``(别名 ``create_time``)/ ``created_by``
26
+ - ``updated_at``(别名 ``update_time``)/ ``updated_by``
27
+ - ``deleted``(逻辑删除标记:``0`` 正常 / ``1`` 删除)
28
+
29
+ 查询过滤(需 ``set_soft_delete_filter(True)``):kit 的查询方法对**有 deleted 列的表/模型**
30
+ 追加 ``deleted = 正常值``;需要读已删除记录时用 ``AuditConfig.include_deleted()`` 上下文。
31
+
32
+ 判定规则(唯一):**表中存在该列** 且 **本次写入数据中该字段为空** → 填充。
33
+ "空" 指 ``None`` / 空串 / 纯空白串(``0`` 与 ``False`` 不算空)。
34
+ 调用方显式给了非空值一律保留,**不存在覆盖语义**。
35
+
36
+ 填充矩阵:
37
+
38
+ ======== ============ ====================== ==========
39
+ 动作 created_* updated_* deleted
40
+ ======== ============ ====================== ==========
41
+ INSERT 空才填 空才填(与 created_* 同值) 空才填 0
42
+ UPDATE 不参与 空才填 不参与
43
+ ======== ============ ====================== ==========
44
+
45
+ "当前值" 指**本次写入的数据**,不是数据库已存值:
46
+
47
+ - dict 路径(``raw_insert`` / ``raw_update`` / ``CRUDBase.update_multi`` / ``upsert``):
48
+ 看 ``data`` 中该键的值;
49
+ - ORM 路径(``before_flush``):看本次 flush 是否显式给该属性赋值(属性变更历史)。
50
+
51
+ 因此业务没传 ``updated_at`` 时,每次更新都会刷新它。
52
+
53
+ 三条落点:
54
+
55
+ 1. ORM flush(``session.add`` / 属性修改 + flush)→ ``before_flush`` 事件;
56
+ 2. Core DML(``CRUDBase.update_multi`` / ``upsert``)→ 方法内填 dict;
57
+ 3. 原生构建器(``raw_insert`` / ``raw_update``)→ 构建 SQL 前填 dict。
58
+
59
+ ``execute()`` 手写 SQL 与批量 executemany **不填充**(不做 SQL 文本改写)。
60
+
61
+ 默认不启用:未调用 :meth:`AuditConfig.enable` 时,kit 所有写入口行为与本模块
62
+ 引入前完全一致(含 ``raw_insert`` 的 SQL 文本)。
63
+
64
+ 用法::
65
+
66
+ from yimo.kit.db import AuditConfig
67
+
68
+ AuditConfig.enable(user_resolver=get_current_userid) # 应用启动时调用一次
69
+ """
70
+
71
+ import re
72
+ import threading
73
+ from collections.abc import Callable, Generator, Mapping, MutableMapping
74
+ from contextlib import contextmanager
75
+ from contextvars import ContextVar
76
+ from datetime import UTC, datetime
77
+ from typing import Any, ClassVar
78
+
79
+ from sqlalchemy import String, event, inspect as sa_inspect
80
+ from sqlalchemy.exc import NoSuchTableError
81
+ from sqlalchemy.orm import Session
82
+ from sqlalchemy.types import TypeEngine
83
+
84
+ from yimo.kit.config.log_config import get_default_logger
85
+ from yimo.kit.db.engine import get_engine
86
+
87
+ logger = get_default_logger(__name__)
88
+
89
+ # 字段「槽位 → 默认列名」:槽位是内部语义键(也是默认列名),
90
+ # 实际列名可用 AuditConfig.set_fields() 覆盖(如把 created_at 换成 create_time)
91
+ CREATED_AT, CREATED_BY, UPDATED_AT, UPDATED_BY, DELETED = (
92
+ "created_at",
93
+ "created_by",
94
+ "updated_at",
95
+ "updated_by",
96
+ "deleted",
97
+ )
98
+
99
+ # 审计四件套槽位(created_at / created_by / updated_at / updated_by)
100
+ AUDIT_FIELDS: tuple[str, ...] = (CREATED_AT, CREATED_BY, UPDATED_AT, UPDATED_BY)
101
+
102
+ # 填充器实际关注的槽位(审计四件套 + 删除标记)
103
+ FILL_FIELDS: tuple[str, ...] = (*AUDIT_FIELDS, DELETED)
104
+
105
+ # 槽位 → 默认列名(默认同名;set_fields 只覆盖发生变化的槽位)
106
+ DEFAULT_FIELDS: dict[str, str] = {slot: slot for slot in FILL_FIELDS}
107
+
108
+ # 槽位 → 内置别名列名:表里有哪个就填哪个,无需 set_fields 配置。
109
+ # 例如业务表用 create_time / update_time,与 created_at / updated_at 等价。
110
+ FIELD_ALIASES: dict[str, tuple[str, ...]] = {
111
+ CREATED_AT: ("create_time",),
112
+ UPDATED_AT: ("update_time",),
113
+ }
114
+
115
+ # 列探测缓存:(db_type, 表名) -> {列名: SQLAlchemy 类型对象}
116
+ # 仅缓存**探测成功**的结果;失败不缓存,表稍后创建可自愈
117
+ _columns_cache: dict[tuple[str, str], dict[str, TypeEngine[Any]]] = {}
118
+ _columns_lock = threading.Lock()
119
+
120
+ # 「查已删除」上下文开关:进入 AuditConfig.include_deleted() 后临时关闭过滤
121
+ _include_deleted: ContextVar[bool] = ContextVar("audit_include_deleted", default=False)
122
+
123
+
124
+ def _default_clock() -> datetime:
125
+ """默认时钟:UTC aware(与 models/base.py::_utcnow 同口径)"""
126
+ return datetime.now(UTC)
127
+
128
+
129
+ def _is_empty(value: object) -> bool:
130
+ """是否为「空」:None / 空串 / 纯空白串(0 与 False 不算空)"""
131
+ if value is None:
132
+ return True
133
+ return isinstance(value, str) and not value.strip()
134
+
135
+
136
+ # 列名会被拼进 SQL 的标识符位置(`SET name = :name` / `INSERT ... (name)`),
137
+ # 故配置入口必须与 raw_* 的 data 键同一套白名单,避免手误到写入时才报晦涩错误。
138
+ _IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
139
+
140
+
141
+ def _check_field_name(name: object) -> None:
142
+ """校验配置的列名是合法标识符(拼接进 SQL 前拦截)
143
+
144
+ Raises:
145
+ ValueError: 非字符串 / 空串 / 含字母、数字、下划线以外的字符 / 以数字开头
146
+ """
147
+ if not isinstance(name, str) or not _IDENT_RE.match(name):
148
+ raise ValueError(
149
+ f"{name!r} 不是合法列名(仅允许字母、数字、下划线,且不能以数字开头)"
150
+ )
151
+
152
+
153
+ def _is_string_type(column_type: TypeEngine[Any]) -> bool:
154
+ """是否为字符串列(兼容 SQLModel 的 ``AutoString`` 这类 ``TypeDecorator``)
155
+
156
+ 三级判定(任一命中即视为字符串):
157
+ 1. ``isinstance(type, String)`` —— 原生 ``VARCHAR`` / ``CHAR`` / ``TEXT``;
158
+ 2. ``python_type is str`` —— 多数类型装饰器;
159
+ 3. ``impl`` 是 ``String`` 或其子类 —— SQLModel 的 ``AutoString``
160
+ (``TypeDecorator``,前两级都判定不到)。
161
+ """
162
+ if isinstance(column_type, String):
163
+ return True
164
+ try:
165
+ if column_type.python_type is str:
166
+ return True
167
+ except (AttributeError, NotImplementedError):
168
+ pass
169
+ impl = getattr(column_type, "impl", None)
170
+ if isinstance(impl, String):
171
+ return True
172
+ return isinstance(impl, type) and issubclass(impl, String)
173
+
174
+
175
+ def normal_value(column_type: TypeEngine[Any]) -> object:
176
+ """删除标记的「正常」值:字符串列(VARCHAR/CHAR/TEXT)为 ``"0"``,整数列为 ``0``
177
+
178
+ 写入填充与查询过滤共用同一个值,避免两侧口径不一致。
179
+ 字符串列写整数在 PostgreSQL(``character varying``)与 MySQL 严格模式下
180
+ 会直接报类型错误,故按列类型区分。
181
+
182
+ ⚠ 内部符号(不进 ``yimo.kit.db.__all__``)。
183
+ """
184
+ return "0" if _is_string_type(column_type) else 0
185
+
186
+
187
+ class AuditConfig:
188
+ """审计字段自动填充的进程级配置(默认关闭)
189
+
190
+ 进程级类属性 + 线程锁;``enable`` / ``disable`` 属启动期一次性调用,
191
+ 不做运行期热切换承诺。模块导入零副作用。
192
+ """
193
+
194
+ _lock: ClassVar[Any] = threading.RLock()
195
+ _enabled: ClassVar[bool] = False
196
+ _user_resolver: ClassVar[Callable[[], object] | None] = None
197
+ _clock: ClassVar[Callable[[], datetime]] = _default_clock
198
+ _fields: ClassVar[dict[str, str]] = dict(DEFAULT_FIELDS)
199
+ _soft_delete_filter: ClassVar[bool] = False
200
+ _listening: ClassVar[bool] = False
201
+
202
+ @classmethod
203
+ def enable(
204
+ cls,
205
+ *,
206
+ user_resolver: Callable[[], object] | None = None,
207
+ clock: Callable[[], datetime] | None = None,
208
+ fields: Mapping[str, str] | None = None,
209
+ soft_delete_filter: bool | None = None,
210
+ ) -> None:
211
+ """启用自动填充(幂等)
212
+
213
+ Args:
214
+ user_resolver: 返回当前操作人的钩子(str 或 int,与列类型一致)。
215
+ 返回 None / 空串时跳过 ``*_by`` 填充;抛异常时记 warning 并跳过,
216
+ 不影响写入。
217
+ clock: 取时间钩子,默认 ``datetime.now(UTC)``(测试可注入冻结时钟)。
218
+ fields: 自定义字段名(槽位 → 实际列名),只给需要改的项,如
219
+ ``{"created_at": "create_time", "deleted": "del_flag"}``;
220
+ 透传给 :meth:`set_fields`。
221
+ soft_delete_filter: 是否让查询方法自动追加「deleted = 正常值」条件
222
+ (None = 保持当前设置;默认关闭)。
223
+
224
+ Note:
225
+ 事件监听挂在父类 :class:`sqlalchemy.orm.Session` 上,因此
226
+ ``session_scope`` 新建的 Session 与应用自建的原生 Session 都会触发。
227
+ """
228
+ with cls._lock:
229
+ if fields is not None:
230
+ cls.set_fields(fields)
231
+ if soft_delete_filter is not None:
232
+ cls._soft_delete_filter = soft_delete_filter
233
+ # ClassVar 上的 Callable 赋值:pyright 会误判为方法绑定,运行时正确
234
+ if user_resolver is not None:
235
+ cls._user_resolver = user_resolver # pyright: ignore[reportAttributeAccessIssue]
236
+ if clock is not None:
237
+ cls._clock = clock # pyright: ignore[reportAttributeAccessIssue]
238
+ if not cls._listening:
239
+ event.listen(Session, "before_flush", _on_before_flush)
240
+ cls._listening = True
241
+ cls._enabled = True
242
+ logger.info("✅ 审计字段与删除标记自动填充已启用")
243
+
244
+ @classmethod
245
+ def fields(cls) -> dict[str, str]:
246
+ """当前「槽位 → 实际列名」映射(副本,可安全修改)"""
247
+ return dict(cls._fields)
248
+
249
+ @classmethod
250
+ def set_fields(cls, fields: Mapping[str, str] | None = None) -> None:
251
+ """配置字段名(不传 / 传 None 恢复默认)
252
+
253
+ Args:
254
+ fields: 槽位 → 实际列名,只给需要改的槽位。可用槽位:
255
+ ``created_at`` / ``created_by`` / ``updated_at`` / ``updated_by`` /
256
+ ``deleted``
257
+
258
+ Raises:
259
+ ValueError: 出现未知槽位(防手误,例如把 ``created_at`` 写成 ``create_at``);
260
+ 或列名不是合法标识符(会被拼进 SQL 的标识符位置)
261
+
262
+ 用法::
263
+
264
+ AuditConfig.set_fields(
265
+ {"created_at": "create_time", "deleted": "del_flag"}
266
+ )
267
+ """
268
+ merged = dict(DEFAULT_FIELDS)
269
+ if fields:
270
+ unknown = set(fields) - set(DEFAULT_FIELDS)
271
+ if unknown:
272
+ raise ValueError(
273
+ f"未知的字段槽位: {sorted(unknown)};"
274
+ f"可用槽位: {sorted(DEFAULT_FIELDS)}"
275
+ )
276
+ for name in fields.values():
277
+ _check_field_name(name)
278
+ merged.update(fields)
279
+ with cls._lock:
280
+ cls._fields = merged
281
+
282
+ @classmethod
283
+ def set_soft_delete_filter(cls, enabled: bool) -> None:
284
+ """开关「查询自动过滤软删除记录」(默认关闭)
285
+
286
+ Args:
287
+ enabled: True 时,kit 的查询方法对**有 deleted 列的表/模型**追加
288
+ ``deleted = 正常值`` 条件(整数字段为 ``0``,字符串字段为 ``"0"``)。
289
+
290
+ Note:
291
+ - 只影响**查询**:`CRUDBase` 的 get / get_or_raise / get_multi /
292
+ get_by_field / get_multi_by_field / count / exists,以及 `raw_get_by`;
293
+ - 写方法(create / update / update_multi / delete / upsert / raw_*)
294
+ 不追加该条件;
295
+ - `query()` 手写 SQL **不处理**(与 `execute()` 同一条原则);
296
+ - 需要读取已删除记录时用 :meth:`include_deleted` 上下文。
297
+ """
298
+ with cls._lock:
299
+ cls._soft_delete_filter = enabled
300
+ logger.info(f"🔎 软删除查询过滤已{'开启' if enabled else '关闭'}")
301
+
302
+ @classmethod
303
+ def filter_deleted(cls) -> bool:
304
+ """当前查询是否应追加「deleted = 正常值」条件
305
+
306
+ 综合两件事:过滤开关已开启,且当前不在 :meth:`include_deleted` 上下文中。
307
+ """
308
+ return cls._soft_delete_filter and not _include_deleted.get()
309
+
310
+ @classmethod
311
+ @contextmanager
312
+ def include_deleted(cls) -> Generator[None, None, None]:
313
+ """临时查询已删除记录的上下文(仅本上下文内关闭过滤)
314
+
315
+ 用法::
316
+
317
+ with AuditConfig.include_deleted():
318
+ rows = PgKit.query(...) # 手写 SQL 本就不受过滤影响
319
+ obj = PgKit.get(Model, 1) # 能查到 deleted=1 的记录
320
+ """
321
+ token = _include_deleted.set(True)
322
+ try:
323
+ yield
324
+ finally:
325
+ _include_deleted.reset(token)
326
+
327
+ @classmethod
328
+ def disable(cls) -> None:
329
+ """关闭自动填充(保留 user_resolver / clock 配置,再次 enable 可沿用)"""
330
+ with cls._lock:
331
+ cls._enabled = False
332
+ if cls._listening:
333
+ event.remove(Session, "before_flush", _on_before_flush)
334
+ cls._listening = False
335
+ logger.info("🔌 审计字段与删除标记自动填充已关闭")
336
+
337
+ @classmethod
338
+ def is_enabled(cls) -> bool:
339
+ """当前是否启用"""
340
+ return cls._enabled
341
+
342
+ @classmethod
343
+ def now(cls) -> datetime:
344
+ """当前时间(UTC aware;clock 异常时记 warning 并回退 UTC now)"""
345
+ try:
346
+ return cls._clock() # pyright: ignore[reportAttributeAccessIssue]
347
+ except Exception as e:
348
+ logger.warning(f"⚠️ 审计时钟调用失败,回退 UTC now: {e}")
349
+ return datetime.now(UTC)
350
+
351
+ @classmethod
352
+ def current_user(cls) -> object | None:
353
+ """当前操作人(resolver 未注册或异常时返回 None)"""
354
+ resolver = cls._user_resolver # pyright: ignore[reportAttributeAccessIssue]
355
+ if resolver is None:
356
+ return None
357
+ try:
358
+ return resolver()
359
+ except Exception as e:
360
+ logger.warning(f"⚠️ user_resolver 调用失败,跳过 *_by 填充: {e}")
361
+ return None
362
+
363
+ @classmethod
364
+ def clear_columns_cache(cls, *tables: str) -> None:
365
+ """清空列探测缓存(表结构变更后调用;不传参清空全部)
366
+
367
+ Args:
368
+ tables: 表名(可多个);不传则清空全部缓存
369
+ """
370
+ with _columns_lock:
371
+ if not tables:
372
+ _columns_cache.clear()
373
+ return
374
+ targets = set(tables)
375
+ for key in [k for k in _columns_cache if k[1] in targets]:
376
+ del _columns_cache[key]
377
+
378
+
379
+ def _candidates(slot: str) -> tuple[str, ...]:
380
+ """槽位的候选列名:当前配置名在前,内置别名在后(去重)
381
+
382
+ 表里有哪个就填哪个;同时存在时两列都填(同值)。
383
+ """
384
+ primary = AuditConfig._fields[slot]
385
+ aliases = FIELD_ALIASES.get(slot, ())
386
+ return (primary, *(alias for alias in aliases if alias != primary))
387
+
388
+
389
+ def candidate_columns(slot: str) -> tuple[str, ...]:
390
+ """槽位的候选列名(当前配置名 + 内置别名),供错误消息与诊断使用
391
+
392
+ ⚠ 内部符号(不进 ``yimo.kit.db.__all__``)。
393
+ """
394
+ return _candidates(slot)
395
+
396
+
397
+ def insert_only_columns() -> tuple[str, ...]:
398
+ """只在 INSERT 填充的列(created_at / created_by 槽位的**全部候选**)
399
+
400
+ ⚠ 内部符号:供 ``CRUDBase.upsert`` 从 ``set_`` 中排除,避免冲突更新
401
+ 把创建时间 / 创建人刷掉。
402
+ """
403
+ return (*_candidates(CREATED_AT), *_candidates(CREATED_BY))
404
+
405
+
406
+ # ==================== 列探测(原生路径) ====================
407
+
408
+
409
+ def table_columns(db_type: str, table_name: str) -> dict[str, TypeEngine[Any]]:
410
+ """表「列名 → SQLAlchemy 类型对象」映射(仅缓存探测成功的结果)
411
+
412
+ Args:
413
+ db_type: 数据库类型(postgresql / mysql / sqlite)
414
+ table_name: 表名(非限定名,按当前 search_path / database 解析)
415
+
416
+ Returns:
417
+ 列名到类型对象的映射;表不存在或探测失败时返回**空字典**(= 不填充),
418
+ 且不写入缓存(下次调用重新探测,表稍后创建可自愈)
419
+
420
+ Note:
421
+ 保留类型对象而非类型名:``deleted`` 的取值需要 ``isinstance`` 判定
422
+ (``String`` 家族 → ``"0"``,其余 → ``0``)。
423
+ """
424
+ key = (db_type, table_name)
425
+ with _columns_lock:
426
+ cached = _columns_cache.get(key)
427
+ if cached is not None:
428
+ return cached
429
+
430
+ try:
431
+ inspector = sa_inspect(get_engine(db_type))
432
+ columns = {col["name"]: col["type"] for col in inspector.get_columns(table_name)}
433
+ except NoSuchTableError:
434
+ logger.debug(f"表 {table_name} 不存在,跳过审计字段填充")
435
+ return {}
436
+ except Exception as e:
437
+ logger.warning(f"⚠️ 列探测失败({db_type}:{table_name}),跳过填充: {e}")
438
+ return {}
439
+
440
+ with _columns_lock:
441
+ _columns_cache[key] = columns
442
+ return columns
443
+
444
+
445
+ def deleted_predicate(
446
+ db_type: str, table_name: str
447
+ ) -> tuple[str, dict[str, object]] | None:
448
+ """软删除过滤条件(SQL 片段 + 绑定参数);不适用时返回 None
449
+
450
+ 适用条件:过滤开关已开启、当前不在 :meth:`AuditConfig.include_deleted` 上下文、
451
+ 表中存在 deleted 列。
452
+
453
+ Returns:
454
+ ``("deleted = :_audit_deleted", {"_audit_deleted": 0})``;字符串列的值是
455
+ ``"0"``。条件不适用时返回 None(调用方据此不加条件)。
456
+
457
+ Note:
458
+ 严格等值,不对 ``NULL`` 做特殊处理——本工具类只提供底层约定,
459
+ 不为业务历史数据兜底。
460
+
461
+ ⚠ 内部符号:只供 kit 自建 SQL 的**查询**方法(如 ``raw_get_by``)使用,
462
+ 写方法不得调用。
463
+ """
464
+ if not AuditConfig.filter_deleted():
465
+ return None
466
+ name = AuditConfig.fields()[DELETED]
467
+ columns = table_columns(db_type, table_name)
468
+ if name not in columns:
469
+ return None
470
+ return f"{name} = :_audit_deleted", {"_audit_deleted": normal_value(columns[name])}
471
+
472
+
473
+ def touch_columns(db_type: str, table_name: str) -> tuple[str, ...]:
474
+ """``raw_touch`` 要写的列:``updated_at`` 槽位候选 ∩ 表实际列(保持候选顺序)
475
+
476
+ 候选含内置别名 ``update_time``;表里存在哪几列就返回哪几列。
477
+
478
+ ⚠ 内部符号:供 ``BaseDbKit.build_raw_touch`` 使用。
479
+ """
480
+ columns = table_columns(db_type, table_name)
481
+ return tuple(name for name in _candidates(UPDATED_AT) if name in columns)
482
+
483
+
484
+ # ==================== dict 路径填充(Core DML / 原生构建器) ====================
485
+
486
+
487
+ def _put(
488
+ data: MutableMapping[str, object],
489
+ columns: Mapping[str, TypeEngine[Any]],
490
+ name: str,
491
+ value: object,
492
+ ) -> None:
493
+ """按唯一规则写一个字段:有列 + 填充值非空 + 当前值为空"""
494
+ if name not in columns or _is_empty(value):
495
+ return
496
+ if not _is_empty(data.get(name)):
497
+ return
498
+ data[name] = value
499
+
500
+
501
+ def fill_insert(
502
+ data: MutableMapping[str, object], columns: Mapping[str, TypeEngine[Any]]
503
+ ) -> None:
504
+ """INSERT 半区:created_* 与 updated_* 同值填补,deleted 补正常值
505
+
506
+ Args:
507
+ data: 待写入的列名 → 值(**原地修改**,调用方应传入副本)
508
+ columns: 表列名 → 类型对象(为空表示表无审计列,不填)
509
+ """
510
+ if not AuditConfig.is_enabled():
511
+ return
512
+ now = AuditConfig.now()
513
+ user = AuditConfig.current_user()
514
+ for slot, value in (
515
+ (CREATED_AT, now),
516
+ (UPDATED_AT, now),
517
+ (CREATED_BY, user),
518
+ (UPDATED_BY, user),
519
+ ):
520
+ for name in _candidates(slot):
521
+ _put(data, columns, name, value)
522
+ deleted_col = AuditConfig._fields[DELETED]
523
+ if deleted_col in columns:
524
+ _put(data, columns, deleted_col, normal_value(columns[deleted_col]))
525
+
526
+
527
+ def fill_update(
528
+ data: MutableMapping[str, object], columns: Mapping[str, TypeEngine[Any]]
529
+ ) -> None:
530
+ """UPDATE 半区:只动 updated_*(不碰 created_*,也不碰 deleted)
531
+
532
+ Args:
533
+ data: 待更新的列名 → 值(**原地修改**,调用方应传入副本)
534
+ columns: 表列名 → 类型对象
535
+ """
536
+ if not AuditConfig.is_enabled():
537
+ return
538
+ now = AuditConfig.now()
539
+ user = AuditConfig.current_user()
540
+ for slot, value in ((UPDATED_AT, now), (UPDATED_BY, user)):
541
+ for name in _candidates(slot):
542
+ _put(data, columns, name, value)
543
+
544
+
545
+ def fill_insert_for(
546
+ db_type: str, table_name: str, data: MutableMapping[str, object]
547
+ ) -> None:
548
+ """原生路径的 INSERT 入口:**先判启用再探测**(未启用时零额外查询)"""
549
+ if not AuditConfig.is_enabled():
550
+ return
551
+ fill_insert(data, table_columns(db_type, table_name))
552
+
553
+
554
+ def fill_update_for(
555
+ db_type: str, table_name: str, data: MutableMapping[str, object]
556
+ ) -> None:
557
+ """原生路径的 UPDATE 入口:**先判启用再探测**(未启用时零额外查询)"""
558
+ if not AuditConfig.is_enabled():
559
+ return
560
+ fill_update(data, table_columns(db_type, table_name))
561
+
562
+
563
+ # ==================== ORM 路径填充(before_flush) ====================
564
+
565
+
566
+ def _object_columns(obj: object) -> dict[str, TypeEngine[Any]]:
567
+ """对象映射到的「表列名 → 类型对象」(无 ``__table__`` 时返回空字典)"""
568
+ table = getattr(obj, "__table__", None)
569
+ if table is None:
570
+ return {}
571
+ return {column.name: column.type for column in table.columns}
572
+
573
+
574
+ def _fill_obj(
575
+ obj: object, *, now: datetime, user: object | None, insert: bool
576
+ ) -> None:
577
+ """按矩阵填充单个 ORM 对象(列不存在 / 已有非空值 → 跳过)"""
578
+ columns = _object_columns(obj)
579
+ slots: tuple[tuple[str, object], ...] = (
580
+ ((CREATED_AT, now), (UPDATED_AT, now), (CREATED_BY, user), (UPDATED_BY, user))
581
+ if insert
582
+ else ((UPDATED_AT, now), (UPDATED_BY, user))
583
+ )
584
+ pairs: list[tuple[str, object]] = [
585
+ (name, value) for slot, value in slots for name in _candidates(slot)
586
+ ]
587
+ deleted_col = AuditConfig._fields[DELETED]
588
+ if insert and deleted_col in columns:
589
+ pairs.append((deleted_col, normal_value(columns[deleted_col])))
590
+
591
+ state = sa_inspect(obj)
592
+ if state is None: # 理论上实例一定有状态,防御性判断
593
+ return
594
+ for name, value in pairs:
595
+ if name not in columns or _is_empty(value) or not hasattr(obj, name):
596
+ continue
597
+ if name not in state.attrs:
598
+ continue
599
+ current = getattr(obj, name, None)
600
+ if insert:
601
+ # INSERT:属性当前值非空 → 调用方已指定
602
+ if not _is_empty(current):
603
+ continue
604
+ elif state.attrs[name].history.has_changes() and not _is_empty(current):
605
+ # UPDATE:本次显式赋了非空值 → 保留;未赋值 / 赋空 → 填充
606
+ continue
607
+ setattr(obj, name, value)
608
+
609
+
610
+ def _on_before_flush(
611
+ session: Session, flush_context: object, instances: object
612
+ ) -> None:
613
+ """``before_flush`` 钩子:INSERT 走 new 集合,UPDATE 走 dirty 集合
614
+
615
+ 时间与用户在一次 flush 内只取一次,同批对象取值一致。
616
+ """
617
+ if not AuditConfig.is_enabled():
618
+ return
619
+ now = AuditConfig.now()
620
+ user = AuditConfig.current_user()
621
+ for obj in session.new:
622
+ _fill_obj(obj, now=now, user=user, insert=True)
623
+ for obj in session.dirty:
624
+ if session.is_modified(obj, include_collections=False):
625
+ _fill_obj(obj, now=now, user=user, insert=False)