Skip to content

[BUG]: incorrect drizzle-zod schema types if Drizzle schema uses branded types #4883

@fr33bits

Description

@fr33bits

Report hasn't been filed before.

  • I have verified that the bug I'm about to report hasn't been filed before.

What version of drizzle-orm are you using?

0.44.5

What version of drizzle-kit are you using?

0.31.4

Other packages

[email protected]

Describe the Bug

If one uses branded types in a Drizzle schema, drizzle-zod creates an incorrect schema (be it select, insert or update) for that type, which also leads to that schema outputting data of an incorrect type.

For example my attempt at creating a UserId branded type resulted in createSelectSchema(userTable) outputting a schema that had the following type for the (user) id:

id: z.ZodObject<{
      toString: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      toFixed: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      toExponential: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      toPrecision: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      valueOf: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      toLocaleString: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
      __brand: z.ZodString;
  }, {
      out: {};
      in: {};
  }>;

The data type of the user id then ends up being;

{
    toString: unknown;
    toFixed: unknown;
    toExponential: unknown;
    toPrecision: unknown;
    valueOf: unknown;
    toLocaleString: unknown;
    __brand: string;
}

Others have reported similar issues with drizzle-zod and branded types (see here and here).

Zod itself also supports branded types however they do branding their own way, so not with __brand like most people do it, so for now it doesn't seem like the Drizzle schema branded type specification can be made compatible with that of Zod and the only way to achieve both would be through drizzle-zod schema refinements.

This closed issue from last year suggests that this is indeed how branded types should be handled but the problem with that is that it will not properly type the results the database returns, which will first need to be parsed by Zod to obtain the correct types, which increases the amount of code required to achieve the same types. Not to mention that regular and Drizzle branded types are not really compatible with those Zod creates.

So to fix this, drizzle-zod needs to ignore branded type data when creating schemas, I think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions