storepy 5.2.0__tar.gz → 5.3.0__tar.gz

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 (117) hide show
  1. {storepy-5.2.0/src/storepy.egg-info → storepy-5.3.0}/PKG-INFO +4 -3
  2. {storepy-5.2.0 → storepy-5.3.0}/README.md +2 -1
  3. {storepy-5.2.0 → storepy-5.3.0}/pyproject.toml +2 -2
  4. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/datasource.py +36 -1
  5. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/ddl.py +44 -3
  6. {storepy-5.2.0 → storepy-5.3.0/src/storepy.egg-info}/PKG-INFO +4 -3
  7. {storepy-5.2.0 → storepy-5.3.0}/src/storepy.egg-info/requires.txt +1 -1
  8. {storepy-5.2.0 → storepy-5.3.0}/tests/test_migration.py +25 -0
  9. {storepy-5.2.0 → storepy-5.3.0}/tests/test_raw_sql_and_ddl.py +130 -0
  10. {storepy-5.2.0 → storepy-5.3.0}/LICENSE +0 -0
  11. {storepy-5.2.0 → storepy-5.3.0}/setup.cfg +0 -0
  12. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/__init__.py +0 -0
  13. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/adapters/__init__.py +0 -0
  14. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/adapters/http.py +0 -0
  15. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/ask.py +0 -0
  16. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/ask_knowledge.md +0 -0
  17. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/bootstrap.py +0 -0
  18. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/cache/__init__.py +0 -0
  19. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/cache/context.py +0 -0
  20. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/cache/provider.py +0 -0
  21. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/cache/redis_io.py +0 -0
  22. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/capabilities.py +0 -0
  23. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/core.py +0 -0
  24. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/__init__.py +0 -0
  25. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/claim.py +0 -0
  26. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/exec.py +0 -0
  27. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/id.py +0 -0
  28. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/mutation.py +0 -0
  29. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/query.py +0 -0
  30. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/triggers.py +0 -0
  31. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/crud/write.py +0 -0
  32. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/degraded.py +0 -0
  33. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/__init__.py +0 -0
  34. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/_values.py +0 -0
  35. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/mongo.py +0 -0
  36. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/mysql.py +0 -0
  37. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/postgres.py +0 -0
  38. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/executors/sqlite.py +0 -0
  39. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/feedback.py +0 -0
  40. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/introspect/__init__.py +0 -0
  41. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/introspect/mysql.py +0 -0
  42. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/introspect/postgres.py +0 -0
  43. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/introspect/sqlite.py +0 -0
  44. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/llm.py +0 -0
  45. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/load.py +0 -0
  46. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/local/__init__.py +0 -0
  47. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/local/handle.py +0 -0
  48. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/local/store.py +0 -0
  49. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/memory/__init__.py +0 -0
  50. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/metadef.py +0 -0
  51. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/migrate.py +0 -0
  52. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/naming.py +0 -0
  53. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/permission.py +0 -0
  54. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/reindex.py +0 -0
  55. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/resource/__init__.py +0 -0
  56. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/resource/providers/__init__.py +0 -0
  57. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/resource/providers/local.py +0 -0
  58. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/resource/providers/s3.py +0 -0
  59. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/scheduler/__init__.py +0 -0
  60. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/schema.py +0 -0
  61. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/scope.py +0 -0
  62. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/secure.py +0 -0
  63. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/sync.py +0 -0
  64. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/vector_index.py +0 -0
  65. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/vector_scan.py +0 -0
  66. {storepy-5.2.0 → storepy-5.3.0}/src/py_store/workflow.py +0 -0
  67. {storepy-5.2.0 → storepy-5.3.0}/src/storepy.egg-info/SOURCES.txt +0 -0
  68. {storepy-5.2.0 → storepy-5.3.0}/src/storepy.egg-info/dependency_links.txt +0 -0
  69. {storepy-5.2.0 → storepy-5.3.0}/src/storepy.egg-info/top_level.txt +0 -0
  70. {storepy-5.2.0 → storepy-5.3.0}/tests/test_access_keys.py +0 -0
  71. {storepy-5.2.0 → storepy-5.3.0}/tests/test_adapters.py +0 -0
  72. {storepy-5.2.0 → storepy-5.3.0}/tests/test_ask.py +0 -0
  73. {storepy-5.2.0 → storepy-5.3.0}/tests/test_cache.py +0 -0
  74. {storepy-5.2.0 → storepy-5.3.0}/tests/test_cache_link.py +0 -0
  75. {storepy-5.2.0 → storepy-5.3.0}/tests/test_claim_concurrency.py +0 -0
  76. {storepy-5.2.0 → storepy-5.3.0}/tests/test_compute_override.py +0 -0
  77. {storepy-5.2.0 → storepy-5.3.0}/tests/test_coverage_margin.py +0 -0
  78. {storepy-5.2.0 → storepy-5.3.0}/tests/test_federation_e2e.py +0 -0
  79. {storepy-5.2.0 → storepy-5.3.0}/tests/test_feedback_flush.py +0 -0
  80. {storepy-5.2.0 → storepy-5.3.0}/tests/test_field_name_type.py +0 -0
  81. {storepy-5.2.0 → storepy-5.3.0}/tests/test_fns_binding.py +0 -0
  82. {storepy-5.2.0 → storepy-5.3.0}/tests/test_host_contract.py +0 -0
  83. {storepy-5.2.0 → storepy-5.3.0}/tests/test_host_paths.py +0 -0
  84. {storepy-5.2.0 → storepy-5.3.0}/tests/test_inline_agg.py +0 -0
  85. {storepy-5.2.0 → storepy-5.3.0}/tests/test_load.py +0 -0
  86. {storepy-5.2.0 → storepy-5.3.0}/tests/test_local_store.py +0 -0
  87. {storepy-5.2.0 → storepy-5.3.0}/tests/test_memory.py +0 -0
  88. {storepy-5.2.0 → storepy-5.3.0}/tests/test_metadef.py +0 -0
  89. {storepy-5.2.0 → storepy-5.3.0}/tests/test_migrate.py +0 -0
  90. {storepy-5.2.0 → storepy-5.3.0}/tests/test_mongo_executor.py +0 -0
  91. {storepy-5.2.0 → storepy-5.3.0}/tests/test_mongo_session.py +0 -0
  92. {storepy-5.2.0 → storepy-5.3.0}/tests/test_multi_datasource.py +0 -0
  93. {storepy-5.2.0 → storepy-5.3.0}/tests/test_parity_deny.py +0 -0
  94. {storepy-5.2.0 → storepy-5.3.0}/tests/test_parity_local.py +0 -0
  95. {storepy-5.2.0 → storepy-5.3.0}/tests/test_parity_local_memory.py +0 -0
  96. {storepy-5.2.0 → storepy-5.3.0}/tests/test_parity_scope.py +0 -0
  97. {storepy-5.2.0 → storepy-5.3.0}/tests/test_policy_isolation.py +0 -0
  98. {storepy-5.2.0 → storepy-5.3.0}/tests/test_profile.py +0 -0
  99. {storepy-5.2.0 → storepy-5.3.0}/tests/test_py_store.py +0 -0
  100. {storepy-5.2.0 → storepy-5.3.0}/tests/test_rbac_host.py +0 -0
  101. {storepy-5.2.0 → storepy-5.3.0}/tests/test_real_backends_e2e.py +0 -0
  102. {storepy-5.2.0 → storepy-5.3.0}/tests/test_require_context.py +0 -0
  103. {storepy-5.2.0 → storepy-5.3.0}/tests/test_resource.py +0 -0
  104. {storepy-5.2.0 → storepy-5.3.0}/tests/test_resource_e2e.py +0 -0
  105. {storepy-5.2.0 → storepy-5.3.0}/tests/test_resource_pools.py +0 -0
  106. {storepy-5.2.0 → storepy-5.3.0}/tests/test_resource_units.py +0 -0
  107. {storepy-5.2.0 → storepy-5.3.0}/tests/test_scenario_course_platform.py +0 -0
  108. {storepy-5.2.0 → storepy-5.3.0}/tests/test_scenario_manager_transaction.py +0 -0
  109. {storepy-5.2.0 → storepy-5.3.0}/tests/test_scheduler.py +0 -0
  110. {storepy-5.2.0 → storepy-5.3.0}/tests/test_session.py +0 -0
  111. {storepy-5.2.0 → storepy-5.3.0}/tests/test_sql_commit_and_registry.py +0 -0
  112. {storepy-5.2.0 → storepy-5.3.0}/tests/test_triggers.py +0 -0
  113. {storepy-5.2.0 → storepy-5.3.0}/tests/test_vector_conformance.py +0 -0
  114. {storepy-5.2.0 → storepy-5.3.0}/tests/test_vector_index.py +0 -0
  115. {storepy-5.2.0 → storepy-5.3.0}/tests/test_vector_scan.py +0 -0
  116. {storepy-5.2.0 → storepy-5.3.0}/tests/test_vector_units.py +0 -0
  117. {storepy-5.2.0 → storepy-5.3.0}/tests/test_workflow.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: storepy
3
- Version: 5.2.0
3
+ Version: 5.3.0
4
4
  Summary: Multi-backend data layer for Python asyncio (MongoDB, MySQL, SQLite, PostgreSQL, local disk): pure JSON schemas, GQL tree queries compiled to a single native query, GROUP BY/HAVING aggregation, computed columns, soft-delete and role-based access control
5
5
  Author-email: 丁滔 <coen_ddt@qq.com>
6
6
  License-Expression: MIT
@@ -24,7 +24,7 @@ Requires-Python: >=3.10
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: pymongo>=4.9
27
- Requires-Dist: rust-store-py<6.0.0,>=5.2.0
27
+ Requires-Dist: rust-store-py<6.0.0,>=5.3.0
28
28
  Provides-Extra: mysql
29
29
  Requires-Dist: asyncmy>=0.2.9; extra == "mysql"
30
30
  Provides-Extra: postgres
@@ -458,7 +458,8 @@ sql = store.generate_ddl("postgres", ["Course", "CourseDeleted"])
458
458
  - Only scalar fields become columns; `object` / `array` fields do not.
459
459
  - Every table gets the `__present` sentinel column; `timestamps` models also get `createdAt` / `updatedAt`; the `<collection>_deleted` archive table is generated like any other registered def.
460
460
  - The `<Name>Deleted` archive def is **derived by the Rust core when the model is registered**; the Python host only mirrors it (`collection` `<c>_deleted`, the `deletedAt` field, empty `idPrefix`) and never re-registers it into the core. So `schema.list()` and `generate_ddl()` contain each archive table exactly once; if a duplicate ever appears (upstream regression), they deduplicate and emit a `schemaDuplicateName` / `ddlDuplicateTable` feedback event instead of silently emitting duplicate `CREATE TABLE`s.
461
- - No `CREATE INDEX` is emitted — SQL backends keep indexes as metadata only.
461
+ - `schema.indexes` (`{keys: {f: 1|-1}}`, Mongo shape) are emitted as `CREATE [UNIQUE] INDEX` after the table (phase 3 landed; see `ddl.py::_index_stmts`). The generator is still pure text.
462
+ - Field type `text` maps to `MEDIUMTEXT` (MySQL) / `TEXT` (PG, SQLite) for long strings (serialized state, base64, bodies). `string` stays `VARCHAR(255)`.
462
463
  - MySQL `__present` is `VARCHAR(255)`; a schema whose present-token string would overflow emits a `ddlPresentOverflow` feedback event rather than failing silently.
463
464
 
464
465
  ### Schema migration (orchestrator)
@@ -416,7 +416,8 @@ sql = store.generate_ddl("postgres", ["Course", "CourseDeleted"])
416
416
  - Only scalar fields become columns; `object` / `array` fields do not.
417
417
  - Every table gets the `__present` sentinel column; `timestamps` models also get `createdAt` / `updatedAt`; the `<collection>_deleted` archive table is generated like any other registered def.
418
418
  - The `<Name>Deleted` archive def is **derived by the Rust core when the model is registered**; the Python host only mirrors it (`collection` `<c>_deleted`, the `deletedAt` field, empty `idPrefix`) and never re-registers it into the core. So `schema.list()` and `generate_ddl()` contain each archive table exactly once; if a duplicate ever appears (upstream regression), they deduplicate and emit a `schemaDuplicateName` / `ddlDuplicateTable` feedback event instead of silently emitting duplicate `CREATE TABLE`s.
419
- - No `CREATE INDEX` is emitted — SQL backends keep indexes as metadata only.
419
+ - `schema.indexes` (`{keys: {f: 1|-1}}`, Mongo shape) are emitted as `CREATE [UNIQUE] INDEX` after the table (phase 3 landed; see `ddl.py::_index_stmts`). The generator is still pure text.
420
+ - Field type `text` maps to `MEDIUMTEXT` (MySQL) / `TEXT` (PG, SQLite) for long strings (serialized state, base64, bodies). `string` stays `VARCHAR(255)`.
420
421
  - MySQL `__present` is `VARCHAR(255)`; a schema whose present-token string would overflow emits a `ddlPresentOverflow` feedback event rather than failing silently.
421
422
 
422
423
  ### Schema migration (orchestrator)
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "storepy"
7
- version = "5.2.0"
7
+ version = "5.3.0"
8
8
  description = "Multi-backend data layer for Python asyncio (MongoDB, MySQL, SQLite, PostgreSQL, local disk): pure JSON schemas, GQL tree queries compiled to a single native query, GROUP BY/HAVING aggregation, computed columns, soft-delete and role-based access control"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -26,7 +26,7 @@ authors = [
26
26
  ]
27
27
  dependencies = [
28
28
  "pymongo>=4.9",
29
- "rust-store-py>=5.2.0,<6.0.0",
29
+ "rust-store-py>=5.3.0,<6.0.0",
30
30
  ]
