drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.68k stars 651 forks source link

[FEATURE]: Integrate Valibot, Zod and Typebox into custom type definition and JSON column types #3565

Open L-Mario564 opened 1 week ago

L-Mario564 commented 1 week ago

Feature hasn't been suggested before.

Describe the enhancement you want to request

The validator libraries are easy to integrate with the types that Drizzle has first-party support for.

varchar({ length: 50 }); /* ---> */ z.string(50);

However, a limitation of these libraries is that there's basically no support for custom types and limited support for JSON column types.

myCustomVarchar({ length: 50 });  /* ---> */ z.any();

json(); /* ---> */ jsonSchema; // Correct, since the JSON column has no shape defined
json().$type<{ prop: string }>(); /* ---> */ jsonSchema; // Incorrect, this schema doesn't respect the shape defined in the `$type` method

The enhancement

Let developers define the shape of custom types and JSON columns using validators (Zod, Valibot, Typebox).

const customTextSchema = z.string();
// No need to pass `{ data: string }` since the data type is inferred from the schema passed as the first param
// The schema won't be used at runtime to avoid mixing validator APIs with Drizzle's
const customText = customType.inferTypeFromSchema(customTextSchema, {
  dataType() {
    return 'text';
  },
};

const customJSONSchema = z.object({ prop: z.string() });
// No need to specify `$type` method
const customJSON = json().$inferTypeFromSchema(customJSONSchema);

// The results after passing the to `createSelectSchema` and `createInsertSchema`
customTextColumn;  /* ---> */ z.string();
customJSON; /* ---> */ z.object({ prop: z.string() });