#Drizzle 集成

已经用 Drizzle 管理 schema 的项目,可以直接把 drizzle table 和 db 交给 oor,获得同一套魔法后缀查询 API。不需要 Zod。

TypeScript
import { TABLE, VIEW } from 'oor/drizzle/pg'
import { TABLE, VIEW, setGlobalConfig } from 'oor/drizzle/sqlite'

drizzle-orm 是可选 peer 依赖,使用本入口前请自行安装。

#基本用法

TypeScript
import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core'
import { drizzle } from 'drizzle-orm/node-postgres'
import { TABLE } from 'oor/drizzle/pg'

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  age: integer('age').notNull()
})

const db = drizzle(pool)

// 实体类型自动从 drizzle table 的 $inferSelect 推导
const User = TABLE(users, db, {
  queryFields: ['id', 'name'],
  detailFields: ['id', 'name', 'age']
})

const list = await User.query({
  ageGte: 18,
  _pagition: { page: 1, size: 20, order: 'age', by: 'desc' }
})

db 也可以传工厂函数:TABLE(users, () => db, options)。

#SQLite

TypeScript
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'
import { TABLE } from 'oor/drizzle/sqlite'

const users = sqliteTable('users', { /* ... */ })
const User = TABLE(users, db, options)

API 与 pg 完全一致。

#配置

options 就是定义与 Schema 中的 TableOptions:queryFields / detailFields / where / defaultSort / deleteField / deleteValue 以及全局配置项。

不需要 columns 和 rowKey:列信息直接取自 drizzle table 定义,主键从 drizzle 的 primaryKey 推断。

#与其他入口的默认值差异

  • Drizzle 入口默认 strictEntity: false(native / SQL 构建器默认 true);
  • 未配置 deleteField 却传了 deleteValue 之类的错误配置会在建表时直接报错。

#setGlobalConfig:进程级默认值

TypeScript
import { setGlobalConfig } from 'oor/drizzle/pg'

setGlobalConfig({ pageSize: 20, maxPageSize: 200, strictQuery: true })

影响之后创建的所有 TABLE / VIEW;单表的 options 优先级更高。

#相关