From 38f6eb5e935e22358e16467623a1c2deed1e52c0 Mon Sep 17 00:00:00 2001 From: Echo-Note Date: Thu, 22 Oct 2026 20:56:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E8=B7=A8=E6=96=B9?= =?UTF-8?q?=E8=A8=80=20JSON=20=E7=B1=BB=E5=9E=8B=20JSONType=EF=BC=88PG=20?= =?UTF-8?q?=E7=94=A8=20JSONB=EF=BC=8CSQLite/MySQL=20=E9=99=8D=E7=BA=A7=20J?= =?UTF-8?q?SON=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原 PR #543 的实现,因其与 #541 同改 base_model.py 的 import 行产生冲突,此处为基于最新 dev 的 rebase 版本,改动内容与原提交一致(提交作者保留为 Echo-Note)。 - PostgreSQL:JSONB;SQLite / MySQL:通用 JSON(TypeEngine.with_variant) - 验证:三方言 DDL(JSONB / JSON / JSON)、sqlite create_all 建表 + JSON 读写、 ruff / basedpyright 0 errors / pytest 97 passed 关联 issue #542:本 PR 提供统一入口;生成器 jsonb 映射与方言类型 import 的修复留作后续。 --- backend/app/core/base_model.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/backend/app/core/base_model.py b/backend/app/core/base_model.py index 7bfc18bb5..7ec7854b0 100644 --- a/backend/app/core/base_model.py +++ b/backend/app/core/base_model.py @@ -1,6 +1,7 @@ from datetime import UTC, datetime -from sqlalchemy import Boolean, DateTime, Index, Integer, MetaData, String +from sqlalchemy import JSON, Boolean, DateTime, Index, Integer, MetaData, String +from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.asyncio import AsyncAttrs from sqlalchemy.orm import DeclarativeBase, Mapped, declared_attr, mapped_column, relationship @@ -18,6 +19,12 @@ "pk": "pk_%(table_name)s", } +# 跨方言 JSON 类型:PostgreSQL(生产)使用 JSONB,SQLite/MySQL(测试环境)降级为 +# 通用 JSON,保证 create_all 与 autogenerate 在三种方言下均可渲染、零漂移。 +# 各模块定义 JSON 列时统一使用 JSONType,而非直接硬编码 JSONB,避免破坏基类 +# 「兼容 SQLite、MySQL 和 PostgreSQL」的承诺。 +JSONType = JSONB().with_variant(JSON(), "sqlite", "mysql") + class MappedBase(AsyncAttrs, DeclarativeBase): """声明式基类