31
31
  classifiers = [
32
32
  "Development Status :: 4 - Beta",
@@ -50,6 +50,16 @@ LOCAL_KIND = 'local'
50
50
  # 进程内内存数据源类型标记(与 local 同族:同为嵌入式载体)
51
51
  MEMORY_KIND = 'memory'
52
52
 
53
+ # MySQL 两步化 claim / compareAndSet 的 SQL 文本占位符(core 规划产物;
54
+ # 领取结果在下一条 stmt 文本中占位,由执行层回填,见 _exec_sql_direct)
55
+ _CLAIMED_IDS = '___claimed_ids___'
56
+
57
+
58
+ def _render_claimed_ids(ids) -> str:
59
+ """_id 列表 → SQL IN 字面量(单引号转义;_id 为框架生成值,转义为防御)"""
60
+ return '(' + ','.join("'" + str(v).replace("'", "''") + "'" for v in ids) + ')'
61
+
62
+
53
63
  _MISSING = object()
54
64
  # Mongo 事务能力缓存:client -> True/False(探测失败不写缓存,下次重探)
55
65
  _mongo_tx_cap: 'weakref.WeakKeyDictionary[object, bool]' = weakref.WeakKeyDictionary()
@@ -550,6 +560,27 @@ async def _exec_sql_direct(source, connection, cmd):
550
560
  if not callable(exec_fn):
551
561
  raise RuntimeError(
552
562
  f'SQL 数据源 {source}({_kind_of(connection)}) 的执行器未接入(见执行文档 Phase 4)')
563
+ stmts = plan.get('stmts') or []
564
+ if len(stmts) >= 2 and _CLAIMED_IDS in (stmts[1].get('text') or ''):
565
+ # MySQL 两步化 claim / compareAndSet:core 把领取结果下沉为 SQL 文本占位符
566
+ # (PG/SQLite 走 UPDATE…RETURNING 单条,不出现该分支)。必须先执行首条取回
567
+ # 命中 _id,回填后再执行置标语句——跳过回填会让驱动直接报
568
+ # ``1054 Unknown column '___claimed_ids___'``。
569
+ first = await exec_fn({'stmts': [stmts[0]]})
570
+ ids = [r['_id'] for r in (first.get('rows') or [])
571
+ if isinstance(r, Mapping) and '_id' in r]
572
+ if not ids:
573
+ # 零领取:不执行置标语句(与 run_atomic_commands「零领取直接返回空」一致)
574
+ return executors.shape_result(cmd, {
575
+ 'docs': None, 'rows': [], 'affectedRows': 0, 'insertId': None})
576
+ second = dict(stmts[1])
577
+ second['text'] = second['text'].replace(_CLAIMED_IDS, _render_claimed_ids(ids))
578
+ out1 = await exec_fn({'stmts': [second]})
579
+ # docs 置 None:首条只取 _id,其 restore 出的残行不能当作完整领取结果
580
+ # (「docs 直返」分支专为 SQLite UPDATE…RETURNING 设计)
581
+ return executors.shape_result(cmd, {
582
+ 'docs': None, 'rows': first.get('rows'),
583
+ 'affectedRows': out1.get('affectedRows', 0), 'insertId': None})
553
584
  out = await exec_fn(plan)
554
585
  return executors.shape_result(cmd, out)
555
586
 
@@ -613,6 +644,8 @@ async def execute_native(source, collection, pipeline, options=None):
613
644
  ``options.session`` 不可覆盖);统一按读路径解析(``is_write=False``),
614
645
  ``$merge``/``$out`` 写管道请自行开事务;
615
646
  - 仅支持 Mongo 源:SQL 源显式报错并指引 ``execute_raw``(绝不静默);
647
+ **适用源不同**:``execute_native`` 只跑 Mongo 原生命令;按 schema 的
648
+ ``aggregate``/``query``(pipeline 由 core 翻译成各方言 SQL)在 SQL 源同样可用。
616
649
  MongoClient 形态须经 schema 声明 database(``mongo_db`` 既有校验,缺名即报错);
617
650
  - 返回 ``{'rows': list}``。
