drizzle-team / drizzle-team/drizzle-orm
[FEATURE]: Add a way to have common refinements for create/insert/patch schema
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Feature hasn't been suggested before.
- [x] I have verified this feature I'm about to request hasn't been suggested before.
### Describe the enhancement you want to request
I'm creating a drizzle table, then I want to use `createSelectSchema/insertSelectSchema/...` but I want those to have common parsing rules (eg typically when using hono/zod-openapi, I want them to have common openapi descriptions, but also perhaps parsing rules, like parsing a string as an email both in create and select schema)
For now I found this hack but there's probably a much better way to do it?
https://stackblitz.com/edit/vitejs-vite-f4i5pqmt?file=schema.ts
```ts
import { z } from '@hono/zod-openapi';
import type { ZodTypeAny } from 'zod/v4';
import { text, pgSchema } from 'drizzle-orm/pg-core';
import {
createInsertSchema,
createSelectSchema,
createUpdateSchema,
} from 'drizzle-zod';
export const myTable = pgSchema('myschema').table('my-table', {
id: text('id').primaryKey(),
tag: text('tag'),
});
// Utility function to create refinements with better type inference
function createRefinements>(
_table: T,
refinements: Partial<{ [K in keyof T]: (schema: T[K]) => T[K] }>
): Partial<{ [K in keyof T]: (schema: ZodTypeAny) => ZodTypeAny }> {
return refinements as Partial<{
[K in keyof T]: (schema: ZodTypeAny) => ZodTypeAny;
}>;
}
// shared refinments for all the createInsert / createSelect / createUpdate
const myRefinements = createRefinements(createSelectSchema(myTable).shape, {
id: (schema) =>
schema.openapi({
description: 'Unique identifier',
}),
tag: (schema) =>
schema.openapi({
description: 'Item tag',
}),
});
export const selectItemsSchema = createSelectSchema(myTable, myRefinements);
export const insertItemSchema = createInsertSchema(myTable, myRefinements).omit(
{
id: true,
}
);
export const patchItemSchema = createUpdateSchema(myTable, myRefinements).omit({
id: true,
});
export type Item = z.infer;
export type NewItem = z.infer;
export type PatchItem = z.infer;
```
Contributor guide
Assessment
This issue has not been assessed yet.