自动生成实体
当数据库表数量庞大或频繁变动时,逐个手工配置 entities 会很繁琐。autoentities 允让你通过模式匹配规则,在服务启动时自动将符合条件的数据库对象公开为 API 实体。
IMPORTANT
autoentities 当前仅支持 SQL Server(mssql)数据源。
基本结构
json
{
"autoentities": {
"public-tables": {
"patterns": {
"include": ["dbo.public_%"],
"exclude": ["dbo.public_internal_%"],
"name": "{schema}_{object}"
},
"template": {
"rest": { "enabled": true },
"graphql": { "enabled": true },
"mcp": { "dml-tools": true },
"health": { "enabled": true },
"cache": { "enabled": true, "ttl-seconds": 30, "level": "L1L2" }
},
"permissions": [
{ "role": "anonymous", "actions": ["read"] }
]
}
}
}每个 autoentities 定义是一个命名配置块,你可以定义多个块,各自匹配不同的表集合并应用不同的权限策略。
patterns — 匹配规则
| 字段 | 说明 | 默认值 |
|---|---|---|
include | SQL LIKE 模式数组,匹配的对象会被公开 | ["%.%"] |
exclude | SQL LIKE 模式数组,匹配的对象会被排除 | null |
name | 实体命名模板,支持 {schema} 和 {object} 插值 | "{schema}_{object}" |
模式使用 T-SQL LIKE 语法。% 匹配任意字符序列,_ 匹配单个字符。
匹配示例
| include | exclude | 匹配结果 |
|---|---|---|
["dbo.%"] | — | dbo 架构下全部表 |
["dbo.%"] | ["dbo._internal%", "dbo.Temp%"] | dbo 架构下除去内表和临时表 |
["dbo.Sales%", "dbo.Order%"] | — | dbo 下以 Sales 或 Order 开头的表 |
命名模板 {schema}_{object} 会将 dbo.Products 映射为实体名 dbo_Products,{object} 则只取表名 Products。
template — 默认配置
template 定义了匹配实体自动获得的默认配置。作用等同于逐个实体的配置字段:
json
{
"template": {
"rest": { "enabled": true },
"graphql": { "enabled": true },
"mcp": { "dml-tools": true },
"health": { "enabled": true },
"cache": { "enabled": true, "ttl-seconds": 30, "level": "L1L2" }
}
}所有匹配的实体都会继承这些默认值。后续可以对个别实体用 entities 块显式覆盖。
permissions — 权限模板
为所有匹配实体统一应用的权限规则:
json
{
"permissions": [
{ "role": "anonymous", "actions": ["read"] },
{ "role": "authenticated", "actions": ["read", "create"] }
]
}格式与 entities 中的 permissions 完全相同。如果需要为不同实体组应用不同权限策略,可以创建多个 autoentities 定义块。
autoentities 与 entities 的关系
- 两者可以共存:
autoentities自动发现 +entities手工精调。 - 同名优先:如果一个实体同时被
autoentities匹配和entities定义,手工定义优先。 - 二选一:存在
autoentities时entities不是必需的,反之亦然。 - 启动时评估:每次服务启动时重新扫描数据库,新表自动上线。
使用 CLI
bash
# 创建 autoentities 定义并写入配置
dab auto-config my-def \
--patterns.include "dbo.%" \
--patterns.exclude "dbo.internal%" \
--patterns.name "{schema}_{object}" \
--template.rest.enabled true \
--template.graphql.enabled true \
--template.cache.enabled true \
--template.cache.ttl-seconds 30 \
--permissions "anonymous:read"
# 预览匹配结果(不修改配置)
dab auto-config-simulate my-def \
--patterns.include "dbo.%" \
--patterns.exclude "dbo.internal%"dab auto-config 会扫描数据库并生成 autoentities 配置写入配置文件。dab auto-config-simulate 只展示匹配结果,不实际修改配置。
适用场景
- 大表量管理后台:几百张表的 CMS 或后台系统,用
include按前缀匹配批量暴露。 - 数据中台:业务表不断新增,
autoentities自动将符合命名规则的表暴露为 API。 - 多租户:每个租户的 schema 使用相同表结构,
autoentities按 schema 名称匹配。 - 快速原型:初期不确定暴露哪些表,先用
autoentities匹配所有表快速体验。
限制
- 仅支持 SQL Server。
- 匹配的实体继承统一的
template和permissions,如需差异化配置需要单独用entities覆盖。 - 实体名由命名模板决定,可能与期望的 API 路径不一致——建议提前规划表命名规范。