618
651
  """
@@ -627,7 +660,9 @@ async def execute_native(source, collection, pipeline, options=None):
627
660
  session = conn.get('session')
628
661
  elif is_sql(conn):
629
662
  raise NativeCommandError(
630
- f'数据源 {source} 是 SQL 源(原生 Mongo 命令入口仅支持 mongo;SQL 源请用 execute_raw)')
663
+ f'数据源 {source} 是 SQL 源(execute_native 仅接受 Mongo 原生命令,SQL 源请用 '
664
+ f'execute_raw;按 schema 的 aggregate/query(pipeline 由 core 翻译)在 SQL 源'
665
+ f'可用——两者适用源不同)')
631
666
  elif _is_mongo_client(conn) or hasattr(conn, 'get_collection'):
632
667
  # 全局裸连接:MongoClient(须声明 database,缺名由 mongo_db 显式报错)/ db 实例
633
668
  db = mongo_db(conn, source, None)
@@ -29,6 +29,10 @@ _BACKENDS = ('mysql', 'postgres', 'sqlite')
29
29
  # schema 声明类型 → (mysql, postgres, sqlite) 列类型
30
30
  _TYPES = {
31
31
  'string': ('VARCHAR(255)', 'TEXT', 'TEXT'),
32
+ # 长文本(序列化状态、正文、base64 等数 KB 起步的字符串):MySQL 用 MEDIUMTEXT
33
+ # (16MB),避免调用方只能声明 string 再在建表后手改列型(宿主私改列型即绕过
34
+ # DDL 真源,见 AGENTS §22)。PG / SQLite 的 TEXT 本身无长度上限。
35
+ 'text': ('MEDIUMTEXT', 'TEXT', 'TEXT'),
32
36
  'int': ('INT', 'INTEGER', 'INTEGER'),
33
37
  'long': ('BIGINT', 'BIGINT', 'INTEGER'),
34
38
  'number': ('BIGINT', 'BIGINT', 'INTEGER'),
@@ -154,6 +158,11 @@ _ID_TYPE = ('VARCHAR(64)', 'TEXT', 'TEXT')
154
158
  _ID_AUTO_TYPE = ('INT AUTO_INCREMENT', 'SERIAL', 'INTEGER')
155
159
  _PRESENT_TYPE = ('VARCHAR(255)', 'TEXT', 'TEXT')
156
160
  _TIMESTAMP_FIELDS = ('createdAt', 'updatedAt')
161
+ # creator 权限隐含归属键(A2):与 core schema/registry.rs::add_creator_field 同款。
162
+ # 写入路径在 creator 权限场景下必注入 `createdBy`,因此该列必须建;仅靠「声明字段」
163
+ # 会导致未声明时 SQL 层报 1054 Unknown column 'created_by'(应用层只能再打补丁)。
164
+ _CREATOR_ROLE = 'creator'
165
+ _CREATOR_FIELD = 'createdBy'
157
166
  _MYSQL_PRESENT_MAX = 255
158
167
 
159
168
 
@@ -187,9 +196,29 @@ def _pname(backend, logical):
187
196
  return _native.translate_name(logical, backend)
188
197
 
189
198
 
199
+ def _has_creator_permission(defn):
200
+ """schema 的 read/write 是否含 creator 伪角色(决定归属键必建)"""
201
+ def _has(roles):
202
+ return bool(roles) and _CREATOR_ROLE in roles
203
+ return _has(defn.get('read')) or _has(defn.get('write'))
204
+
205
+
206
+ def _owner_field(defn):
207
+ """owner 行控使用的归属键名;None = 不使用 owner 行控(不补列)。
208
+
209
+ ownerKey 缺省 = createdBy;`_id` 是系统主键,DDL 已建,不重复补列。
210
+ 与 core schema/registry.rs::add_owner_field 同口径。
211
+ """
212
+ if not _has_creator_permission(defn):
213
+ return None
214
+ declared = defn.get('ownerKey')
215
+ name = declared if isinstance(declared, str) and declared else _CREATOR_FIELD
216
+ return None if name == '_id' else name
217
+
218
+
190
219
  def _columns(defn, backend):
191
220
  """返回 [(name, sql_type, pk, auto)],顺序:声明的字段(标量 / object·array JSON 列)→
192
- timestamps → __present;name 为该后端物理列名(snake_case)。"""
221
+ timestamps → 归属键(owner 行控隐含)→ __present;name 为该后端物理列名(snake_case)。"""
193
222
  i = _idx(backend)
194
223
  cols = []
195
224
  fields = defn.get('fields') or {}
@@ -222,6 +251,13 @@ def _columns(defn, backend):
222
251
  col = _pname(backend, ts)
223
252
  if not any(c[0] == col for c in cols):
224
253
  cols.append((col, _TYPES['number'][i], False, False))
254
+ # A2:owner 行控(creator 权限)⇒ 归属键必建(与时间戳同款自动补齐;
255
+ # 已声明则沿用声明的类型)。键名取 ownerKey(缺省 createdBy),与 core 同口径。
256
+ owner = _owner_field(defn)
257
+ if owner is not None:
258
+ col = _pname(backend, owner)
259
+ if not any(c[0] == col for c in cols):
260
+ cols.append((col, _TYPES['string'][i], False, False))
225
261
  cols.append(('__present', _PRESENT_TYPE[i], False, False))
226
262
  return cols
227
263
 
@@ -374,7 +410,10 @@ def _archive_defn_of(defn):
374
410
  """主 def → 归档表 def(列 = 主列 + deletedAt;剔除 _id 自增策略;indexes 继承;
375
411
  对齐 core registry.rs::archive_defn)"""
376
412
  fields = dict(defn.get('fields') or {})
