ormate 0.1.1a1__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.
- ormate-0.1.1a1/.gitignore +20 -0
- ormate-0.1.1a1/.python-version +1 -0
- ormate-0.1.1a1/CHANGELOG.md +16 -0
- ormate-0.1.1a1/LICENSE +22 -0
- ormate-0.1.1a1/PKG-INFO +338 -0
- ormate-0.1.1a1/README.md +270 -0
- ormate-0.1.1a1/docs/publishing.md +33 -0
- ormate-0.1.1a1/examples/async_sqlalchemy.py +40 -0
- ormate-0.1.1a1/examples/async_sqlmodel.py +36 -0
- ormate-0.1.1a1/examples/elasticsearch.py +89 -0
- ormate-0.1.1a1/examples/query_dsl.py +81 -0
- ormate-0.1.1a1/examples/shared_transaction.py +43 -0
- ormate-0.1.1a1/examples/sync_sqlalchemy.py +21 -0
- ormate-0.1.1a1/examples/web_middleware.py +16 -0
- ormate-0.1.1a1/pyproject.toml +65 -0
- ormate-0.1.1a1/src/ormate/__init__.py +25 -0
- ormate-0.1.1a1/src/ormate/adapters/__init__.py +5 -0
- ormate-0.1.1a1/src/ormate/adapters/base.py +38 -0
- ormate-0.1.1a1/src/ormate/adapters/elasticsearch.py +192 -0
- ormate-0.1.1a1/src/ormate/adapters/sqlalchemy.py +200 -0
- ormate-0.1.1a1/src/ormate/adapters/sqlmodel.py +6 -0
- ormate-0.1.1a1/src/ormate/elasticsearch/__init__.py +12 -0
- ormate-0.1.1a1/src/ormate/elasticsearch/document.py +20 -0
- ormate-0.1.1a1/src/ormate/projection.py +37 -0
- ormate-0.1.1a1/src/ormate/protocols.py +17 -0
- ormate-0.1.1a1/src/ormate/py.typed +1 -0
- ormate-0.1.1a1/src/ormate/query.py +124 -0
- ormate-0.1.1a1/src/ormate/repository.py +150 -0
- ormate-0.1.1a1/src/ormate/sqlalchemy/__init__.py +16 -0
- ormate-0.1.1a1/src/ormate/sqlalchemy/database.py +174 -0
- ormate-0.1.1a1/src/ormate/sqlalchemy/sessions.py +90 -0
- ormate-0.1.1a1/src/ormate/web/__init__.py +8 -0
- ormate-0.1.1a1/src/ormate/web/middleware.py +43 -0
- ormate-0.1.1a1/tests/__init__.py +1 -0
- ormate-0.1.1a1/tests/conftest.py +31 -0
- ormate-0.1.1a1/tests/models.py +47 -0
- ormate-0.1.1a1/tests/test_async_database.py +40 -0
- ormate-0.1.1a1/tests/test_async_repository.py +31 -0
- ormate-0.1.1a1/tests/test_elasticsearch.py +142 -0
- ormate-0.1.1a1/tests/test_model_separation.py +14 -0
- ormate-0.1.1a1/tests/test_projection.py +69 -0
- ormate-0.1.1a1/tests/test_query.py +54 -0
- ormate-0.1.1a1/tests/test_sqlmodel.py +49 -0
- ormate-0.1.1a1/tests/test_sync_database.py +20 -0
- ormate-0.1.1a1/tests/test_sync_repository.py +8 -0
- ormate-0.1.1a1/tests/test_transactions.py +24 -0
- ormate-0.1.1a1/tests/test_web_middleware.py +27 -0
- ormate-0.1.1a1/uv.lock +1621 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Python-generated files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[oc]
|
|
4
|
+
build/
|
|
5
|
+
dist/
|
|
6
|
+
wheels/
|
|
7
|
+
*.egg-info
|
|
8
|
+
|
|
9
|
+
# Virtual environments
|
|
10
|
+
.venv
|
|
11
|
+
.venv/
|
|
12
|
+
dist/
|
|
13
|
+
build/
|
|
14
|
+
*.egg-info/
|
|
15
|
+
__pycache__/
|
|
16
|
+
*.py[cod]
|
|
17
|
+
.pytest_cache/
|
|
18
|
+
.mypy_cache/
|
|
19
|
+
.ruff_cache/
|
|
20
|
+
.coverage
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.13
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 - Unreleased
|
|
4
|
+
|
|
5
|
+
- 提供同步和异步 SQLAlchemy 会话作用域。
|
|
6
|
+
- 提供基于 `StorageAdapter` 的统一 `ModelRepository`。
|
|
7
|
+
- 提供 `SQLAlchemyAdapter`,SQLAlchemy 与 SQLModel 表模型共享同一套接口。
|
|
8
|
+
- 提供直接继承 `SQLAlchemyAdapter` 的 `SQLModelAdapter` 语义入口,不干预业务模型的基础字段定义。
|
|
9
|
+
- 通过 Adapter 的 `storage_name()` 统一解析 SQL 表名与 Elasticsearch 索引名。
|
|
10
|
+
- 提供可选 `ElasticsearchAdapter` 与 `ElasticsearchDocument`,支持原生 Query DSL、全文检索入口和聚合。
|
|
11
|
+
- 支持独立 Create、Update、Read 模型、批量主键操作、复合主键、计数和存在性检查。
|
|
12
|
+
- Repository 使用 `add`、`find`、`get`、`update`、`remove` 等仓储语义 API。
|
|
13
|
+
- ReadModel 普通读取按字段和 `validation_alias` 自动投影,并区分 `serialization_alias`。
|
|
14
|
+
- 提供可编译到 SQLAlchemy、SQLModel 和 Elasticsearch 的结构化过滤 DSL,同时保留原生查询。
|
|
15
|
+
- 增加结构化查询 DSL 的完整可运行示例。
|
|
16
|
+
- 提供并发安全的会话作用域、ASGI 中间件和数据库驱动 extras。
|
ormate-0.1.1a1/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 zhangzhanqi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
ormate-0.1.1a1/PKG-INFO
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ormate
|
|
3
|
+
Version: 0.1.1a1
|
|
4
|
+
Summary: Async repositories with separate read/write models and pluggable storage adapters
|
|
5
|
+
Author: zhangzhanqi
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 zhangzhanqi
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Keywords: asyncio,database,elasticsearch,repository,sqlalchemy,sqlmodel
|
|
30
|
+
Classifier: Development Status :: 3 - Alpha
|
|
31
|
+
Classifier: Framework :: AsyncIO
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Operating System :: OS Independent
|
|
34
|
+
Classifier: Programming Language :: Python :: 3
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
36
|
+
Classifier: Typing :: Typed
|
|
37
|
+
Requires-Python: >=3.13
|
|
38
|
+
Requires-Dist: sqlalchemy<3,>=2.0.36
|
|
39
|
+
Provides-Extra: dev
|
|
40
|
+
Requires-Dist: aiosqlite>=0.20; extra == 'dev'
|
|
41
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
42
|
+
Requires-Dist: elasticsearch[async]<10,>=8.17; extra == 'dev'
|
|
43
|
+
Requires-Dist: httpx>=0.28; extra == 'dev'
|
|
44
|
+
Requires-Dist: mypy>=1.13; extra == 'dev'
|
|
45
|
+
Requires-Dist: pydantic>=2.10; extra == 'dev'
|
|
46
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
47
|
+
Requires-Dist: pytest>=8.3; extra == 'dev'
|
|
48
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
49
|
+
Requires-Dist: sqlmodel>=0.0.22; extra == 'dev'
|
|
50
|
+
Requires-Dist: starlette>=0.41; extra == 'dev'
|
|
51
|
+
Requires-Dist: twine>=6.0; extra == 'dev'
|
|
52
|
+
Provides-Extra: elasticsearch
|
|
53
|
+
Requires-Dist: elasticsearch[async]<10,>=8.17; extra == 'elasticsearch'
|
|
54
|
+
Requires-Dist: pydantic>=2.10; extra == 'elasticsearch'
|
|
55
|
+
Provides-Extra: mysql
|
|
56
|
+
Requires-Dist: aiomysql>=0.2; extra == 'mysql'
|
|
57
|
+
Requires-Dist: pymysql>=1.1; extra == 'mysql'
|
|
58
|
+
Provides-Extra: postgresql
|
|
59
|
+
Requires-Dist: asyncpg>=0.30; extra == 'postgresql'
|
|
60
|
+
Requires-Dist: psycopg[binary]>=3.2; extra == 'postgresql'
|
|
61
|
+
Provides-Extra: sqlite
|
|
62
|
+
Requires-Dist: aiosqlite>=0.20; extra == 'sqlite'
|
|
63
|
+
Provides-Extra: sqlmodel
|
|
64
|
+
Requires-Dist: sqlmodel>=0.0.22; extra == 'sqlmodel'
|
|
65
|
+
Provides-Extra: web
|
|
66
|
+
Requires-Dist: starlette>=0.41; extra == 'web'
|
|
67
|
+
Description-Content-Type: text/markdown
|
|
68
|
+
|
|
69
|
+
# ormate
|
|
70
|
+
|
|
71
|
+
ormate 是一个异步 Repository 工具包,用同一套 CRUD 接口访问 SQLAlchemy、SQLModel 和 Elasticsearch。Repository 负责输入输出模型转换,Adapter 负责具体的存储操作和查询语法。
|
|
72
|
+
|
|
73
|
+
项目目前处于 `0.1.0` 阶段,API 在 `1.0` 前仍可能调整。
|
|
74
|
+
|
|
75
|
+
## 安装
|
|
76
|
+
|
|
77
|
+
需要 Python 3.13 或更高版本。核心包只依赖 SQLAlchemy:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install ormate
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
其他依赖按需安装:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install "ormate[sqlite]"
|
|
87
|
+
pip install "ormate[sqlmodel]"
|
|
88
|
+
pip install "ormate[postgresql]"
|
|
89
|
+
pip install "ormate[mysql]"
|
|
90
|
+
pip install "ormate[elasticsearch]"
|
|
91
|
+
pip install "ormate[web]"
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## SQLAlchemy
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from pydantic import BaseModel
|
|
98
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
99
|
+
|
|
100
|
+
from ormate import AsyncDatabase, ModelRepository, SQLAlchemyAdapter
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Base(DeclarativeBase):
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class User(Base):
|
|
108
|
+
__tablename__ = "users"
|
|
109
|
+
|
|
110
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
111
|
+
name: Mapped[str]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class UserCreate(BaseModel):
|
|
115
|
+
id: int
|
|
116
|
+
name: str
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class UserRead(BaseModel):
|
|
120
|
+
id: int
|
|
121
|
+
name: str
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
db = AsyncDatabase.create("sqlite+aiosqlite:///app.db")
|
|
125
|
+
repository = ModelRepository(SQLAlchemyAdapter(db), User, UserRead)
|
|
126
|
+
|
|
127
|
+
async with db.engine.begin() as connection:
|
|
128
|
+
await connection.run_sync(Base.metadata.create_all)
|
|
129
|
+
|
|
130
|
+
created = await repository.add(UserCreate(id=1, name="Ada"))
|
|
131
|
+
loaded = await repository.get(1)
|
|
132
|
+
updated = await repository.update_by_id(1, {"name": "Grace"})
|
|
133
|
+
deleted = await repository.remove_by_id(1)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Create 和 Update 参数可以是字典,也可以是实现了 `model_dump(exclude_unset=True)` 的 Pydantic/SQLModel 对象。传入 ReadModel 时,该模型需要提供 `model_validate()`;不传则返回存储模型。
|
|
137
|
+
|
|
138
|
+
SQLAlchemy 条件查询直接使用 SQLAlchemy 表达式:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
users = await repository.find(User.name.contains("Ada"), limit=20)
|
|
142
|
+
total = await repository.count(User.name.contains("Ada"))
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
SQLAlchemy、SQLModel 和 Elasticsearch 也可以共享结构化过滤 DSL:
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
from ormate import and_, eq, gte, in_, not_, or_
|
|
149
|
+
|
|
150
|
+
query = and_(
|
|
151
|
+
eq(Product.status, "published"),
|
|
152
|
+
gte(Product.created_at, start_time),
|
|
153
|
+
or_(in_(Product.category, ["guide", "reference"]), not_(eq(Product.hidden, True))),
|
|
154
|
+
)
|
|
155
|
+
items = await repository.find(query)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
DSL 字段可以写成底层存储字段名或 SQLAlchemy/SQLModel 映射字段,例如 `eq("active", True)` 和 `eq(Product.active, True)` 等价。映射字段会在构造表达式时归一化为其存储字段名,因此 DSL AST 不持有 SQLAlchemy 对象。它提供 `eq`、`ne`、`gt`、`gte`、`lt`、`lte`、`in_`、`not_in`、`and_`、`or_` 和 `not_`。SQL JOIN、ES 全文评分、nested、geo 和聚合等能力仍使用后端原生查询。
|
|
159
|
+
|
|
160
|
+
DSL 可以复用于所有接受查询条件的 Repository 方法:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
# 查询与统计
|
|
164
|
+
books = await repository.find(and_(eq("active", True), in_("category", ["book", "guide"])))
|
|
165
|
+
total = await repository.count(gte("price", 100))
|
|
166
|
+
available = await repository.exists(not_(eq("status", "deleted")))
|
|
167
|
+
|
|
168
|
+
# 条件更新与删除
|
|
169
|
+
updated = await repository.update(eq("status", "draft"), {"status": "review"})
|
|
170
|
+
removed = await repository.remove(and_(eq("active", False), lt("updated_at", expire_at)))
|
|
171
|
+
|
|
172
|
+
# 空集合具有固定语义
|
|
173
|
+
await repository.find(in_("id", [])) # 恒假,返回空列表
|
|
174
|
+
await repository.find(not_in("id", [])) # 恒真,返回全部
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
`and_()` 恒真,`or_()` 恒假;相同类型的嵌套组合会自动展平。`and_`、`or_`、`not_` 只接受 ormate DSL 节点,不能在节点内部混入 SQLAlchemy 表达式或 ES 字典。需要后端特有能力时,将完整原生查询直接传给 Repository。
|
|
178
|
+
|
|
179
|
+
完整可运行示例:
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
uv run python examples/query_dsl.py
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## ReadModel 字段投影
|
|
186
|
+
|
|
187
|
+
配置 ReadModel 后,普通读取只查询 ReadModel 验证所需的字段。`validation_alias` 用于推断存储字段,`serialization_alias` 只控制向外序列化:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from pydantic import BaseModel, Field
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class UserRead(BaseModel):
|
|
194
|
+
display_name: str = Field(
|
|
195
|
+
validation_alias="name",
|
|
196
|
+
serialization_alias="displayName",
|
|
197
|
+
)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
这个模型从底层读取 `name`,执行 `model_dump(by_alias=True)` 时输出 `displayName`。普通 `alias` 同时用于验证和序列化;只有 `serialization_alias` 时仍按模型字段名读取。纯字符串 `AliasChoices` 会选择第一个存在的存储字段,`AliasPath` 因 SQL 与 ES 路径语义不同而不支持自动投影。
|
|
201
|
+
|
|
202
|
+
自动投影应用于 `find`、`find_one`、`get` 和 `get_many`。创建、更新、删除以及未配置 ReadModel 的查询仍读取完整存储对象。
|
|
203
|
+
|
|
204
|
+
## SQLModel 与事务
|
|
205
|
+
|
|
206
|
+
`SQLModelAdapter` 继承 `SQLAlchemyAdapter`,两者使用相同的 Session 和事务实现。绑定到同一个 `Database` 后,SQLAlchemy 和 SQLModel 的操作可以放在同一个事务中:
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
audit_logs = ModelRepository(SQLAlchemyAdapter(db), AuditLog)
|
|
210
|
+
tasks = ModelRepository(SQLModelAdapter(db), Task)
|
|
211
|
+
|
|
212
|
+
async with db:
|
|
213
|
+
await audit_logs.add({"id": 1, "message": "task created"})
|
|
214
|
+
await tasks.add({"title": "publish package"})
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
作用域正常退出时提交,发生异常时回滚。同步代码可以使用 `Database` 和 `with db:`。
|
|
218
|
+
|
|
219
|
+
相关示例:
|
|
220
|
+
|
|
221
|
+
- `examples/async_sqlalchemy.py`
|
|
222
|
+
- `examples/sync_sqlalchemy.py`
|
|
223
|
+
- `examples/async_sqlmodel.py`
|
|
224
|
+
- `examples/shared_transaction.py`
|
|
225
|
+
|
|
226
|
+
## Elasticsearch
|
|
227
|
+
|
|
228
|
+
Elasticsearch 使用 Pydantic 文档模型,查询参数保持原生 Query DSL:
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
from ormate import ModelRepository
|
|
232
|
+
from ormate.elasticsearch import ElasticsearchAdapter, ElasticsearchDocument
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class ArticleDocument(ElasticsearchDocument):
|
|
236
|
+
index_name = "articles"
|
|
237
|
+
|
|
238
|
+
title: str
|
|
239
|
+
content: str
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
adapter = ElasticsearchAdapter(client, refresh="wait_for")
|
|
243
|
+
articles = ModelRepository(adapter, ArticleDocument)
|
|
244
|
+
|
|
245
|
+
created = await articles.add(
|
|
246
|
+
{"id": "quickstart", "title": "ormate", "content": "pluggable adapters"}
|
|
247
|
+
)
|
|
248
|
+
matched = await articles.find({"match": {"content": "adapters"}}, limit=10)
|
|
249
|
+
updated = await articles.update_by_id("quickstart", {"title": "ormate 0.1"})
|
|
250
|
+
deleted = await articles.remove_by_id("quickstart")
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
完整的索引初始化、CRUD、计数、聚合和客户端关闭示例在 `examples/elasticsearch.py`:
|
|
254
|
+
|
|
255
|
+
```bash
|
|
256
|
+
ELASTICSEARCH_URL=http://localhost:9200 uv run python examples/elasticsearch.py
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
全文检索和聚合等 ES 专属操作直接通过 `ElasticsearchAdapter` 调用。Elasticsearch 不参与 SQL 事务;SQL 与 ES 双写需要使用 outbox、消息队列或补偿机制。
|
|
260
|
+
|
|
261
|
+
## Repository 和 Adapter
|
|
262
|
+
|
|
263
|
+
`ModelRepository` 提供以下通用操作:
|
|
264
|
+
|
|
265
|
+
- `add`、`add_many`
|
|
266
|
+
- `find`、`find_one`、`get`、`get_many`
|
|
267
|
+
- `update`、`update_by_id`、`update_many`
|
|
268
|
+
- `remove`、`remove_by_id`、`remove_many`
|
|
269
|
+
- `count`、`exists`、`limit`、`offset`
|
|
270
|
+
- 后端原生命令执行
|
|
271
|
+
|
|
272
|
+
SQLAlchemy/SQLModel 额外支持复合主键。后端特有的能力不放进通用协议,例如 SQL JOIN 和 ES 聚合分别留在对应 Adapter 中。
|
|
273
|
+
|
|
274
|
+
实现 `StorageAdapter` 协议可以接入其他存储:
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
repository = ModelRepository(custom_adapter, CustomModel, CustomRead)
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
Adapter 负责持久化、查询、主键条件和存储名称。Repository 负责输入转换、`encode_for_storage()`、`decode_from_storage()` 和 ReadModel 构造。
|
|
281
|
+
|
|
282
|
+
ormate 不定义 `id`、`created_at`、`updated_at` 等业务字段。SQLAlchemy/SQLModel 继续使用 `__tablename__`,Elasticsearch 使用 `index_name`,统一名称可以从 Repository 获取:
|
|
283
|
+
|
|
284
|
+
```python
|
|
285
|
+
repository.storage_name
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`ElasticsearchDocument.id` 只用于映射 Elasticsearch `_id`。
|
|
289
|
+
|
|
290
|
+
## Web 中间件
|
|
291
|
+
|
|
292
|
+
```python
|
|
293
|
+
from ormate.web import DBSessionMiddleware
|
|
294
|
+
|
|
295
|
+
app.add_middleware(
|
|
296
|
+
DBSessionMiddleware,
|
|
297
|
+
db=db,
|
|
298
|
+
rollback_on_http_error=True,
|
|
299
|
+
)
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
中间件接受 `AsyncDatabase` 或 `AsyncEngine`,为每个 HTTP/WebSocket 请求建立独立会话作用域。
|
|
303
|
+
|
|
304
|
+
## 当前限制
|
|
305
|
+
|
|
306
|
+
- PostgreSQL、MySQL 和真实 Elasticsearch 集群尚未加入自动化集成测试。
|
|
307
|
+
- Elasticsearch 条件批量更新和删除受 `default_size` 限制,默认最多处理 1000 个匹配文档。
|
|
308
|
+
- ES mapping 迁移、bulk、PIT/search_after 和乐观并发控制尚未实现。
|
|
309
|
+
- 不提供 SQL 与 Elasticsearch 之间的分布式事务。
|
|
310
|
+
|
|
311
|
+
## 路线图
|
|
312
|
+
|
|
313
|
+
`0.1.x` 用于完成首次 PyPI 发布,当前还需要经过 TestPyPI 安装验证。
|
|
314
|
+
|
|
315
|
+
`0.2` 主要完善 Elasticsearch:bulk 写入、PIT/search_after、索引 mapping 管理、并发冲突处理和真实集群测试。
|
|
316
|
+
|
|
317
|
+
`0.3` 主要完善关系型数据库:PostgreSQL/MySQL 测试矩阵、分页结果类型、显式 savepoint API 和批量性能优化。
|
|
318
|
+
|
|
319
|
+
后续会补充 Adapter 契约测试工具,并评估 MongoDB、RedisJSON 以及 SQL 到 ES 的 outbox 示例。到 `1.0` 前会冻结公共 API,补齐迁移指南和性能基准。
|
|
320
|
+
|
|
321
|
+
路线图只表示开发方向,不承诺具体发布日期。
|
|
322
|
+
|
|
323
|
+
## 开发
|
|
324
|
+
|
|
325
|
+
```bash
|
|
326
|
+
uv sync --all-extras
|
|
327
|
+
uv run ruff check .
|
|
328
|
+
uv run mypy
|
|
329
|
+
uv run pytest
|
|
330
|
+
uv build
|
|
331
|
+
uv run twine check dist/*
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
发布步骤见 `docs/publishing.md`。
|
|
335
|
+
|
|
336
|
+
## License
|
|
337
|
+
|
|
338
|
+
[MIT License](LICENSE)
|
ormate-0.1.1a1/README.md
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
# ormate
|
|
2
|
+
|
|
3
|
+
ormate 是一个异步 Repository 工具包,用同一套 CRUD 接口访问 SQLAlchemy、SQLModel 和 Elasticsearch。Repository 负责输入输出模型转换,Adapter 负责具体的存储操作和查询语法。
|
|
4
|
+
|
|
5
|
+
项目目前处于 `0.1.0` 阶段,API 在 `1.0` 前仍可能调整。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
需要 Python 3.13 或更高版本。核心包只依赖 SQLAlchemy:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install ormate
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
其他依赖按需安装:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install "ormate[sqlite]"
|
|
19
|
+
pip install "ormate[sqlmodel]"
|
|
20
|
+
pip install "ormate[postgresql]"
|
|
21
|
+
pip install "ormate[mysql]"
|
|
22
|
+
pip install "ormate[elasticsearch]"
|
|
23
|
+
pip install "ormate[web]"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## SQLAlchemy
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from pydantic import BaseModel
|
|
30
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
31
|
+
|
|
32
|
+
from ormate import AsyncDatabase, ModelRepository, SQLAlchemyAdapter
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Base(DeclarativeBase):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class User(Base):
|
|
40
|
+
__tablename__ = "users"
|
|
41
|
+
|
|
42
|
+
id: Mapped[int] = mapped_column(primary_key=True)
|
|
43
|
+
name: Mapped[str]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class UserCreate(BaseModel):
|
|
47
|
+
id: int
|
|
48
|
+
name: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UserRead(BaseModel):
|
|
52
|
+
id: int
|
|
53
|
+
name: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
db = AsyncDatabase.create("sqlite+aiosqlite:///app.db")
|
|
57
|
+
repository = ModelRepository(SQLAlchemyAdapter(db), User, UserRead)
|
|
58
|
+
|
|
59
|
+
async with db.engine.begin() as connection:
|
|
60
|
+
await connection.run_sync(Base.metadata.create_all)
|
|
61
|
+
|
|
62
|
+
created = await repository.add(UserCreate(id=1, name="Ada"))
|
|
63
|
+
loaded = await repository.get(1)
|
|
64
|
+
updated = await repository.update_by_id(1, {"name": "Grace"})
|
|
65
|
+
deleted = await repository.remove_by_id(1)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Create 和 Update 参数可以是字典,也可以是实现了 `model_dump(exclude_unset=True)` 的 Pydantic/SQLModel 对象。传入 ReadModel 时,该模型需要提供 `model_validate()`;不传则返回存储模型。
|
|
69
|
+
|
|
70
|
+
SQLAlchemy 条件查询直接使用 SQLAlchemy 表达式:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
users = await repository.find(User.name.contains("Ada"), limit=20)
|
|
74
|
+
total = await repository.count(User.name.contains("Ada"))
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
SQLAlchemy、SQLModel 和 Elasticsearch 也可以共享结构化过滤 DSL:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from ormate import and_, eq, gte, in_, not_, or_
|
|
81
|
+
|
|
82
|
+
query = and_(
|
|
83
|
+
eq(Product.status, "published"),
|
|
84
|
+
gte(Product.created_at, start_time),
|
|
85
|
+
or_(in_(Product.category, ["guide", "reference"]), not_(eq(Product.hidden, True))),
|
|
86
|
+
)
|
|
87
|
+
items = await repository.find(query)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
DSL 字段可以写成底层存储字段名或 SQLAlchemy/SQLModel 映射字段,例如 `eq("active", True)` 和 `eq(Product.active, True)` 等价。映射字段会在构造表达式时归一化为其存储字段名,因此 DSL AST 不持有 SQLAlchemy 对象。它提供 `eq`、`ne`、`gt`、`gte`、`lt`、`lte`、`in_`、`not_in`、`and_`、`or_` 和 `not_`。SQL JOIN、ES 全文评分、nested、geo 和聚合等能力仍使用后端原生查询。
|
|
91
|
+
|
|
92
|
+
DSL 可以复用于所有接受查询条件的 Repository 方法:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
# 查询与统计
|
|
96
|
+
books = await repository.find(and_(eq("active", True), in_("category", ["book", "guide"])))
|
|
97
|
+
total = await repository.count(gte("price", 100))
|
|
98
|
+
available = await repository.exists(not_(eq("status", "deleted")))
|
|
99
|
+
|
|
100
|
+
# 条件更新与删除
|
|
101
|
+
updated = await repository.update(eq("status", "draft"), {"status": "review"})
|
|
102
|
+
removed = await repository.remove(and_(eq("active", False), lt("updated_at", expire_at)))
|
|
103
|
+
|
|
104
|
+
# 空集合具有固定语义
|
|
105
|
+
await repository.find(in_("id", [])) # 恒假,返回空列表
|
|
106
|
+
await repository.find(not_in("id", [])) # 恒真,返回全部
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`and_()` 恒真,`or_()` 恒假;相同类型的嵌套组合会自动展平。`and_`、`or_`、`not_` 只接受 ormate DSL 节点,不能在节点内部混入 SQLAlchemy 表达式或 ES 字典。需要后端特有能力时,将完整原生查询直接传给 Repository。
|
|
110
|
+
|
|
111
|
+
完整可运行示例:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
uv run python examples/query_dsl.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## ReadModel 字段投影
|
|
118
|
+
|
|
119
|
+
配置 ReadModel 后,普通读取只查询 ReadModel 验证所需的字段。`validation_alias` 用于推断存储字段,`serialization_alias` 只控制向外序列化:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from pydantic import BaseModel, Field
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class UserRead(BaseModel):
|
|
126
|
+
display_name: str = Field(
|
|
127
|
+
validation_alias="name",
|
|
128
|
+
serialization_alias="displayName",
|
|
129
|
+
)
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
这个模型从底层读取 `name`,执行 `model_dump(by_alias=True)` 时输出 `displayName`。普通 `alias` 同时用于验证和序列化;只有 `serialization_alias` 时仍按模型字段名读取。纯字符串 `AliasChoices` 会选择第一个存在的存储字段,`AliasPath` 因 SQL 与 ES 路径语义不同而不支持自动投影。
|
|
133
|
+
|
|
134
|
+
自动投影应用于 `find`、`find_one`、`get` 和 `get_many`。创建、更新、删除以及未配置 ReadModel 的查询仍读取完整存储对象。
|
|
135
|
+
|
|
136
|
+
## SQLModel 与事务
|
|
137
|
+
|
|
138
|
+
`SQLModelAdapter` 继承 `SQLAlchemyAdapter`,两者使用相同的 Session 和事务实现。绑定到同一个 `Database` 后,SQLAlchemy 和 SQLModel 的操作可以放在同一个事务中:
|
|
139
|
+
|
|
140
|
+
```python
|
|
141
|
+
audit_logs = ModelRepository(SQLAlchemyAdapter(db), AuditLog)
|
|
142
|
+
tasks = ModelRepository(SQLModelAdapter(db), Task)
|
|
143
|
+
|
|
144
|
+
async with db:
|
|
145
|
+
await audit_logs.add({"id": 1, "message": "task created"})
|
|
146
|
+
await tasks.add({"title": "publish package"})
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
作用域正常退出时提交,发生异常时回滚。同步代码可以使用 `Database` 和 `with db:`。
|
|
150
|
+
|
|
151
|
+
相关示例:
|
|
152
|
+
|
|
153
|
+
- `examples/async_sqlalchemy.py`
|
|
154
|
+
- `examples/sync_sqlalchemy.py`
|
|
155
|
+
- `examples/async_sqlmodel.py`
|
|
156
|
+
- `examples/shared_transaction.py`
|
|
157
|
+
|
|
158
|
+
## Elasticsearch
|
|
159
|
+
|
|
160
|
+
Elasticsearch 使用 Pydantic 文档模型,查询参数保持原生 Query DSL:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from ormate import ModelRepository
|
|
164
|
+
from ormate.elasticsearch import ElasticsearchAdapter, ElasticsearchDocument
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class ArticleDocument(ElasticsearchDocument):
|
|
168
|
+
index_name = "articles"
|
|
169
|
+
|
|
170
|
+
title: str
|
|
171
|
+
content: str
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
adapter = ElasticsearchAdapter(client, refresh="wait_for")
|
|
175
|
+
articles = ModelRepository(adapter, ArticleDocument)
|
|
176
|
+
|
|
177
|
+
created = await articles.add(
|
|
178
|
+
{"id": "quickstart", "title": "ormate", "content": "pluggable adapters"}
|
|
179
|
+
)
|
|
180
|
+
matched = await articles.find({"match": {"content": "adapters"}}, limit=10)
|
|
181
|
+
updated = await articles.update_by_id("quickstart", {"title": "ormate 0.1"})
|
|
182
|
+
deleted = await articles.remove_by_id("quickstart")
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
完整的索引初始化、CRUD、计数、聚合和客户端关闭示例在 `examples/elasticsearch.py`:
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
ELASTICSEARCH_URL=http://localhost:9200 uv run python examples/elasticsearch.py
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
全文检索和聚合等 ES 专属操作直接通过 `ElasticsearchAdapter` 调用。Elasticsearch 不参与 SQL 事务;SQL 与 ES 双写需要使用 outbox、消息队列或补偿机制。
|
|
192
|
+
|
|
193
|
+
## Repository 和 Adapter
|
|
194
|
+
|
|
195
|
+
`ModelRepository` 提供以下通用操作:
|
|
196
|
+
|
|
197
|
+
- `add`、`add_many`
|
|
198
|
+
- `find`、`find_one`、`get`、`get_many`
|
|
199
|
+
- `update`、`update_by_id`、`update_many`
|
|
200
|
+
- `remove`、`remove_by_id`、`remove_many`
|
|
201
|
+
- `count`、`exists`、`limit`、`offset`
|
|
202
|
+
- 后端原生命令执行
|
|
203
|
+
|
|
204
|
+
SQLAlchemy/SQLModel 额外支持复合主键。后端特有的能力不放进通用协议,例如 SQL JOIN 和 ES 聚合分别留在对应 Adapter 中。
|
|
205
|
+
|
|
206
|
+
实现 `StorageAdapter` 协议可以接入其他存储:
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
repository = ModelRepository(custom_adapter, CustomModel, CustomRead)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Adapter 负责持久化、查询、主键条件和存储名称。Repository 负责输入转换、`encode_for_storage()`、`decode_from_storage()` 和 ReadModel 构造。
|
|
213
|
+
|
|
214
|
+
ormate 不定义 `id`、`created_at`、`updated_at` 等业务字段。SQLAlchemy/SQLModel 继续使用 `__tablename__`,Elasticsearch 使用 `index_name`,统一名称可以从 Repository 获取:
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
repository.storage_name
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`ElasticsearchDocument.id` 只用于映射 Elasticsearch `_id`。
|
|
221
|
+
|
|
222
|
+
## Web 中间件
|
|
223
|
+
|
|
224
|
+
```python
|
|
225
|
+
from ormate.web import DBSessionMiddleware
|
|
226
|
+
|
|
227
|
+
app.add_middleware(
|
|
228
|
+
DBSessionMiddleware,
|
|
229
|
+
db=db,
|
|
230
|
+
rollback_on_http_error=True,
|
|
231
|
+
)
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
中间件接受 `AsyncDatabase` 或 `AsyncEngine`,为每个 HTTP/WebSocket 请求建立独立会话作用域。
|
|
235
|
+
|
|
236
|
+
## 当前限制
|
|
237
|
+
|
|
238
|
+
- PostgreSQL、MySQL 和真实 Elasticsearch 集群尚未加入自动化集成测试。
|
|
239
|
+
- Elasticsearch 条件批量更新和删除受 `default_size` 限制,默认最多处理 1000 个匹配文档。
|
|
240
|
+
- ES mapping 迁移、bulk、PIT/search_after 和乐观并发控制尚未实现。
|
|
241
|
+
- 不提供 SQL 与 Elasticsearch 之间的分布式事务。
|
|
242
|
+
|
|
243
|
+
## 路线图
|
|
244
|
+
|
|
245
|
+
`0.1.x` 用于完成首次 PyPI 发布,当前还需要经过 TestPyPI 安装验证。
|
|
246
|
+
|
|
247
|
+
`0.2` 主要完善 Elasticsearch:bulk 写入、PIT/search_after、索引 mapping 管理、并发冲突处理和真实集群测试。
|
|
248
|
+
|
|
249
|
+
`0.3` 主要完善关系型数据库:PostgreSQL/MySQL 测试矩阵、分页结果类型、显式 savepoint API 和批量性能优化。
|
|
250
|
+
|
|
251
|
+
后续会补充 Adapter 契约测试工具,并评估 MongoDB、RedisJSON 以及 SQL 到 ES 的 outbox 示例。到 `1.0` 前会冻结公共 API,补齐迁移指南和性能基准。
|
|
252
|
+
|
|
253
|
+
路线图只表示开发方向,不承诺具体发布日期。
|
|
254
|
+
|
|
255
|
+
## 开发
|
|
256
|
+
|
|
257
|
+
```bash
|
|
258
|
+
uv sync --all-extras
|
|
259
|
+
uv run ruff check .
|
|
260
|
+
uv run mypy
|
|
261
|
+
uv run pytest
|
|
262
|
+
uv build
|
|
263
|
+
uv run twine check dist/*
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
发布步骤见 `docs/publishing.md`。
|
|
267
|
+
|
|
268
|
+
## License
|
|
269
|
+
|
|
270
|
+
[MIT License](LICENSE)
|