db.py
11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""数据库(外部 MySQL,SQLAlchemy Core):共享 MetaData、引擎、常用查询帮助函数,以及 Alembic 迁移入口。
用法:
from app.core import db
db.rows(db.select(t).where(t.c.store_id == sid))
"""
from __future__ import annotations
import datetime as dt
import json
from contextlib import contextmanager
from typing import Any, Iterator
from sqlalchemy import (JSON, BigInteger, Boolean, Column, Date, DateTime, Float, Index, Integer, # noqa: F401
MetaData, String, Table, Text, UniqueConstraint, and_, create_engine, delete, desc, func,
insert, or_, select, text, update)
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.engine import Connection, Engine
from .config import C, SERVER_ROOT
NAMING = {"ix": "ix_%(table_name)s_%(column_0_N_name)s", "uq": "uq_%(table_name)s_%(column_0_N_name)s",
"pk": "pk_%(table_name)s", "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"}
metadata = MetaData(naming_convention=NAMING)
LongText = Text().with_variant(MEDIUMTEXT(), "mysql")
VERSION_TABLE = "atrs_sys_schema_version" # Alembic 版本表(和业务表一样用 atrs_ 前缀)
_engine: Engine | None = None
def init_engine(url: str | None = None) -> Engine:
global _engine
_engine = create_engine(url or C.db_url(), pool_pre_ping=True, pool_recycle=1800, pool_size=10, max_overflow=20,
future=True)
return _engine
def engine() -> Engine:
if _engine is None:
raise RuntimeError("数据库还没有初始化")
return _engine
def now() -> dt.datetime:
"""写库时间戳与调度用同一个时钟(测试时可快进)。"""
from . import clock
return clock.now()
@contextmanager
def tx() -> Iterator[Connection]:
with engine().begin() as c:
yield c
def q(stmt):
with engine().begin() as c:
return c.execute(stmt)
def rows(stmt) -> list[dict]:
with engine().begin() as c:
return [dict(r._mapping) for r in c.execute(stmt)]
def one(stmt) -> dict | None:
r = rows(stmt)
return r[0] if r else None
def scalar(stmt) -> Any:
with engine().begin() as c:
return c.execute(stmt).scalar()
def paged(stmt, page: int = 1, size: int = 20, max_size: int = 200) -> dict:
"""列表分页:stmt 是带 where / order_by 的 select;返回 {rows, total, page, size}(rows 未 plain)。"""
size = max(1, min(int(size or 20), max_size))
page = max(1, int(page or 1))
total = scalar(select(func.count()).select_from(stmt.order_by(None).subquery())) or 0
return {"rows": rows(stmt.limit(size).offset((page - 1) * size)), "total": total, "page": page, "size": size}
def jdump(o: Any) -> str:
return json.dumps(o, ensure_ascii=False, default=str)
def jload(s: Any, default: Any = None) -> Any:
if s is None or s == "":
return default
if isinstance(s, (dict, list)):
return s
try:
return json.loads(s)
except (TypeError, ValueError):
return default
def plain(row: dict | None) -> dict | None:
"""把一行里的 datetime / date 转成字符串,便于直接作为 JSON 返回。"""
if row is None:
return None
return {k: (v.isoformat(sep=" ") if isinstance(v, dt.datetime) else v.isoformat() if isinstance(v, dt.date) else v)
for k, v in row.items()}
# ---------------- 建库 / 表结构同步 / 迁移 ----------------
# 云端每次启动自动执行 migrate(),部署后不用手工建库建表:
# 1. 库不存在就建(utf8mb4);
# 2. 按 app.models 自动同步表结构(只管 atrs_ 开头的表):建表、加字段、改字段类型 / 可空 / 注释、建删索引;
# 3. 跑 migrations/versions 里的数据迁移(以后要搬数据、改数据才写迁移文件;表结构不用写,第 2 步自动做);
# 4. 删掉代码里已经没有的字段和表(.env 的 DB_SYNC_DROP=false 可关闭;旧版本程序连上新库时不删,防止回滚丢数据)。
# 新加的 NOT NULL 字段请给 server_default,否则老数据行加字段时可能报错。
TABLE_PREFIX = "atrs_"
SCHEMA_MARK = "db_schema" # atrs_sys_config 里的一行:最后一次同步表结构的程序版本
def alembic_config():
from alembic.config import Config as AlembicConfig
cfg = AlembicConfig() # 不读 ini 文件,全部在这里设置
cfg.set_main_option("script_location", str(SERVER_ROOT / "migrations"))
cfg.attributes["engine"] = engine()
return cfg
def ensure_database() -> bool:
"""连接串里的库不存在就建(utf8mb4_unicode_ci)。返回是否新建了库。"""
url = engine().url
name = url.database
if not name or not url.drivername.startswith("mysql"):
return False
root = create_engine(url.set(database=None), future=True)
try:
with root.connect() as c:
if c.execute(text("SELECT 1 FROM information_schema.schemata WHERE schema_name = :n"), {"n": name}).first():
return False
c.execute(text("CREATE DATABASE `{}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
.format(name.replace("`", "``"))))
_log().warning("数据库 %s 不存在,已自动创建", name)
return True
finally:
root.dispose()
def _log():
import logging
return logging.getLogger("server.db")
def _include_name(name, type_, parent_names) -> bool:
if type_ == "table":
return bool(name) and name.startswith(TABLE_PREFIX) and name != VERSION_TABLE
return True
def _schema_ops(conn: Connection) -> list:
"""库里的表结构和 app.models 的差异(alembic 自动比对),返回一条条 DDL 操作。只读。"""
from alembic.autogenerate import produce_migrations
from alembic.migration import MigrationContext
from alembic.operations.ops import ModifyTableOps
from .. import models # noqa: F401 注册全部表
mc = MigrationContext.configure(conn, opts={"compare_type": True, "include_name": _include_name})
out = []
for o in produce_migrations(mc, metadata).upgrade_ops.ops:
out.extend(o.ops if isinstance(o, ModifyTableOps) else [o])
return out
def _is_drop(o) -> bool:
from alembic.operations import ops
return isinstance(o, (ops.DropTableOp, ops.DropColumnOp))
def describe_op(o) -> str:
from alembic.operations import ops
t = getattr(o, "table_name", "")
if isinstance(o, ops.CreateTableOp):
return f"建表 {t}"
if isinstance(o, ops.DropTableOp):
return f"删表 {t}"
if isinstance(o, ops.AddColumnOp):
return f"加字段 {t}.{o.column.name}"
if isinstance(o, ops.DropColumnOp):
return f"删字段 {t}.{o.column_name}"
if isinstance(o, ops.AlterColumnOp):
what = [n for n, changed in (("类型", o.modify_type is not None), ("可空", o.modify_nullable is not None),
("注释", o.modify_comment is not False),
("默认值", o.modify_server_default is not False)) if changed]
return f"改字段 {t}.{o.column_name}({'、'.join(what) or '定义'})"
if isinstance(o, ops.CreateIndexOp):
return f"建索引 {t}.{o.index_name}"
if isinstance(o, ops.DropIndexOp):
return f"删索引 {t}.{o.index_name}"
if isinstance(o, ops.AddConstraintOp):
return f"建约束 {t}.{getattr(o, 'constraint_name', '')}"
if isinstance(o, ops.DropConstraintOp):
return f"删约束 {t}.{o.constraint_name}"
if isinstance(o, (ops.CreateTableCommentOp, ops.DropTableCommentOp)):
return f"改表注释 {t}"
return f"{type(o).__name__} {t}"
def schema_diff() -> list[str]:
"""库里的表结构还差哪些没同步(部署自检用,只读)。"""
with engine().connect() as c:
return [describe_op(o) for o in _schema_ops(c)]
def _apply(ops_: list) -> None:
from alembic.migration import MigrationContext
from alembic.operations import Operations
if not ops_:
return
with engine().begin() as c:
op = Operations(MigrationContext.configure(c))
for o in ops_:
_log().warning("表结构同步:%s", describe_op(o))
op.invoke(o)
def _sync_additive() -> None:
"""建表、加字段、改字段、建删索引 / 约束(不删字段和表)。先删索引再建,同名索引换列时不冲突。"""
from alembic.operations import ops
with engine().connect() as c:
todo = [o for o in _schema_ops(c) if not _is_drop(o)]
first = [o for o in todo if isinstance(o, (ops.DropIndexOp, ops.DropConstraintOp))]
_apply(first + [o for o in todo if o not in first])
def _version_tuple(v: str) -> tuple:
return tuple(int(x) if x.isdigit() else 0 for x in str(v or "0").split("."))
def _sync_drops() -> None:
"""删掉代码里已经没有的字段和表。DB_SYNC_DROP=false 不删;库是更新的程序版本同步过的(回滚到旧版本)也不删。"""
from .. import __version__
from ..models import settings_t
from .config import env_bool
with engine().connect() as c:
drops = [o for o in _schema_ops(c) if _is_drop(o)]
mark = jload(c.execute(select(settings_t.c.v).where(settings_t.c.k == SCHEMA_MARK)).scalar(), {}) or {}
newer = _version_tuple(mark.get("version")) > _version_tuple(__version__)
if drops and (newer or not env_bool("DB_SYNC_DROP", True)):
why = (f"库是更新的程序版本 {mark.get('version')} 同步过的(当前 {__version__})" if newer
else ".env 设置了 DB_SYNC_DROP=false")
_log().warning("%s,以下多余的字段 / 表没有删除:%s", why, ";".join(describe_op(o) for o in drops))
else:
_apply(drops)
if not newer:
with engine().begin() as c:
c.execute(delete(settings_t).where(settings_t.c.k == SCHEMA_MARK))
c.execute(insert(settings_t).values(k=SCHEMA_MARK, v=jdump({"version": __version__}), updated_by="系统",
updated_at=now()))
def _forget_unknown_revision() -> None:
"""版本表里记的迁移文件已经不存在(迁移文件合并过)→ 清掉,从头跑一遍现有的迁移(都可以重复执行)。"""
from alembic.script import ScriptDirectory
known = {s.revision for s in ScriptDirectory.from_config(alembic_config()).walk_revisions()}
with engine().begin() as c:
if not c.execute(text("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() "
"AND table_name = :t"), {"t": VERSION_TABLE}).first():
return
cur = [r[0] for r in c.execute(text(f"SELECT version_num FROM `{VERSION_TABLE}`"))]
if any(v not in known for v in cur):
_log().warning("迁移版本 %s 在代码里已不存在,重置后按现有迁移重新执行", "、".join(cur))
c.execute(text(f"DELETE FROM `{VERSION_TABLE}`"))
def migrate() -> None:
from alembic import command
ensure_database()
_sync_additive()
_forget_unknown_revision()
command.upgrade(alembic_config(), "head")
_sync_drops()