377
- fields['deletedAt'] = {'type': 'number'}
413
+ # 主 def 可能已声明 deletedAt / deleted_at:已存在则不重复追加,
414
+ # 否则归档表 CREATE TABLE 会 duplicate column name
415
+ if 'deletedAt' not in fields and 'deleted_at' not in fields:
416
+ fields['deletedAt'] = {'type': 'number'}
378
417
  idf = fields.get('_id')
379
418
  if isinstance(idf, dict):
380
419
  idf = {k: v for k, v in idf.items() if k != 'strategy'}
@@ -514,7 +553,9 @@ def generate_migration(backend, old_defn, new_defn):
514
553
  if ftype in _NON_COLUMN or ftype == 'vector':
515
554
  raise ValueError(
516
555
  f'MIGRATION_UNSUPPORTED: 新列 "{name}"({ftype} 列)不支持 DEFAULT'
517
- '(存量行缺失语义由 __present 哨兵表达;default 仅影响新写入)')
556
+ '(建新表可设 default;老表新增列必须「加列 + 回填」两步:'
557
+ '先 ADD COLUMN 不带 default,再回填存量行——漏回填的行按新列过滤'
558
+ '会全表不可见;存量行缺失语义由 __present 哨兵表达)')
518
559
  col_sql += ' DEFAULT ' + _sql_literal(default)
519
560
  stmts.append(f'ALTER TABLE {_q(backend, table)} ADD COLUMN {col_sql}')
520
561
  # 归档表跟随:不同步则归档 insert(显式拷贝全列)因缺列报错;
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: storepy
3
- Version: 5.2.0
3
+ Version: 5.3.0
4
4
  Summary: Multi-backend data layer for Python asyncio (MongoDB, MySQL, SQLite, PostgreSQL, local disk): pure JSON schemas, GQL tree queries compiled to a single native query, GROUP BY/HAVING aggregation, computed columns, soft-delete and role-based access control
5
5
  Author-email: 丁滔 <coen_ddt@qq.com>
6
6
  License-Expression: MIT
@@ -24,7 +24,7 @@ Requires-Python: >=3.10
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: pymongo>=4.9
27
- Requires-Dist: rust-store-py<6.0.0,>=5.2.0
27
+ Requires-Dist: rust-store-py<6.0.0,>=5.3.0
28
28
  Provides-Extra: mysql
29
29
  Requires-Dist: asyncmy>=0.2.9; extra == "mysql"
30
30
  Provides-Extra: postgres
@@ -458,7 +458,8 @@ sql = store.generate_ddl("postgres", ["Course", "CourseDeleted"])
458
458
  - Only scalar fields become columns; `object` / `array` fields do not.
459
459
  - Every table gets the `__present` sentinel column; `timestamps` models also get `createdAt` / `updatedAt`; the `<collection>_deleted` archive table is generated like any other registered def.
460
460
  - The `<Name>Deleted` archive def is **derived by the Rust core when the model is registered**; the Python host only mirrors it (`collection` `<c>_deleted`, the `deletedAt` field, empty `idPrefix`) and never re-registers it into the core. So `schema.list()` and `generate_ddl()` contain each archive table exactly once; if a duplicate ever appears (upstream regression), they deduplicate and emit a `schemaDuplicateName` / `ddlDuplicateTable` feedback event instead of silently emitting duplicate `CREATE TABLE`s.
461
- - No `CREATE INDEX` is emitted — SQL backends keep indexes as metadata only.
461
+ - `schema.indexes` (`{keys: {f: 1|-1}}`, Mongo shape) are emitted as `CREATE [UNIQUE] INDEX` after the table (phase 3 landed; see `ddl.py::_index_stmts`). The generator is still pure text.
462
+ - Field type `text` maps to `MEDIUMTEXT` (MySQL) / `TEXT` (PG, SQLite) for long strings (serialized state, base64, bodies). `string` stays `VARCHAR(255)`.
462
463
  - MySQL `__present` is `VARCHAR(255)`; a schema whose present-token string would overflow emits a `ddlPresentOverflow` feedback event rather than failing silently.
463
464
 
464
465
  ### Schema migration (orchestrator)
@@ -1,5 +1,5 @@
1
1
  pymongo>=4.9
2
- rust-store-py<6.0.0,>=5.2.0
2
+ rust-store-py<6.0.0,>=5.3.0
3
3
 
4
4
  [dev]
5
5
  pytest>=8
@@ -114,6 +114,31 @@ def test_generate_bad_backend():
114
114
  ddl.generate_migration('mongodb', OLD, NEW)
115
115
 
116
116
 
