eorm 0.1.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.
- eorm-0.1.0/.gitignore +19 -0
- eorm-0.1.0/.python-version +1 -0
- eorm-0.1.0/LICENSE +201 -0
- eorm-0.1.0/PKG-INFO +384 -0
- eorm-0.1.0/README.md +367 -0
- eorm-0.1.0/eorm/__init__.py +17 -0
- eorm-0.1.0/eorm/ddl.py +56 -0
- eorm-0.1.0/eorm/dialects/__init__.py +0 -0
- eorm-0.1.0/eorm/dialects/base.py +712 -0
- eorm-0.1.0/eorm/dialects/mysql.py +291 -0
- eorm-0.1.0/eorm/dialects/postgresql.py +274 -0
- eorm-0.1.0/eorm/engine.py +194 -0
- eorm-0.1.0/eorm/exceptions.py +21 -0
- eorm-0.1.0/eorm/expression.py +237 -0
- eorm-0.1.0/eorm/fields.py +110 -0
- eorm-0.1.0/eorm/model.py +179 -0
- eorm-0.1.0/eorm/query.py +170 -0
- eorm-0.1.0/eorm/row.py +66 -0
- eorm-0.1.0/eorm/session.py +136 -0
- eorm-0.1.0/main.py +6 -0
- eorm-0.1.0/pyproject.toml +40 -0
- eorm-0.1.0/tests/__init__.py +0 -0
- eorm-0.1.0/tests/conftest.py +0 -0
- eorm-0.1.0/tests/test_ddl.py +838 -0
- eorm-0.1.0/tests/test_engine.py +277 -0
- eorm-0.1.0/tests/test_model.py +67 -0
- eorm-0.1.0/tests/test_query.py +641 -0
- eorm-0.1.0/tests/test_query_builder.py +626 -0
- eorm-0.1.0/uv.lock +861 -0
eorm-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.10
|
eorm-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
eorm-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: eorm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async ORM for MySQL and PostgreSQL, powered by Pydantic v2
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Requires-Dist: asyncmy>=0.2
|
|
8
|
+
Requires-Dist: asyncpg>=0.29
|
|
9
|
+
Requires-Dist: cryptography>=49.0.0
|
|
10
|
+
Requires-Dist: pydantic>=2.0
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# eorm
|
|
19
|
+
|
|
20
|
+
**Async ORM for Python 3.10+** — MySQL and PostgreSQL, 基于 Pydantic v2 开发, 以pydantic作为数据模型,同时增加额外字段属性作为数据库字段必要属性,从而可以操作数据库表结构.这个库以精简为主,不提供外键以及多对一,多对多等键功能
|
|
21
|
+
|
|
22
|
+
## 特性
|
|
23
|
+
|
|
24
|
+
- **Async-first** — 所有 I/O 均为 `async`/`await`,基于 `asyncmy`(MySQL)和 `asyncpg`(PostgreSQL)
|
|
25
|
+
- **Pydantic 原生** — 模型即 `BaseModel`,享受类型校验、序列化等全部 Pydantic 功能
|
|
26
|
+
- **表达式 API** — `==` `!=` `>` `<` `like()` `between()` `in_()` `json_path()` 生成参数化 SQL
|
|
27
|
+
- **DDL 自动同步** — `Model.sync_table()` 建表、新增列、修改列、创建索引,只增改不删
|
|
28
|
+
- **JSON 原生支持** — `dict`/`list` 自动映射 JSON/JSONB,默认值使用数据库原生函数
|
|
29
|
+
- **时间戳行为** — `timestamp_behavior="create"|"update"|"both"` 控制自动时间戳
|
|
30
|
+
- **联合索引** — `Meta.indexes` 声明,`Field(index=True)` 简写,只增不删
|
|
31
|
+
- **断连自动重试** — 连接断开时自动重试 3 次(指数退避),非连接错误直接抛出
|
|
32
|
+
- **多表 JOIN** — 显式 ON 条件,`Row` 对象支持属性/字典双模式访问
|
|
33
|
+
- **原生 SQL** — `execute_raw()` / `fetch_raw()` / `fetch_one_raw()` 绕过 ORM 直接执行
|
|
34
|
+
|
|
35
|
+
## 安装
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install eorm
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| 数据库 | 驱动 | 说明 |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| MySQL | `asyncmy` | 连接池 + 事务 |
|
|
44
|
+
| PostgreSQL | `asyncpg` | 连接池 + 事务 |
|
|
45
|
+
|
|
46
|
+
## 字段示例
|
|
47
|
+
```python
|
|
48
|
+
import datetime
|
|
49
|
+
from eorm import Field, Model
|
|
50
|
+
from eorm.ddl import Index
|
|
51
|
+
|
|
52
|
+
class AllFieldTypes(Model):
|
|
53
|
+
"""覆盖所有 Python 类型 → SQL 类型的映射。"""
|
|
54
|
+
|
|
55
|
+
class Meta:
|
|
56
|
+
table = "all_field_types"
|
|
57
|
+
indexes = [
|
|
58
|
+
Index(fields=("short_text",),unique=True),
|
|
59
|
+
Index(fields=("age","score")) #联合索引
|
|
60
|
+
]
|
|
61
|
+
# 注意: 当数据库中的某个字段值可能为None时, 请在类型后面加上 None类型, 否则反序列化时会报错 例如: short_name :str|None
|
|
62
|
+
# -- 主键 ---------------------------------------------------------
|
|
63
|
+
id: int = Field(primary_key=True, auto_increment=True,db_type="bigint")
|
|
64
|
+
# db_type 当设置了这个值的时候,数据库会直接使用这个值作为类型
|
|
65
|
+
# MySQL → `id` INT AUTO_INCREMENT PRIMARY KEY
|
|
66
|
+
# PG → "id" SERIAL PRIMARY KEY
|
|
67
|
+
|
|
68
|
+
# -- 字符串 -------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
short_text: str = Field(max_length=100, nullable=True,default="")
|
|
71
|
+
# max_length 指定 → VARCHAR(100)
|
|
72
|
+
|
|
73
|
+
free_text: str | None = None
|
|
74
|
+
# 不指定 max_length → TEXT
|
|
75
|
+
|
|
76
|
+
# -- 数值 ---------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
age: int | None = 0
|
|
79
|
+
# MySQL → INT, PG → INTEGER
|
|
80
|
+
|
|
81
|
+
score: float = Field(default=0)
|
|
82
|
+
# MySQL → DOUBLE, PG → DOUBLE PRECISION
|
|
83
|
+
|
|
84
|
+
price: decimal.Decimal | None = Field(default=0.0,db_type="decimal(8,5)")
|
|
85
|
+
# MySQL → DECIMAL(18,6), PG → DECIMAL(18,6)
|
|
86
|
+
|
|
87
|
+
# -- 布尔 ---------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
is_active: bool = Field(default=True)
|
|
90
|
+
# MySQL → BOOL, PG → BOOLEAN
|
|
91
|
+
|
|
92
|
+
# -- 日期时间 -----------------------------------------------------
|
|
93
|
+
|
|
94
|
+
created_at: datetime.datetime = Field(
|
|
95
|
+
default_factory=datetime.datetime.now,
|
|
96
|
+
timestamp_behavior="create", # INSERT 时写入,UPDATE 时跳过
|
|
97
|
+
)
|
|
98
|
+
# MySQL → DATETIME, PG → TIMESTAMP
|
|
99
|
+
|
|
100
|
+
updated_at: datetime.datetime = Field(
|
|
101
|
+
default_factory=datetime.datetime.now,
|
|
102
|
+
timestamp_behavior="both", # INSERT / UPDATE 都会刷新
|
|
103
|
+
index=True
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
event_date: datetime.date | None = None
|
|
107
|
+
# MySQL → DATE, PG → DATE
|
|
108
|
+
|
|
109
|
+
# -- 二进制 -------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
payload: bytes | None = None
|
|
112
|
+
# MySQL → BLOB, PG → BYTEA
|
|
113
|
+
|
|
114
|
+
# -- JSON ---------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
config: dict = Field(default_factory=dict)
|
|
117
|
+
# MySQL → JSON, PG → JSONB
|
|
118
|
+
# DDL: MySQL DEFAULT (JSON_OBJECT()), PG DEFAULT jsonb_build_object()
|
|
119
|
+
|
|
120
|
+
tags: list = Field(default_factory=list)
|
|
121
|
+
# MySQL → JSON, PG → JSONB
|
|
122
|
+
# DDL: MySQL DEFAULT (JSON_ARRAY()), PG DEFAULT jsonb_build_array()
|
|
123
|
+
new_field:list = Field(default_factory=list)
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
## 快速开始
|
|
131
|
+
|
|
132
|
+
### 1. 定义模型
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
import datetime
|
|
136
|
+
from eorm import Field, Model
|
|
137
|
+
from eorm.ddl import Index
|
|
138
|
+
|
|
139
|
+
class Article(Model):
|
|
140
|
+
class Meta:
|
|
141
|
+
table = "articles"
|
|
142
|
+
indexes = [
|
|
143
|
+
Index(fields=("title",)), # 单列索引
|
|
144
|
+
Index(fields=("title", "created_at")), # 联合索引
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
id: int = Field(primary_key=True, auto_increment=True)
|
|
148
|
+
title: str = Field(max_length=200)
|
|
149
|
+
body: str # → TEXT
|
|
150
|
+
tags: list = Field(default_factory=list) # → JSON/JSONB
|
|
151
|
+
view_count: int = Field(default=0)
|
|
152
|
+
created_at: datetime.datetime = Field(
|
|
153
|
+
default_factory=datetime.datetime.now,
|
|
154
|
+
timestamp_behavior="create", # INSERT 写入,UPDATE 保留原值
|
|
155
|
+
)
|
|
156
|
+
updated_at: datetime.datetime = Field(
|
|
157
|
+
default_factory=datetime.datetime.now,
|
|
158
|
+
timestamp_behavior="both", # INSERT + UPDATE 均刷新
|
|
159
|
+
)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### 2. 连接数据库
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from eorm.engine import create_mysql_engine, create_postgresql_engine
|
|
166
|
+
|
|
167
|
+
# Mysql 连接池(推荐)
|
|
168
|
+
mysql_engine = await engine.create_mysql_engine(host="127.0.0.1",port=3306,user="username",password="password",database="test",minsize=10,maxsize=20)
|
|
169
|
+
session = mysql_engine.session()
|
|
170
|
+
|
|
171
|
+
# PostgreSQL 连接池(推荐)
|
|
172
|
+
postgresql_engine = await engine.create_postgresql_engine(host="127.0.0.1",port=3306,user="username",password="password",database="test",min_size=50,max_size=100)
|
|
173
|
+
session = postgresql_engine.session()
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### 3. 建表 & 索引
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
await Article.sync_table(session.dialect)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
首次 → `CREATE TABLE IF NOT EXISTS` + `CREATE INDEX`。后续新增列/修改类型/新增索引分别合并为单条 `ALTER TABLE` / `CREATE INDEX`。**永不删除列、表或索引。**
|
|
183
|
+
|
|
184
|
+
### 4. CRUD
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
# INSERT
|
|
188
|
+
article = Article(title="Hello", tags=["tech"])
|
|
189
|
+
await session.save(article) # 单条插入,id 自动回填
|
|
190
|
+
await session.bulk_insert([...]) # 批量插入
|
|
191
|
+
|
|
192
|
+
# SELECT
|
|
193
|
+
await session.query(Article).all() # 全表
|
|
194
|
+
await session.query(Article).filter(Article.view_count >= 10).all() # 条件
|
|
195
|
+
await session.query(Article).filter(Article.id == 1).one() # 精确一条
|
|
196
|
+
await session.query(Article).filter(Article.title.like("Post%")).first() # 有则返无则 None
|
|
197
|
+
await session.query(Article).count() # 计数
|
|
198
|
+
await session.query(Article).filter(Article.id == 1).exists() # 存在性
|
|
199
|
+
await session.query(Article).order_by(Article.id.desc()).limit(10).offset(20).all() # 分页
|
|
200
|
+
|
|
201
|
+
# UPDATE
|
|
202
|
+
article.view_count += 1
|
|
203
|
+
await session.save(article) # 主键不为 None → UPDATE
|
|
204
|
+
await session.query(Article).filter(Article.view_count == 0).update(view_count=1) # 批量
|
|
205
|
+
|
|
206
|
+
# DELETE
|
|
207
|
+
await session.delete(article)
|
|
208
|
+
await session.query(Article).filter(Article.view_count == 0).delete() # 批量
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### 5. 高级查询
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
# LIKE / BETWEEN
|
|
215
|
+
await session.query(User).filter(User.name.like("张%")).all()
|
|
216
|
+
await session.query(Book).filter(Book.price.between(10, 50)).all()
|
|
217
|
+
|
|
218
|
+
# IN / IS NULL
|
|
219
|
+
await session.query(User).filter(User.role.in_(["admin", "editor"])).all()
|
|
220
|
+
await session.query(User).filter(User.email.is_null()).all()
|
|
221
|
+
|
|
222
|
+
# AND / OR
|
|
223
|
+
cond = (User.age >= 18) & (User.role == "member") # AND
|
|
224
|
+
cond = (User.role == "admin") | (User.role == "staff") # OR
|
|
225
|
+
|
|
226
|
+
# JSON 路径查询(MySQL: column->>'$.path' / PG: column->'key'->>'sub')
|
|
227
|
+
await session.query(Article).filter(Article.tags.json_path("$[0]") == "tech").all()
|
|
228
|
+
await session.query(Product).filter(Product.data.json_path("$.price") > 100).all()
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### 6. 多表 JOIN
|
|
232
|
+
|
|
233
|
+
```python
|
|
234
|
+
# 两表 INNER JOIN
|
|
235
|
+
rows = await session.query(Author).join(
|
|
236
|
+
Book, on=Author.id == Book.author_id
|
|
237
|
+
).filter(Book.price > 20).order_by(Author.name.asc()).all()
|
|
238
|
+
|
|
239
|
+
# LEFT JOIN
|
|
240
|
+
rows = await session.query(Author).join(
|
|
241
|
+
Book, on=Author.id == Book.author_id, type="LEFT"
|
|
242
|
+
).all()
|
|
243
|
+
|
|
244
|
+
# Row 访问
|
|
245
|
+
print(rows[0].authors.name) # 属性
|
|
246
|
+
print(rows[0]["authors.id"]) # 字典 key
|
|
247
|
+
print(dict(rows[0])) # 扁平字典
|
|
248
|
+
|
|
249
|
+
# select() 可用于查询指定字段,alias()可用于别名
|
|
250
|
+
d = await mysql_session.query(AllFieldTypes)\
|
|
251
|
+
.join(JoinTable,on=AllFieldTypes.id==JoinTable.all_id,type="left")\
|
|
252
|
+
.join(JoinTableSecond,on=JoinTable.id==JoinTableSecond.join_all_id,type="left")\
|
|
253
|
+
.select(AllFieldTypes.id,AllFieldTypes.short_text,JoinTable.short_text.alias("j_s_t"),JoinTableSecond.short_text.alias("j_ss_t")).all()
|
|
254
|
+
|
|
255
|
+
class ReturnJoinTableSecond(Model):
|
|
256
|
+
id: int|None
|
|
257
|
+
|
|
258
|
+
short_text: str|None
|
|
259
|
+
|
|
260
|
+
j_s_t: str|None
|
|
261
|
+
|
|
262
|
+
j_ss_t:str|None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# 后续可以使用pydantic提供的功能反序列化到pydantic模型中
|
|
266
|
+
adapter = TypeAdapter(list[ReturnJoinTableSecond])
|
|
267
|
+
e: list[ReturnJoinTableSecond] = adapter.validate_python(d)
|
|
268
|
+
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### 7. 事务 & 健康检查
|
|
272
|
+
|
|
273
|
+
```python
|
|
274
|
+
# Session 事务
|
|
275
|
+
async with session.transaction():
|
|
276
|
+
await session.save(alice)
|
|
277
|
+
await session.save(bob)
|
|
278
|
+
# 异常自动回滚,正常自动提交
|
|
279
|
+
|
|
280
|
+
# 健康检查
|
|
281
|
+
ok = await session.dialect.ping() # True → 连接正常
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### 8. 原生 SQL
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
await session.execute_raw("DELETE FROM users WHERE status = %s", ["inactive"])
|
|
288
|
+
rows = await session.fetch_raw("SELECT id, name FROM users WHERE age > %s", [18])
|
|
289
|
+
row = await session.fetch_one_raw("SELECT * FROM users WHERE id = %s", [1])
|
|
290
|
+
```
|
|
291
|
+
## 查看日志
|
|
292
|
+
```
|
|
293
|
+
import logging
|
|
294
|
+
|
|
295
|
+
# 看所有 SQL 语句
|
|
296
|
+
logging.getLogger("eorm").setLevel(logging.DEBUG)
|
|
297
|
+
|
|
298
|
+
# 只看 DDL 和重连信息
|
|
299
|
+
logging.getLogger("eorm").setLevel(logging.INFO)
|
|
300
|
+
|
|
301
|
+
# 配置输出格式
|
|
302
|
+
logging.basicConfig(
|
|
303
|
+
level=logging.DEBUG,
|
|
304
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
305
|
+
)
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## 模型定义参考
|
|
309
|
+
|
|
310
|
+
### Field 参数
|
|
311
|
+
|
|
312
|
+
| 参数 | 类型 | 默认值 | 说明 |
|
|
313
|
+
|---|---|---|---|
|
|
314
|
+
| `primary_key` | `bool` | `False` | 主键 |
|
|
315
|
+
| `auto_increment` | `bool` | `False` | 自增(仅 int 主键) |
|
|
316
|
+
| `column_name` | `str \| None` | `None` | 数据库列名,默认取 Python 属性名 |
|
|
317
|
+
| `nullable` | `bool` | `True` | 是否允许 NULL |
|
|
318
|
+
| `unique` | `bool` | `False` | 唯一约束 |
|
|
319
|
+
| `index` | `bool` | `False` | 单列索引(自动转为 Index) |
|
|
320
|
+
| `max_length` | `int \| None` | `None` | 字符串长度 → VARCHAR(n);无 → TEXT |
|
|
321
|
+
| `db_type` | `str \| None` | `None` | 直接指定数据库类型 |
|
|
322
|
+
| `timestamp_behavior` | `"create" \| "update" \| "both" \| None` | `None` | 自动时间戳行为 |
|
|
323
|
+
| `default` / `default_factory` | — | — | Python 默认值(同时生成 DDL DEFAULT) |
|
|
324
|
+
|
|
325
|
+
### timestamp_behavior
|
|
326
|
+
|
|
327
|
+
| 值 | INSERT | UPDATE |
|
|
328
|
+
|---|---|---|
|
|
329
|
+
| `"create"` | 写入值 | 跳过,保留原值 |
|
|
330
|
+
| `"update"` | 写入值 | 重新计算当前时间 |
|
|
331
|
+
| `"both"` | 写入值 | 重新计算当前时间 |
|
|
332
|
+
|
|
333
|
+
### Meta 配置
|
|
334
|
+
|
|
335
|
+
```python
|
|
336
|
+
class Meta:
|
|
337
|
+
table = "table_name" # 表名(必填)
|
|
338
|
+
indexes = [ # 联合索引(可选)
|
|
339
|
+
Index(fields=("col1", "col2")), # 普通索引
|
|
340
|
+
Index(fields=("col1",), unique=True), # 唯一索引
|
|
341
|
+
Index(fields=("col1", "col2"), name="idx_custom"), # 自定义名称
|
|
342
|
+
]
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
索引名自动生成规则:`ix_{table}_{fields}`(普通),`unq_{table}_{fields}`(唯一)。
|
|
346
|
+
|
|
347
|
+
### Python → SQL 类型映射
|
|
348
|
+
|
|
349
|
+
| Python 类型 | MySQL | PostgreSQL |
|
|
350
|
+
|---|---|---|
|
|
351
|
+
| `int` | `INT` | `INTEGER` |
|
|
352
|
+
| `int` + auto_increment PK | `INT AUTO_INCREMENT` | `SERIAL` |
|
|
353
|
+
| `str` + max_length | `VARCHAR(n)` | `VARCHAR(n)` |
|
|
354
|
+
| `str` 无 max_length | `TEXT` | `TEXT` |
|
|
355
|
+
| `bool` | `BOOL` | `BOOLEAN` |
|
|
356
|
+
| `float` | `DOUBLE` | `DOUBLE PRECISION` |
|
|
357
|
+
| `bytes` | `BLOB` | `BYTEA` |
|
|
358
|
+
| `datetime.datetime` | `DATETIME` | `TIMESTAMP` |
|
|
359
|
+
| `datetime.date` | `DATE` | `DATE` |
|
|
360
|
+
| `decimal.Decimal` | `DECIMAL(18,6)` | `DECIMAL(18,6)` |
|
|
361
|
+
| `dict` | `JSON` | `JSONB` |
|
|
362
|
+
| `list` | `JSON` | `JSONB` |
|
|
363
|
+
|
|
364
|
+
## 开发
|
|
365
|
+
|
|
366
|
+
```bash
|
|
367
|
+
uv sync # 安装依赖
|
|
368
|
+
uv run pytest # 运行测试(112 个)
|
|
369
|
+
uv run mypy eorm/ # 类型检查
|
|
370
|
+
uv run ruff check eorm/ # 代码风格
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
## 设计原则
|
|
374
|
+
|
|
375
|
+
- **参数化查询** — 所有 SQL 参数绑定,永不拼接用户输入
|
|
376
|
+
- **方言隔离** — MySQL / PG 差异封装在 Dialect 子类,业务层无感
|
|
377
|
+
- **安全 DDL** — 只增不改不删(ADD COLUMN + ALTER COLUMN + CREATE INDEX,不 DROP)
|
|
378
|
+
- **Pydantic 优先** — 模型定义、校验、序列化完全复用 Pydantic 生态
|
|
379
|
+
- **数据库原生优先** — JSON 默认值使用 `JSON_OBJECT()` / `jsonb_build_object()` 等原生函数,不依赖代码序列化
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
## License
|
|
383
|
+
|
|
384
|
+
[Apache License](./LICENSE)
|