流派
ORM-不可知JSON查询语言有可插接的Prisma适配器.
前端发送一个 GenQueryInput 对象。 后端验证它相对于一个 Schema 而适配器将结果转换为ORM操作. 运出适配器瞄准了Prisma.
安装
# npm pubblico (registry.npmjs.org), con provenienza
npm install @generazioneai/genquery
# Prisma client (peer; you almost certainly already have it)
npm install @prisma/client
快速启动( Prisma)
import { Prisma, PrismaClient } from "@prisma/client";
import { createPrismaEngine } from "@generazioneai/genquery/prisma";
const prisma = new PrismaClient();
// 1. One line to set up the schema (from the DMMF), adapter, and engine
const engine = createPrismaEngine(Prisma.dmmf.datamodel);
// 2. Run a query from a request body against a model delegate
const { data, current, total } = await engine.run(
{
searchBy: { firstName: "mario" },
orderBy: "createdAt",
pagination: { page: 0, perPage: 20 },
},
"User", // root entity name — Prisma delegates don't expose it
prisma.user, // target model delegate; entity type flows from this
);
// data: User[]
// current: data.length (omitted if pagination.showNumber === false)
// total: match count (via a parallel count; omitted if pagination.showTotal === false)
engine.run 是同步和返回 { data, current?, total? }。 。 。 . current 财务报告和审定财务报表 total 居民人数 pagination.showNumber 编号 : pagination.showTotal (两者均默认为 true); 设置 showTotal: false 跳过额外 count。 。 。 .
createPrismaEngine 是薄薄的包装 schemaFromPrisma → new PrismaAdapter → new GenQueryEngine。根实体("User")必须明确通过——普里斯马代表不会在稳定的公共API上暴露出他们的模型名. TS实体类型取自代表 findMany 返回时.
如果您只想要 Prisma args 对象( 海关链、 交易、 自己的) findMany 调用),分别解析和调用 runParsed,不执行则返回参数 :
const parsed = engine.parse(input, "User");
const args = engine.runParsed(parsed, prisma.user); // { where, orderBy, skip, take, include, ... }
const rows = await prisma.user.findMany(args);
需要精细的控制吗? 您仍然可以手动构建 :
const schema = schemaFromPrisma(Prisma.dmmf.datamodel, { overrides: { User: { meta: "string" } } });
const adapter = new PrismaAdapter(schema, { parallelCount: false });
const engine = new GenQueryEngine({ adapter }); // schema is read from the adapter
或者通过同样的选择 createPrismaEngine数字 :
const engine = createPrismaEngine(Prisma.dmmf.datamodel, {
schema: { overrides: { User: { meta: "string" } } },
adapter: { parallelCount: false },
});
核心概念
司马
这个 Schema 独立地描述您的数据模型。 解析器用它来拒绝未知字段;适配器用它来知道哪些字段是日期与字符串对关系.
与Prisma合作
import { schemaFromPrisma } from "@generazioneai/genquery/prisma";
const schema = schemaFromPrisma(Prisma.dmmf.datamodel);
// optional: restrict to specific models
const schema = schemaFromPrisma(Prisma.dmmf.datamodel, { models: ["User", "Post"] });
// optional: override fields with non-standard column types
const schema = schemaFromPrisma(Prisma.dmmf.datamodel, {
overrides: { User: { preferences: "string" } },
});
或明确声明(无ORM,或精细控制):
const schema: Schema = {
entities: {
EntityName: {
name: "EntityName",
primaryKey: "id", // optional, defaults to "id"
fields: {
fieldName: { type: "string" | "number" | "boolean" | "date" },
},
relations: {
relationName: { target: "OtherEntity", kind: "one" | "many" },
},
},
},
};
查询输入
A 类 GenQueryInput 是一个有五个可选顶级密钥的平版 JSON 对象.
实体类型从 target 具有可识别形状的参数(Prisma模型代表曝光) findMany(args?): Promise<T[]>) (中文(简体) ). 无需明确通用——自动完成和价值形状检查来自代表的实体类型:
// prisma.user is Prisma.UserDelegate — entity type flows into the call below
await engine.run(
{
searchBy: {
firstName: "mario", // OK
age: { operation: ">=", value: 18 }, // OK — number → comparison
birthDate: { after: "2000-01-01T00:00:00Z" }, // OK — date → range
posts: { title: "typescript" }, // OK — relation → recursive
// age: "x", // ✗ type error: number field can't take a string
// nope: "x", // ✗ type error: 'nope' isn't a field on User
},
orderBy: { field: "lastName", order: "asc" }, // ✓ field constrained to User keys
select: { firstName: true }, // ✓ only primitive fields
include: { posts: "all" }, // ✓ only relations
},
"User",
prisma.user,
);
推论区分了字段(原始-可搜索/可选择)与关系(对象/阵列-不可包含/递归搜索),并按字段类型选择正确的值形状(字符串/数字/boolean/Date/enum).
如果您的目标类型不暴露实体,输入会回落到一个松散的形式,其中任何密钥/值都被接受——运行时的分解器仍然会比照计划验证一切.
顶级密钥 :
| 密钥 | 默认 | 目的 |
|---|---|---|
searchBy | —— 说 | 过滤条件( AND + OR) |
orderBy | —— 说 | 排序字段和方向 |
select | "all" | 要返回的字段( 已取消的政策字段) "all"(中文(简体) ) |
include | "none" | 哪些关系要加入 |
pagination | "all" | 页/ 限制 |
完整查询语言引用 : 文献/查询
发动机
GenQueryEngine 是公共入境点。 它从适配器读取了这个计划——有一个真理的来源.
const engine = new GenQueryEngine({ adapter }); // schema comes from the adapter
// parse + apply + execute → Promise<{ data, current?, total? }>
await engine.run(input, rootEntity, target);
// parse only (requires explicit rootEntity)
const parsed = engine.parse(input, rootEntity);
// apply a previously parsed query without executing (returns the raw args object)
engine.runParsed(parsed, target);
政策(贷款清单)
默认情况下,每个字段/关系 已存在 在计划内是可查询的。 一项政策
限制每个实体的表面,所以前端可以读取一个字段,但不能过滤/排序它,
不包括昂贵的关系,或者不过度牵强一页。 由解析器执行
(掷出) QueryValidationError(三); maxPerPage 实值 夹住而不是拒绝.
截至0.14.0, 拒绝为 select 被剥去 默认 选择 :
未明确查询 select (即说. select: "all")得到一个Prisma omit 会 议 日 程 和 议 程
拒绝的字段,在根源和内部包括关系——拒绝/保密字段从不
回来,即使没有请教, 而其他的一栏(包括其中的一栏)
不做模特,喜欢 Json 或 scalar 数组)保留了 Prisma 的默认选择.
低级别: 计划上的可选旗帜( )filterable 编号 : sortable 编号 : selectable 在球场上,
includable 编号 : filterable 关于关系, maxPerPage ——所有默认允许.
Ergonomic:按名称声明许可列表,并投影到 applyPolicy (ORM-不可知论)或
页:1 policy 选项 schemaFromPrisma。 。 。 .
import { applyPolicy } from "@generazioneai/genquery";
const restricted = applyPolicy(schema, {
User: {
filterable: ["name", "email"], // only these allowed in searchBy
sortable: ["createdAt"], // only this in orderBy
includable: ["posts"], // only this relation in include
maxPerPage: 100, // perPage > 100 is clamped to 100
},
});
// per axis: array omitted = unrestricted · present = only-listed · empty = none
// Prisma: build + restrict in one call
const schema = schemaFromPrisma(Prisma.dmmf.datamodel, {
policy: { User: { filterable: ["name"], includable: ["posts"], maxPerPage: 100 } },
});
错误
分析失败 QueryValidationError 带有 path 字段指输入中的违法地点(例如:. "searchBy.posts.title.value") (中文(简体) ).
import { QueryValidationError } from "@generazioneai/genquery";
try {
await engine.run(input, "User", prisma.user);
} catch (e) {
if (e instanceof QueryValidationError) {
console.error(e.path, e.message);
}
}
实例
见 文件/实例.md 用于完整实例:
- 字符串搜索模式( splitword, 精确 -)
nativeregex被 Prisma 适配器拒绝) - 日期范围
- 数字比较
- 或条件
- 关系过滤和纳入
- 接地和排序
限制和秘密(0.15、0.15.1、0.16)
每个限制都有两种模式, GENQUERY_LIMIT_MODE=log|enforce (默认) log: log 措施和日志
(单位:千美元)wouldCap 编号 : wouldReject而不改变任何东西; enforce 切或拒绝。 秘诀是例外:
在两种模式中关闭.
| 设置 | 默认 | 影响于 enforce |
|---|---|---|
limits.maxRows 编号 : GENQUERY_MAX_ROWS | 联合国 | pagination: "all" (没有帕吉宁)得到 take: cap+1; 结果切为 cap 并携带 truncated: true |
entityMaxRows 编号 : EntityDefinition.maxRows 编号 : EntityPolicy.maxRows | —— 说 | 每实体上限; null = 明确“无盖”例外 |
limits.maxDepth 编号 : GENQUERY_MAX_DEPTH | 3个 | 包含或巢接关系过滤器比 NHP 更深 : QueryValidationError |
limits.maxFilterDepth 编号 : GENQUERY_MAX_FILTER_DEPTH (0.16) (中文(简体) ) | maxDepth | 嵌入式关系过滤器的深度searchBy仅限 filterDepth 活动(wouldReject 内 log) (中文(简体) ). 包含深度保留在 maxDepth |
limits.toManyAfterToOne | true | 不包括在一对一之后(规则从 SKILLHR-BE 的 包括- 选择的后卫) |
limits.sharedRoots | [] | 根实体中,没有多个包含(全球/共享行) |
limits.includablePaths 编号 : EntityPolicy.includablePaths 编号 : buildGenQueryPolicy({ includablePaths }) 联合国 | —— 说 | 每根,被嵌入的路径包括允许的路径(见下文) |
limits.onEvent | console.warn 贾森 | 用于事件( e)rowCap, (中文(简体) ), depth, (中文(简体) ), filterDepth, (中文(简体) ), toManyAfterToOne, (中文(简体) ), includablePath, (中文(简体) ), baseIncludeDropped, (中文(简体) ), includeMergeConflict(中文(简体) ) |
new PrismaAdapter(schema, { limits: { mode: "enforce", maxRows: 2000, sharedRoots: ["AbsenceType"] } });
巢穴包括: includablePaths 联合国
结构 toManyAfterToOne 规则拒绝合法包括:
JuridicalIndividual → individual (to-one) → individualDatas (to-many)。根可以声明嵌入路径
它允许; 包括巢穴在内,只允许申报数字 :
const includablePaths = { JuridicalIndividual: ["individual.individualDatas", "juridical.juridicalDatas"] };
new PrismaAdapter(schema, { limits: { mode: "enforce", includablePaths } });
// or in the policy: buildGenQueryPolicy({ datamodel, includablePaths }) / EntityPolicy.includablePaths
- (单位:千美元) 一级 包括(从根部跳出一跳)继续受政策支配(
includable和以前一样; - (单位:千美元) 筑巢 路径( r)
rel.rel[.rel…]如果已声明或已宣布路径的前缀,则允许使用; - 用于声明根
includablePaths,任何其他被窝住的道路都是违反的(includablePath事件:wouldReject内log, (中文(简体) ),QueryValidationError内enforce结构规则否 长期适用于该根; - b. 无保留结构规则的根(兼容性);
maxDepth永远适用,而且sharedRoots仍然禁止任何人,无论是否公开;- 适配器选项胜过每个根的策略/政策;无效路径(未知的根或关系)使
PrismaAdapter构造器投掷SchemaError。 。 。 .validateIncludablePaths(schema, paths)返回问题, 用于后端测试.
服务器端包括: includeMerge (0.16) (中文(简体) )
baseArgs.include (信任,服务设置)只在客户端不发送时才适用 include 也没有
select否则就静静地扔了. PrismaAdapterOptions.includeMerge 编号 : GENQUERY_INCLUDE_MERGE数字 :
| 数值 | 行为 |
|---|---|
log (默认) | 如在0.16之前,加上a baseIncludeDropped 活动(entity, (中文(简体) ), key, (中文(简体) ), reason: clientInclude|clientSelect每丢入的服务密钥 |
replace | 无事件 |
merge | 递归合并,服务从不扩大 |
merge 规则:(1) 服务具有 select,或参数(where, (中文(简体) ), orderBy, (中文(简体) ), take,.)在键上,服务
赢:客户端 true 既不宽放,也不移除其论据(客户端嵌入) include 添加到
服务参数; 服务 omit (2) 只添加客户端密钥( 已被 parser 验证)
(三) 客户 select 在根位下,服务与以前一样(活动) select + 键 include
从未在同一级别(在他们与服务发生冲突的密钥上)排放 include 胜利, 事件
includeMergeConflict) (中文(简体) ). mergeIncludes(service, client) 用于输出和纯度.
genquery-check (0.16) (中文(简体) )
重播真实的CLI parseQuery + 键 checkQueryShape (和你的极限) include 编号 : searchBy 字节
在源代码中发现,所以一个限制变化或一个计划变化会打破CI而不是生产.
# 1. manifest: entities, relations with cardinality, policy flags, limits
genquery-check manifest --schema prisma/schema.prisma [--limits genquery.limits.js] --out genquery.manifest.json
# 2. TypeScript: literals passed to engine.run/parse, .send(...), rpcCall(...)
genquery-check --lang ts --manifest genquery.manifest.json [--routes routes.json] [--fail-on error|warn|never] src/
# 3. Dart: `include: {…}`, `searchBy:`/`searchParams:` maps and table filter keys `a:b:c`
genquery-check --lang dart --manifest genquery.manifest.json --routes routes.json lib/
--schema数字 :schema.prisma或DMMF JSON({datamodel}编号 :{models, enums}) (中文(简体) ).--limitsJSON或联署材料模块maxDepth, (中文(简体) ),maxFilterDepth, (中文(简体) ),toManyAfterToOne, (中文(简体) ),sharedRoots, (中文(简体) ),includablePaths, (中文(简体) ),policy(单位:千美元)EntityPolicy百分比 实体,extraSecretFields, (中文(简体) ),allowSecretFields。 。 。 .--manifest可能是一个文件或一个http(s)URL (中文(简体) ).--routes贾森{ "<route or cmd>": "<RootEntity>" }(数值可能是:{ "root": … },网关的形状 从 OpenAPI 导出x-genquery-root) (中文(简体) ). 需要知道一个 Dart 字节的根( 连接到最近的apiUrl:) 和.send({cmd}, …)编号 :rpcCall有效载荷;engine.run(q, "Root", …)带着它自己的根.- 表格密钥
a:b:c被检查为搜索{a:{b:{c:…}}}对根--routes(每个实体何时) 如果有任何候选人接受,他们就会通过. - 产出
file:line: error|warn: message。错误:未知的字段或关系,不包含、深度、多规则, 未申报includablePaths。警告:动态部件(扩展、计算出密钥、在include, (中文(简体) ), 未解决的根 。 动态 数值 内部searchBy不是警告(数值类型与形状无关). --fail-on error|warn|never(默认)error:退出代码1只针对出错 / 也针对警告 / 永远(仅针对注释). 用法错误: 2.- 类型脚本模式需要
typescript软件包(可选的对等依赖)。 达特提取器是宽容的 用 TypeScript (无 Dart 分析器) 编写的扫描仪: 它读取了地图文字,而不是 Dart 语义.
baseArgs (信任的,服务器侧)不检查 . DEFAULT_SECRET_FIELDS + 键 DEFAULT_SECRET_PATTERNS
(单位:千美元)otp*, (中文(简体) ), secret*, (中文(简体) ), *Encrypted, (中文(简体) ), *Enc永远无法选择、过滤或排序和 applyPolicy 无法
重新开放; schemaFromPrisma 带 extraSecretFields 和每个模型 allowSecretFields 除外.
浏览器和 Next.js 客户端 : @generazioneai/genquery/client (0.17) (中文(简体) )
给谁 电话 a 流派终点。 零依赖性,节点API,无害环境管理+CJS+类型. 没有
发动机被拉入。 电线编码是达特客户端之一 skillera_ui
(单位:千美元)GenQuery.build + 键 ApiManager.asQueryParams),这是什么 createGenQueryDecorator({ from: 'query' })
联 合 国 genquery-nestjs 回读 : pagination 原始为 all编号 :first 还有JSON, searchBy, (中文(简体) ), orderBy
(单位:千美元){field, direction, order}, (中文(简体) ), include, (中文(简体) ), select 如JSON,空的则省去.
import { gq, toQueryParam, type GenQueryInput } from "@generazioneai/genquery/client";
const q = gq<Presence>()
.where({ structureId: "s1" })
.or({ attendanceStatus: "PENDING" }, { attendanceStatus: "APPROVED" }) // OR in AND with the rest
.include({ structure: "all", individual: { individualDatas: true } })
.orderBy("createdAt", "desc")
.page(1, 20); // 1-based; on the wire it is {"page":0,"perPage":20}
q.toQueryParam(); // { pagination: '{"page":0,"perPage":20}', searchBy: '{...}', orderBy: '...', include: '...' }
q.toQueryString(); // "pagination=%7B...&searchBy=..." (encodeURIComponent, like Dart)
q.toSearchParams(); // URLSearchParams
q.url("/api/hr/presences"); // "/api/hr/presences?pagination=..."
构建器是不可改变的(每一种方法都返回一个新的方法:在React状态中安全并作为缓存键). build() 给
简单 GenQueryInput· ; toQueryParam(input) 编码一个你已经有了. gq<T>() 类型 where编号 :include编号 :select
反对实体类型, gq() 保持松动.
下一个.js
// app/presenze/page.tsx (Server Component)
import { gq } from "@generazioneai/genquery/client";
export default async function Page({ searchParams }: { searchParams: Promise<{ q?: string; p?: string }> }) {
const { q, p } = await searchParams;
const query = gq<Presence>()
.filters({ "individual:individualDatas:firstName|individual:individualDatas:lastName": q }) // empty → ignored
.orderBy("checkInAt", "desc")
.page(Number(p) || 1, 25);
const res = await fetch(query.url(`${process.env.API_URL}/hr/presences`), { cache: "no-store" });
return <List data={await res.json()} />;
}
在包含 SWR/React 查询的客户端组件中,密钥是 query.toQueryString(); 与 fetch 使用情况 query.url(base)。 。 。 .
表格过滤器filters, (中文(简体) ), searchByFromFilters(中文(简体) )
平键 skillera_ui 表格变成嵌入式 searchBy数字 : 'a:b:c' 窝, 'x|y' 是一个横跨列的 OR
(单位:千美元)'a:x|a:y' 取出常见的前缀,值被密钥所包裹(文本 ~) {value, contained: true}, (中文(简体) ), id编号 :…Id…
现在, …Ids 和阵列 {in}, (中文(简体) ), fullName 无空格; null 财务报告和审定财务报表 "" 被跳过). buildQueryParams 这是
字端口数 GenQuery.build编号 :buildFromRaw编号 :findOne (基于1种) page, (中文(简体) ), pivot, (中文(简体) ), orderByParams 与 {columnId, mode}) (中文(简体) ).
有意保持已知差异:达特 DateTimeRange 编码为 {gte, lte},引擎拒绝的日期.
searchByFromFilters 复制它({ start, end } → {gte, lte}),所以两个客户端保持不变;在新代码中
过滤日期为 { after, before } 结束 where()。 。 。 .
与达特等同
src/tests/fixtures/dart-equivalence.json 案件(从 skillera_hr 财务报告和审定财务报表 skillera_ops)与输出
由真实的 Dart 代码制作;测试按字符串比较字符串,然后将结果反馈给真实的解析器.
更改为 skillera_ui数字 : scripts/dart-equivalence/run.sh <skillera_ui dir> [dart]。 。 。 .
(JSON数字像 1.0 打印为 1 《联合提交的材料》和 1.0 在达特:在过滤器中避开它们。)
建筑
三层,严格分离:
Wire types (types.ts)
└─ Parser validates + normalizes → Parsed types (parsed.ts)
└─ Adapter consumes ParsedQuery + Schema → ORM output
适配器从不见有线型. 新适配器已执行 Adapter<TTarget, TResult> (从包根再出).
见 文件/海关适应器 给指示.
文档
| 文件 | 目录 |
|---|---|
| 文档/开始 | 安装、 设置、 第一个查询 |
| 文献/查询 | 完整查询语言参考 |
| 文献/主编 | Prisma 适配器选项和内部 |
| 文件/海关适应器 | 构建自定义适配器 |
| 文件/实例.md | 端到端实例 |
| 光谱md | 真实源线格式光谱 |