117
+ def test_object_column_default_requires_backfill():
118
+ """A5:区分「标量列可随 ADD COLUMN 设 DEFAULT」与「object/vector 列必须加列 + 回填」。"""
119
+ obj_add = {
120
+ 'name': 'Order', 'collection': 'orders', 'idPrefix': 'o', 'timestamps': False,
121
+ 'fields': dict(OLD['fields'],
122
+ meta={'type': 'object', 'default': {'k': 1},
123
+ 'fields': {'k': {'type': 'int'}}}),
124
+ 'indexes': OLD['indexes'],
125
+ }
126
+ with pytest.raises(ValueError, match=r'加列 \+ 回填'):
127
+ ddl.generate_migration('mysql', OLD, obj_add)
128
+
129
+
130
+ def test_declared_deleted_at_creates_single_archive_column():
131
+ """主 def 已声明 deletedAt 时,归档表不得重复建 deleted_at 列。"""
132
+ defn = {
133
+ 'name': 'Doc', 'collection': 'docs', 'idPrefix': 'd', 'timestamps': False,
134
+ 'fields': {'_id': {'type': 'string'}, 'deleted_at': {'type': 'number', 'default': 0}},
135
+ }
136
+ stmts = ddl.generate_migration('sqlite', None, defn)
137
+ arch = [s for s in stmts if 'CREATE TABLE "docs_deleted"' in s]
138
+ assert arch, stmts
139
+ assert arch[0].count('"deleted_at"') == 1, arch[0]
140
+
141
+
117
142
  def test_parity_anchor():
118
143
  """双宿主 parity 锚:nodejs-store/tests/migration.test.js 的同输入输出必须逐字节一致。"""
119
144
  # sqlite 遇混合变更中的 widen → 整体显式拒绝(不产半截语句)
@@ -523,6 +523,69 @@ def test_ddl_unknown_field_type_raises():
523
523
  store.generate_ddl('mysql', ['DdlBad'])
524
524
 
525
525
 
526
+ def test_ddl_owner_key_uses_custom_field():
527
+ """ownerKey 自定义 + creator 权限 ⇒ 补 ownerKey 列,不再补 created_by(三后端)。"""
528
+ store.register({
529
+ 'name': 'DdlOwnerCustom', 'collection': 'ddl_owner_custom', 'idPrefix': 'o',
530
+ 'timestamps': False, 'write': ['creator'], 'ownerKey': 'creatorId',
531
+ 'fields': {'_id': {'type': 'string'}, 'title': {'type': 'string'}},
532
+ })
533
+ for backend, pat in (('mysql', '`creator_id` VARCHAR(255)'),
534
+ ('postgres', '"creator_id" TEXT'),
535
+ ('sqlite', '"creator_id" TEXT')):
536
+ ddl = store.generate_ddl(backend, ['DdlOwnerCustom'])
537
+ assert pat in ddl, ddl
538
+ assert 'created_by' not in ddl, ddl
539
+
540
+
541
+ def test_ddl_owner_key_without_owner_control_adds_nothing():
542
+ """无 creator 行控(ownerKey 仅声明语义)⇒ 不补列,行为不变。"""
543
+ store.register({
544
+ 'name': 'DdlOwnerNoCtl', 'collection': 'ddl_owner_noctl', 'idPrefix': 'o',
545
+ 'timestamps': False, 'ownerKey': 'creatorId', 'read': ['admin'],
546
+ 'fields': {'_id': {'type': 'string'}, 'title': {'type': 'string'}},
547
+ })
548
+ for backend in ('mysql', 'postgres', 'sqlite'):
549
+ ddl = store.generate_ddl(backend, ['DdlOwnerNoCtl'])
550
+ assert 'creator_id' not in ddl, ddl
551
+ assert 'created_by' not in ddl, ddl
552
+
553
+
554
+ def test_ddl_creator_permission_adds_created_by_column():
555
+ """A2:read/write 含 creator ⇒ DDL 自动补 created_by 列(三后端)。
556
+
557
+ 与 core schema/registry.rs::add_creator_field 同口径:注册期字段声明补齐 +
558
+ 建表列补齐,避免写入路径注入 createdBy 时 SQL 1054 Unknown column。
559
+ """
560
+ store.register({
561
+ 'name': 'DdlCreator', 'collection': 'ddl_creator', 'idPrefix': 'c',
562
+ 'timestamps': False, 'write': ['creator'],
563
+ 'fields': {'_id': {'type': 'string'}, 'title': {'type': 'string'}},
564
+ })
565
+ my = store.generate_ddl('mysql', ['DdlCreator'])
566
+ pg = store.generate_ddl('postgres', ['DdlCreator'])
567
+ lite = store.generate_ddl('sqlite', ['DdlCreator'])
568
+
569
+ assert '`created_by` VARCHAR(255)' in my
570
+ assert '"created_by" TEXT' in pg
571
+ assert '"created_by" TEXT' in lite
572
+
573
+
574
+ def test_ddl_creator_permission_keeps_declared_type():
575
+ """已声明 createdBy 时沿用声明类型,不重复建列。"""
576
+ store.register({
577
+ 'name': 'DdlCreatorDecl', 'collection': 'ddl_creator_decl', 'idPrefix': 'c',
578
+ 'timestamps': False, 'read': ['creator'],
579
+ 'fields': {
580
+ '_id': {'type': 'string'},
581
+ 'createdBy': {'type': 'string'},
582
+ },
583
+ })
584
+ sql = store.generate_ddl('mysql', ['DdlCreatorDecl'])
585
+
586
+ assert sql.count('`created_by`') == 1, sql
587
+
588
+
526
589
  def test_ddl_present_overflow_emits_feedback():
527
590
  events = []
528
591
  feedback.set_sink(events.append)
@@ -536,3 +599,70 @@ def test_ddl_present_overflow_emits_feedback():
536
599
  store.generate_ddl('mysql', ['DdlWide'])
537
600
 
538
601
  assert any(e.get('code') == 'ddlPresentOverflow' for e in events), events
602
+
603
+
604
+ def test_ddl_text_field_uses_backend_long_text():
605
+ """text 类型 → MySQL MEDIUMTEXT / PG·SQLite TEXT
606
+
607
+ 长字符串(任务序列化状态、base64、正文等数 KB 起步)此前只能声明 string,
608
+ 而 string 在 MySQL 侧固定 VARCHAR(255),宿主被迫在建表后手改列型(绕过 DDL 真源)。
609
+ """
610
+ store.register({
611
+ 'name': 'DdlText', 'collection': 'ddl_text', 'idPrefix': 'x', 'timestamps': False,
612
+ 'fields': {'_id': {'type': 'string'}, 'payload': {'type': 'text'}},
613
+ })
614
+ my = store.generate_ddl('mysql', ['DdlText'])
615
+ pg = store.generate_ddl('postgres', ['DdlText'])
616
+ lite = store.generate_ddl('sqlite', ['DdlText'])
617
+
618
+ assert '`payload` MEDIUMTEXT' in my
619
+ assert '"payload" TEXT' in pg
620
+ assert '"payload" TEXT' in lite
621
+
622
+
623
+ # ─── ③ 两步化 claim / compareAndSet:SQL 文本占位符回填 ─────────
624
+
625
+ class _TwoStepCore:
626
+ """dialect_translate 桩:返回 core 在 MySQL 侧产出的两条 stmt(首条取 _id、次条占位)"""
627
+
628
+ def dialect_translate(self, kind, cmd):
629
+ return {'stmts': [
630
+ {'text': 'SELECT _id FROM claim_jobs WHERE status = 0 LIMIT 2'},
631
+ {'text': 'UPDATE claim_jobs SET status = 1 WHERE _id IN ___claimed_ids___'},
632
+ ]}
633
+
634
+
635
+ def test_two_step_claim_backfills_sql_text_placeholder(monkeypatch):
636
+ calls = []
637
+
638
+ async def fake_exec(plan):
639
+ calls.append([dict(s) for s in plan['stmts']])
640
+ if len(calls) == 1:
641
+ return {'rows': [{'_id': 'a1'}, {'_id': 'a2'}], 'affectedRows': 0, 'insertId': None}
642
+ return {'rows': [], 'affectedRows': 2, 'insertId': None}
643
+
644
+ monkeypatch.setattr(datasource, 'get_core', lambda: _TwoStepCore())
645
+ out = _run(datasource._exec_sql_direct(
646
+ 'default', {'kind': 'mysql', 'exec': fake_exec},
647
+ {'kind': 'updateMany', 'collection': 'claim_jobs', 'filter': {}}))
648
+
649
+ # 置标语句的占位符必须按首条取回的 _id 回填,否则 MySQL 报 1054 Unknown column
650
+ assert calls[1][0]['text'] == (
651
+ "UPDATE claim_jobs SET status = 1 WHERE _id IN ('a1','a2')"), calls
652
+ assert out.modified_count == 2
653
+
654
+
655
+ def test_two_step_claim_zero_rows_skips_marker_stmt(monkeypatch):
656
+ calls = []
657
+
658
+ async def fake_exec(plan):
659
+ calls.append([dict(s) for s in plan['stmts']])
660
+ return {'rows': [], 'affectedRows': 0, 'insertId': None}
661
+
662
+ monkeypatch.setattr(datasource, 'get_core', lambda: _TwoStepCore())
663
+ out = _run(datasource._exec_sql_direct(
664
+ 'default', {'kind': 'mysql', 'exec': fake_exec},
665
+ {'kind': 'updateMany', 'collection': 'claim_jobs', 'filter': {}}))
666
+
667
+ assert len(calls) == 1 # 零领取:不执行置标语句(与 run_atomic_commands 一致)
668
+ assert out.modified_count == 0
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes