Skip to content

feat: 新增跨方言 JSON 类型 JSONType(PG 用 JSONB,SQLite/MySQL 降级 JSON) - #543

Closed
Echo-Note wants to merge 2 commits into
fastapiadmin:devfrom
Echo-Note:feat/cross-dialect-json-type
Closed

Echo-Note wants to merge 2 commits into
fastapiadmin:devfrom
Echo-Note:feat/cross-dialect-json-type

Conversation

@Echo-Note

Copy link
Copy Markdown

背景

MappedBase 基类声明「兼容 SQLite、MySQL 和 PostgreSQL」,但业务模型若直接硬编码 sqlalchemy.dialects.postgresql.JSONB,会在 SQLite / MySQL 下让 create_all 渲染失败:

sqlalchemy.exc.CompileError: can't render element of type JSONB

当前仓库已同时存在通用 JSON(如 system/menu、task/storage)与 JSONB 两种用法,缺乏统一入口。

改动

在 app/core/base_model.py 新增统一的跨方言 JSON 类型:

JSONType = JSONB().with_variant(JSON(), "sqlite", "mysql")
  • PostgreSQL(生产):渲染为 JSONB,保留索引 / 操作符能力。
  • SQLite / MySQL(测试 / 其他环境):降级为通用 JSON,保证 create_all 与 autogenerate 三种方言零漂移。

用法

业务模型定义 JSON 列时改用 JSONType,替代直接硬编码 JSONB:

from app.core.base_model import JSONType, ModelMixin, UserMixin

class XxxModel(ModelMixin, UserMixin):
    payload: Mapped[dict] = mapped_column(JSONType, nullable=False, comment="...")

验证

  • 三种方言下 MappedBase.metadata.create_all 均可正常编译、执行。
  • PostgreSQL 下 autogenerate 与现有 JSONB 迁移零漂移(with_variant 在 PostgreSQL 方言下仍渲染为 JSONB)。

关联 issue:#542

@fastapiadmin
fastapiadmin changed the base branch from master to dev October 22, 2026 12:49
fastapiadmin added a commit that referenced this pull request Oct 22, 2026
feat: 新增跨方言 JSON 类型 JSONType(rebase 版,替代 #543 的冲突)
@fastapiadmin

Copy link
Copy Markdown
Owner

感谢贡献 👍 这个改动本身已确认正确(三方言 DDL、SQLite create_all、ruff/pyright/pytest 均通过)。

它与 #541 都修改了 backend/app/core/base_model.py 第 1 行的 from sqlalchemy import ...,#541 先合并后本 PR 变为冲突。为不丢失你的改动,已基于最新 dev 重新应用(提交作者仍为 Echo-Note):

因此本 PR 关闭,内容已进入 dev。issue #542 保持 open:生成器把 jsonb 列渲染成 from sqlalchemy import JSONB(该 import 非法)的问题仍需后续修复,欢迎继续跟进。

xiaoyu-awk pushed a commit to xiaoyu-awk/FastapiAdmin that referenced this pull request Oct 23, 2026
原 PR fastapiadmin#543 的实现,因其与 fastapiadmin#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 fastapiadmin#542:本 PR 提供统一入口;生成器 jsonb 映射与方言类型 import 的修复留作后续。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants