Merge pull request #7050 from DDSRem-Dev/codex-comment-migration

docs: 统一全项目中文注释和结构化契约说明
This commit is contained in:
DDSRem
2026-10-17 19:26:29 +08:00
committed by GitHub
parent 3c7431b7da
commit 2de976f6b3
2345 changed files with 143990 additions and 61534 deletions

View File

@@ -1,4 +1,6 @@
"""插件自管理数据库框架:建表隔离、SQLite 生命周期与 PostgreSQL 所有权边界。"""
"""
插件自管理数据库框架:建表隔离、SQLite 生命周期与 PostgreSQL 所有权边界。
"""
from __future__ import annotations
@@ -30,7 +32,9 @@ from app.db.plugin.locator import (
@pytest.fixture(autouse=True)
def _isolate_plugin_databases():
"""快照插件数据库句柄,用例结束后释放残留句柄并还原快照。"""
"""
快照插件数据库句柄,用例结束后释放残留句柄并还原快照。
"""
handles = dict(registry_module._handles)
registry_module._handles.clear()
yield
@@ -41,7 +45,9 @@ def _isolate_plugin_databases():
def _raise_dispose() -> None:
"""模拟连接池释放失败。"""
"""
模拟连接池释放失败。
"""
raise RuntimeError("dispose failed")
@@ -152,7 +158,9 @@ def downgrade():
@pytest.fixture
def plugin_data_root(tmp_path, monkeypatch) -> Path:
"""把插件数据库文件隔离到进程私有的临时目录。"""
"""
把插件数据库文件隔离到进程私有的临时目录。
"""
root = tmp_path / "plugins"
monkeypatch.setattr(
datadir_module,
@@ -164,7 +172,9 @@ def plugin_data_root(tmp_path, monkeypatch) -> Path:
@pytest.fixture
def sqlite_backend(monkeypatch):
"""把宿主数据库类型固定为 SQLite。"""
"""
把宿主数据库类型固定为 SQLite。
"""
monkeypatch.setattr(
registry_module,
"get_runtime_setting",
@@ -174,7 +184,9 @@ def sqlite_backend(monkeypatch):
@pytest.fixture
def postgresql_backend(monkeypatch):
"""把宿主数据库类型固定为 PostgreSQL,并用替身覆盖宿主引擎。"""
"""
把宿主数据库类型固定为 PostgreSQL,并用替身覆盖宿主引擎。
"""
host_engine = MagicMock(name="host_engine")
# 派生引擎必须是真实引擎:注册 begin 监听器要求一个真实的 SQLAlchemy 事件目标,
# 替身对象会被 event.listen 拒绝
@@ -192,16 +204,24 @@ def postgresql_backend(monkeypatch):
def test_plugin_declarative_base_returns_a_fresh_metadata_per_call():
"""两次调用互不共享 MetaData,两个基类上都能定义同名表而不抛错。"""
"""
两次调用互不共享 MetaData,两个基类上都能定义同名表而不抛错。
"""
base_a = plugin_declarative_base()
base_b = plugin_declarative_base()
assert base_a.metadata is not base_b.metadata
class ItemA(base_a):
"""
第一个插件声明的测试表,用于验证同名模型隔离。
"""
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
class ItemB(base_b):
"""
第二个插件声明的同名测试表,与第一个插件独立存储。
"""
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
@@ -210,10 +230,15 @@ def test_plugin_declarative_base_returns_a_fresh_metadata_per_call():
def test_declared_models_create_tables_in_the_plugin_own_database(plugin_data_root, sqlite_backend):
"""按声明的模型建表,数据可插入读回,且不污染宿主 Base.metadata。"""
"""
按声明的模型建表,数据可插入读回,且不污染宿主 Base.metadata。
"""
base = plugin_declarative_base()
class Widget(base):
"""
用于验证插件模型建表及读写能力的测试实体。
"""
__tablename__ = "widgets"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column()
@@ -232,16 +257,24 @@ def test_declared_models_create_tables_in_the_plugin_own_database(plugin_data_ro
def test_two_plugins_may_declare_the_same_table_name(plugin_data_root, sqlite_backend):
"""两个插件各自的同名表互不冲突,各自库文件不同,数据互不可见。"""
"""
两个插件各自的同名表互不冲突,各自库文件不同,数据互不可见。
"""
base_a = plugin_declarative_base()
base_b = plugin_declarative_base()
class ItemA(base_a):
"""
第一个插件声明的测试表,用于验证同名模型隔离。
"""
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
label: Mapped[str] = mapped_column()
class ItemB(base_b):
"""
第二个插件声明的同名测试表,与第一个插件独立存储。
"""
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
note: Mapped[str] = mapped_column()
@@ -267,14 +300,22 @@ def test_two_plugins_may_declare_the_same_table_name(plugin_data_root, sqlite_ba
def test_only_declared_tables_are_created(plugin_data_root, sqlite_backend):
"""只建声明的表,未声明的同基类模型不会被创建。"""
"""
只建声明的表,未声明的同基类模型不会被创建。
"""
base = plugin_declarative_base()
class Declared(base):
"""
显式交给注册入口的模型,应当创建对应表。
"""
__tablename__ = "declared"
id: Mapped[int] = mapped_column(primary_key=True)
class Undeclared(base):
"""
未交给注册入口的同基类模型,不应自动建表。
"""
__tablename__ = "undeclared"
id: Mapped[int] = mapped_column(primary_key=True)
@@ -285,7 +326,9 @@ def test_only_declared_tables_are_created(plugin_data_root, sqlite_backend):
def test_sqlite_database_lands_in_the_plugin_data_directory(plugin_data_root, sqlite_backend):
"""SQLite 库文件落在插件数据目录下,句柄独占引擎,不带 schema。"""
"""
SQLite 库文件落在插件数据目录下,句柄独占引擎,不带 schema。
"""
handle = registry_module.get_database("demo")
assert registry_module.database_handles() == (handle,)
assert handle.db_path == plugin_data_root / "demo" / "plugin.db"
@@ -295,14 +338,18 @@ def test_sqlite_database_lands_in_the_plugin_data_directory(plugin_data_root, sq
def test_undeclared_plugin_creates_no_database_file(plugin_data_root, sqlite_backend):
"""两项声明都为空时不建句柄、不落盘。"""
"""
两项声明都为空时不建句柄、不落盘。
"""
registry_module.ensure_database("demo")
assert "demo" not in registry_module._handles
assert not (plugin_data_root / "demo").exists()
def test_release_disposes_the_owned_sqlite_engine(plugin_data_root, sqlite_backend, monkeypatch):
"""release 只 dispose 句柄独占的引擎,并把句柄移出注册表。"""
"""
release 只 dispose 句柄独占的引擎,并把句柄移出注册表。
"""
handle = registry_module.get_database("demo")
calls: list[str] = []
monkeypatch.setattr(handle.engine, "dispose", lambda: calls.append("disposed"))
@@ -312,7 +359,9 @@ def test_release_disposes_the_owned_sqlite_engine(plugin_data_root, sqlite_backe
def test_release_all_disposes_every_plugin_database(plugin_data_root, sqlite_backend, monkeypatch):
"""release_all 释放全部插件的数据库连接,注册表清空。"""
"""
release_all 释放全部插件的数据库连接,注册表清空。
"""
handle_a = registry_module.get_database("plugin_a")
handle_b = registry_module.get_database("plugin_b")
calls: list[str] = []
@@ -324,7 +373,9 @@ def test_release_all_disposes_every_plugin_database(plugin_data_root, sqlite_bac
def test_destroy_removes_the_database_file_and_sidecars(plugin_data_root, sqlite_backend):
"""destroy 删除库文件及其 -wal/-shm 边车文件,并移出注册表。"""
"""
destroy 删除库文件及其 -wal/-shm 边车文件,并移出注册表。
"""
handle = registry_module.get_database("demo")
for sidecar in sqlite_sidecar_paths(handle.db_path):
sidecar.write_text("")
@@ -336,7 +387,9 @@ def test_destroy_removes_the_database_file_and_sidecars(plugin_data_root, sqlite
def test_destroy_after_release_still_removes_the_database_file(plugin_data_root, sqlite_backend):
"""先 release 再 destroy 时库文件仍会被删除,覆盖 reset 流程的真实调用顺序。"""
"""
先 release 再 destroy 时库文件仍会被删除,覆盖 reset 流程的真实调用顺序。
"""
handle = registry_module.get_database("demo")
db_path = handle.db_path
registry_module.release_database("demo")
@@ -346,11 +399,15 @@ def test_destroy_after_release_still_removes_the_database_file(plugin_data_root,
def test_destroy_never_raises_when_the_file_cannot_be_removed(plugin_data_root, sqlite_backend, monkeypatch):
"""删除失败只记日志,不得向上抛出异常。"""
"""
删除失败只记日志,不得向上抛出异常。
"""
registry_module.get_database("demo")
def _raise_unlink(self, missing_ok=False):
"""模拟文件系统拒绝删除。"""
"""
模拟文件系统拒绝删除。
"""
raise OSError("permission denied")
monkeypatch.setattr(Path, "unlink", _raise_unlink)
@@ -358,7 +415,9 @@ def test_destroy_never_raises_when_the_file_cannot_be_removed(plugin_data_root,
def test_postgresql_handle_does_not_own_the_host_engine(postgresql_backend):
"""PostgreSQL 下句柄只是宿主引擎按 schema 派生的外观,不拥有它。"""
"""
PostgreSQL 下句柄只是宿主引擎按 schema 派生的外观,不拥有它。
"""
host_engine, derived_engine = postgresql_backend
handle = registry_module.get_database("demo")
assert handle.owns_engine is False
@@ -370,7 +429,9 @@ def test_postgresql_handle_does_not_own_the_host_engine(postgresql_backend):
def test_postgresql_release_never_disposes_the_host_engine(postgresql_backend, monkeypatch):
"""release 在 PostgreSQL 下不得 dispose 派生引擎,也不得触碰宿主引擎。"""
"""
release 在 PostgreSQL 下不得 dispose 派生引擎,也不得触碰宿主引擎。
"""
host_engine, derived_engine = postgresql_backend
disposed: list[str] = []
monkeypatch.setattr(derived_engine, "dispose", lambda: disposed.append("derived"))
@@ -384,7 +445,9 @@ def test_postgresql_destroy_drops_the_schema_and_keeps_the_host_engine(
postgresql_backend,
monkeypatch,
):
"""destroy 在 PostgreSQL 下丢弃对应 schema,且不 dispose 任何引擎。"""
"""
destroy 在 PostgreSQL 下丢弃对应 schema,且不 dispose 任何引擎。
"""
host_engine, derived_engine = postgresql_backend
disposed: list[str] = []
monkeypatch.setattr(derived_engine, "dispose", lambda: disposed.append("derived"))
@@ -404,7 +467,9 @@ def test_declared_migrations_take_precedence_over_models(
monkeypatch,
tmp_path,
):
"""同时声明模型与迁移目录时优先走 alembic,且模型表不会被建出。"""
"""
同时声明模型与迁移目录时优先走 alembic,且模型表不会被建出。
"""
calls: list[tuple[str, Path]] = []
monkeypatch.setattr(
migration_module,
@@ -414,6 +479,9 @@ def test_declared_migrations_take_precedence_over_models(
base = plugin_declarative_base()
class Widget(base):
"""
声明但不应通过模型自动建表的实体,用于验证迁移优先级。
"""
__tablename__ = "widgets"
id: Mapped[int] = mapped_column(primary_key=True)
@@ -425,19 +493,25 @@ def test_declared_migrations_take_precedence_over_models(
def test_plugin_schema_name_sanitizes_the_plugin_id():
"""schema 名只保留小写字母、数字与下划线,被改写过的标识再带上区分哈希。"""
"""
schema 名只保留小写字母、数字与下划线,被改写过的标识再带上区分哈希。
"""
schema = plugin_schema_name("Demo-Plugin.v2")
assert schema.startswith("plugin_demo_plugin_v2_")
assert schema.removeprefix("plugin_demo_plugin_v2_").isalnum()
def test_plugin_schema_name_keeps_an_already_legal_plugin_id_verbatim():
"""标识本身已是合法 schema 片段时不追加哈希。"""
"""
标识本身已是合法 schema 片段时不追加哈希。
"""
assert plugin_schema_name("my_plugin") == "plugin_my_plugin"
def test_plugin_schema_name_separates_ids_that_normalize_to_the_same_text():
"""归一后同名的三个插件标识各自拿到不同 schema,卸载互不波及。"""
"""
归一后同名的三个插件标识各自拿到不同 schema,卸载互不波及。
"""
schemas = {
plugin_schema_name(plugin_id)
for plugin_id in ("My-Plugin", "My_Plugin", "my_plugin")
@@ -446,14 +520,18 @@ def test_plugin_schema_name_separates_ids_that_normalize_to_the_same_text():
def test_plugin_schema_name_fits_the_postgresql_identifier_limit():
"""超长插件标识被截断到 PostgreSQL 标识符上限以内,且仍带区分哈希。"""
"""
超长插件标识被截断到 PostgreSQL 标识符上限以内,且仍带区分哈希。
"""
schema = plugin_schema_name("p" * 200)
assert len(schema.encode("utf-8")) <= SCHEMA_NAME_MAX_LENGTH
assert plugin_schema_name("p" * 200) != plugin_schema_name("p" * 201)
def test_sqlite_sidecar_paths_cover_wal_and_shm():
"""边车路径覆盖 -wal 与 -shm 两个后缀。"""
"""
边车路径覆盖 -wal 与 -shm 两个后缀。
"""
db_path = Path("/tmp/plugin.db")
assert sqlite_sidecar_paths(db_path) == (
Path("/tmp/plugin.db-wal"),
@@ -462,7 +540,9 @@ def test_sqlite_sidecar_paths_cover_wal_and_shm():
def test_release_all_isolates_a_failing_plugin_dispose(plugin_data_root, sqlite_backend, monkeypatch):
"""一个插件的连接池释放抛错,其余插件仍被释放,异常不向上传播。"""
"""
一个插件的连接池释放抛错,其余插件仍被释放,异常不向上传播。
"""
handle_a = registry_module.get_database("plugin_a")
handle_b = registry_module.get_database("plugin_b")
calls: list[str] = []
@@ -480,7 +560,9 @@ def test_close_database_disposes_the_host_engine_when_a_plugin_dispose_fails(
sqlite_backend,
monkeypatch,
):
"""插件连接池释放抛错时,宿主同步引擎仍然被释放。"""
"""
插件连接池释放抛错时,宿主同步引擎仍然被释放。
"""
handle = registry_module.get_database("demo")
monkeypatch.setattr(handle.engine, "dispose", _raise_dispose)
disposed: list[str] = []
@@ -500,7 +582,9 @@ def test_destroy_removes_the_database_file_even_when_dispose_fails(
sqlite_backend,
monkeypatch,
):
"""连接池释放抛错不得中断销毁,库文件照样被删除。"""
"""
连接池释放抛错不得中断销毁,库文件照样被删除。
"""
handle = registry_module.get_database("demo")
monkeypatch.setattr(handle.engine, "dispose", _raise_dispose)
@@ -511,16 +595,24 @@ def test_destroy_removes_the_database_file_even_when_dispose_fails(
def test_single_table_inheritance_creates_the_shared_table_once(plugin_data_root, sqlite_backend):
"""单表继承的父子类共享同一张表,一并声明只建一次,重复建库幂等。"""
"""
单表继承的父子类共享同一张表,一并声明只建一次,重复建库幂等。
"""
base = plugin_declarative_base()
class Node(base):
"""
单表继承的父实体,通过类型字段区分记录。
"""
__tablename__ = "nodes"
__mapper_args__ = {"polymorphic_on": "kind", "polymorphic_identity": "node"}
id: Mapped[int] = mapped_column(primary_key=True)
kind: Mapped[str] = mapped_column()
class Leaf(Node):
"""
共享父实体数据表的子实体,用于验证重复建表的幂等性。
"""
__mapper_args__ = {"polymorphic_identity": "leaf"}
assert Leaf.__table__ is Node.__table__
@@ -533,7 +625,9 @@ def test_single_table_inheritance_creates_the_shared_table_once(plugin_data_root
def test_release_closes_the_thread_local_session(plugin_data_root, sqlite_backend):
"""release 先清掉线程局部会话,句柄不再扣着已 dispose 引擎上的连接。"""
"""
release 先清掉线程局部会话,句柄不再扣着已 dispose 引擎上的连接。
"""
handle = registry_module.get_database("demo")
session = handle.scoped_session()
session.execute(text("SELECT 1"))
@@ -548,7 +642,9 @@ def test_relative_migrations_directory_is_rejected_before_any_file_is_created(
plugin_data_root,
sqlite_backend,
):
"""迁移目录是相对路径时直接抛错:它按宿主工作目录解析,可能是另一条迁移链。"""
"""
迁移目录是相对路径时直接抛错:它按宿主工作目录解析,可能是另一条迁移链。
"""
with pytest.raises(ValueError):
registry_module.ensure_database("demo", (), Path("migrations"))
@@ -561,7 +657,9 @@ def test_missing_migrations_directory_is_rejected_before_any_file_is_created(
sqlite_backend,
tmp_path,
):
"""迁移目录不存在时直接抛错,不留下空库文件,也不建插件数据目录。"""
"""
迁移目录不存在时直接抛错,不留下空库文件,也不建插件数据目录。
"""
with pytest.raises(FileNotFoundError):
registry_module.ensure_database("demo", (), tmp_path / "missing")
@@ -570,7 +668,9 @@ def test_missing_migrations_directory_is_rejected_before_any_file_is_created(
def test_postgresql_handle_creates_the_plugin_schema(postgresql_backend):
"""PostgreSQL 下建句柄先按插件 schema 执行 CREATE SCHEMA IF NOT EXISTS。"""
"""
PostgreSQL 下建句柄先按插件 schema 执行 CREATE SCHEMA IF NOT EXISTS。
"""
host_engine, _ = postgresql_backend
handle = registry_module.get_database("demo")
connection = host_engine.begin.return_value.__enter__.return_value
@@ -579,7 +679,9 @@ def test_postgresql_handle_creates_the_plugin_schema(postgresql_backend):
def test_postgresql_handle_rejects_schema_without_write_privilege(postgresql_backend):
"""已有 schema 但当前账号不可写时,插件建库必须直接失败。"""
"""
已有 schema 但当前账号不可写时,插件建库必须直接失败。
"""
host_engine, _ = postgresql_backend
connection = host_engine.begin.return_value.__enter__.return_value
denied = MagicMock()
@@ -593,14 +695,18 @@ def test_postgresql_handle_rejects_schema_without_write_privilege(postgresql_bac
def test_concurrent_get_database_builds_a_single_handle(plugin_data_root, sqlite_backend):
"""八个线程同时取同一插件的句柄时只建出一个句柄,不会并存两份连接池。"""
"""
八个线程同时取同一插件的句柄时只建出一个句柄,不会并存两份连接池。
"""
thread_count = 8
barrier = threading.Barrier(thread_count)
guard = threading.Lock()
handles: list[PluginDatabaseHandle] = []
def _acquire() -> None:
"""在同一时刻取句柄并记录结果。"""
"""
在同一时刻取句柄并记录结果。
"""
barrier.wait()
handle = registry_module.get_database("demo")
with guard:
@@ -618,7 +724,9 @@ def test_concurrent_get_database_builds_a_single_handle(plugin_data_root, sqlite
def test_get_database_rebuilds_a_released_handle(plugin_data_root, sqlite_backend):
"""release 之后再取句柄会重建出一个可用的新句柄。"""
"""
release 之后再取句柄会重建出一个可用的新句柄。
"""
first = registry_module.get_database("demo")
registry_module.release_database("demo")
@@ -633,7 +741,9 @@ def test_get_database_rebuilds_a_released_handle(plugin_data_root, sqlite_backen
def test_get_database_rebuilds_a_destroyed_handle(plugin_data_root, sqlite_backend):
"""destroy 之后再取句柄会重建库文件与新句柄。"""
"""
destroy 之后再取句柄会重建库文件与新句柄。
"""
first = registry_module.get_database("demo")
registry_module.destroy_database("demo")
@@ -649,7 +759,9 @@ def test_get_database_rebuilds_a_destroyed_handle(plugin_data_root, sqlite_backe
def test_run_migrations_upgrades_a_sqlite_plugin_database(plugin_data_root, sqlite_backend, tmp_path):
"""声明迁移目录时按 alembic 建表并写入版本号,重复建库幂等。"""
"""
声明迁移目录时按 alembic 建表并写入版本号,重复建库幂等。
"""
directory = _write_migration_directory(tmp_path)
registry_module.ensure_database("demo", (), directory)
@@ -668,7 +780,9 @@ def test_run_migrations_rejects_a_revision_the_script_tree_cannot_locate(
sqlite_backend,
tmp_path,
):
"""装回旧版本时库里残留的新 revision 必须被明确拒绝,且不得自动降级。"""
"""
装回旧版本时库里残留的新 revision 必须被明确拒绝,且不得自动降级。
"""
newer = _write_migration_directory(
tmp_path,
name="migrations-new",
@@ -695,7 +809,9 @@ def test_run_migrations_accepts_a_database_stamped_by_the_same_script_tree(
sqlite_backend,
tmp_path,
):
"""同一棵迁移树内的旧 revision 仍须正常升到 head,兼容检查不得误伤。"""
"""
同一棵迁移树内的旧 revision 仍须正常升到 head,兼容检查不得误伤。
"""
directory = _write_migration_directory(tmp_path, follow_up_revision="0002")
registry_module.ensure_database("demo", (), directory)
@@ -709,16 +825,22 @@ def test_run_migrations_routes_the_postgresql_connection_through_the_handle(
monkeypatch,
tmp_path,
):
"""PostgreSQL 下迁移复用句柄已限定 schema 的连接,并在结束后提交。"""
"""
PostgreSQL 下迁移复用句柄已限定 schema 的连接,并在结束后提交。
"""
captured: dict[str, object] = {}
def _record_upgrade(config, revision):
"""记录 alembic 收到的连接与目标版本。"""
"""
记录 alembic 收到的连接与目标版本。
"""
captured["connection"] = config.attributes.get("connection")
captured["revision"] = revision
def _record_guard(connection, _config, _directory):
"""记录 revision 兼容检查落在哪条连接上。"""
"""
记录 revision 兼容检查落在哪条连接上。
"""
captured["guarded"] = connection
monkeypatch.setattr(migration_module, "upgrade", _record_upgrade)
@@ -740,7 +862,9 @@ def test_release_after_destroy_keeps_a_database_rebuilt_by_a_stop_hook(
plugin_data_root,
sqlite_backend,
):
"""销毁后重新建出的库属于仍在运行的插件,普通停止只释放连接、不得再删一次。"""
"""
销毁后重新建出的库属于仍在运行的插件,普通停止只释放连接、不得再删一次。
"""
registry_module.get_database("demo")
registry_module.destroy_database("demo")
@@ -763,14 +887,18 @@ def test_destroy_blocks_a_concurrent_handle_rebuild_until_the_carrier_is_removed
sqlite_backend,
monkeypatch,
):
"""销毁未删完载体前并发的取句柄取不到结果,新句柄因此不会指向被删掉的载体。"""
"""
销毁未删完载体前并发的取句柄取不到结果,新句柄因此不会指向被删掉的载体。
"""
first = registry_module.get_database("demo")
entered_removal = threading.Event()
resume_removal = threading.Event()
original_remove_storage = registry_module._remove_storage
def _blocking_remove_storage(plugin_id, handle):
"""在删除载体前挂住销毁流程,制造并发窗口。"""
"""
在删除载体前挂住销毁流程,制造并发窗口。
"""
entered_removal.set()
assert resume_removal.wait(10)
original_remove_storage(plugin_id, handle)
@@ -779,7 +907,9 @@ def test_destroy_blocks_a_concurrent_handle_rebuild_until_the_carrier_is_removed
rebuilt: list[PluginDatabaseHandle] = []
def _rebuild() -> None:
"""在销毁进行中重新取句柄。"""
"""
在销毁进行中重新取句柄。
"""
rebuilt.append(registry_module.get_database("demo"))
destroyer = threading.Thread(target=registry_module.destroy_database, args=("demo",))
@@ -802,7 +932,9 @@ def test_destroy_blocks_a_concurrent_handle_rebuild_until_the_carrier_is_removed
def test_search_path_setter_binds_the_quoted_plugin_schema():
"""监听器在事务开始时执行 SET LOCAL search_path,schema 名带引号且不留 public 兜底。"""
"""
监听器在事务开始时执行 SET LOCAL search_path,schema 名带引号且不留 public 兜底。
"""
connection = MagicMock(name="connection")
registry_module._search_path_setter("plugin_demo")(connection)
@@ -813,13 +945,17 @@ def test_search_path_setter_binds_the_quoted_plugin_schema():
def test_begin_listener_on_a_derived_engine_never_reaches_the_host_engine(tmp_path):
"""派生引擎上的 begin 监听器只对派生连接生效,宿主引擎的连接不触发。"""
"""
派生引擎上的 begin 监听器只对派生连接生效,宿主引擎的连接不触发。
"""
host_engine = create_engine(f"sqlite:///{tmp_path / 'host.db'}")
derived_engine = host_engine.execution_options()
fired: list[str] = []
def _listener(connection) -> None:
"""记录触发并在同一连接上执行一条无害语句,验证不会递归或报错。"""
"""
记录触发并在同一连接上执行一条无害语句,验证不会递归或报错。
"""
fired.append("begin")
connection.exec_driver_sql("SELECT 1")
@@ -850,13 +986,17 @@ def test_postgresql_handle_binds_a_search_path_listener_to_the_derived_engine(
postgresql_backend,
monkeypatch,
):
"""PostgreSQL 建句柄时把插件 schema 的监听器挂到派生引擎,而不是宿主引擎。"""
"""
PostgreSQL 建句柄时把插件 schema 的监听器挂到派生引擎,而不是宿主引擎。
"""
_host_engine, derived_engine = postgresql_backend
bound: list[tuple] = []
build_listener = registry_module._search_path_setter
def _record(schema: str):
"""记录被绑定的 schema 与生成的监听器。"""
"""
记录被绑定的 schema 与生成的监听器。
"""
listener = build_listener(schema)
bound.append((schema, listener))
return listener
@@ -870,7 +1010,9 @@ def test_postgresql_handle_binds_a_search_path_listener_to_the_derived_engine(
def test_alembic_migrations_trigger_the_begin_event_on_a_borrowed_engine(tmp_path):
"""借用引擎的迁移在连接上首次执行即触发 begin,search_path 监听器因此覆盖 alembic。"""
"""
借用引擎的迁移在连接上首次执行即触发 begin,search_path 监听器因此覆盖 alembic。
"""
engine = create_engine(f"sqlite:///{tmp_path / 'host.db'}").execution_options()
begins: list[str] = []
event.listen(engine, "begin", lambda _connection: begins.append("begin"))