db.py
3.77 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
"""数据库(外部 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()}
# ---------------- 迁移 ----------------
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 migrate() -> None:
from alembic import command
command.upgrade(alembic_config(), "head")