JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q43471F
  • License Apache-2.0

Generate Drizzle schema from Prisma schema

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@metamorph/drizzle-prisma-generator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    Drizzle Prisma Generator

    Automatically generate Drizzle schema from Prisma schema

    Usage

    • Install generator: pnpm add -D drizzle-prisma-generator
    • Add generator to prisma:
    generator drizzle {
      provider = "drizzle-prisma-generator"
      output   = "./src/schema.ts"
      imports  = "./drizzleSchemaUtils.ts"
    
      // convert to Kysely types
      file1             = "./kyselyDatabase.ts"
      template1         = "import { Kyselify } from 'drizzle-orm/kysely'\n\n{{imports}}\n\nexport interface Database {\n{{content}}\n}"
      template1_content = "\t{{tableName}}: Kyselify<typeof {{modelName}}>"
    
      // convert to Zod types
      file2                           = "./drizzleZodSchemas.ts"
      // file layout template which receives typeMapImports and content
      template2                       = "import { createInsertSchema, createSelectSchema } from 'drizzle-zod'\n\n{{imports}}\nimport {\n{{typeMapImports}}} from './drizzleSchemaUtils'\n\n{{content}}"
      // mapping for each imported type (using @type(imports.<type>))
      template2_typeMapImports        = "\t{{fieldType}}DataSchema,\n"
      // file content template
      template2_content               = "export const {{modelName|camelCase}}Schema = createSelectSchema({{modelName}}){{importedTypesContent}}\nexport const {{modelName|camelCase}}InsertSchema = createInsertSchema({{modelName}}){{importedTypesContent}}\n"
      // content for all imported types which receives importedTypesMap
      template2_importedTypesContent  = ".extend({\n{{importedTypesMap}}})"
      // mapping for each imported type (using @type(imports.<type>))
      // receives all field data (name, type, isRequired, ...)
      template2_importedTypesMap      = "  {{name}}: {{type}}DataSchema{{|if(isRequired)?:.nullable()}},\n"
    }

    ⚠️ - if output doesn't end with .ts, it will be treated like a folder, and schema will be generated to schema.ts inside of it.
    ⚠️ - binary types in MySQL, PostgreSQL are not yet supported by drizzle-orm, therefore will throw an error.
    ⚠️ - generator only supports postgresql, mysql, sqlite data providers, others will throw an error.

    • Install drizzle-orm: pnpm add drizzle-orm
    • Import schema from specified output file\folder
    • Congratulations, now you can use Drizzle ORM with generated schemas!

    Using any types (improved for pg only)

    Use documentation with @type, @tsType and @.<anyDrizzleFieldMethod>(...)

    model Warehouse {
      /// @type(geometry, { type: 'point', srid: 4326 })
      /// @tsType(SomeNamespace.SomeType)
      coordinates Json @default([123, 123])
      /// @type(imports.polygon, { srid: 4326 })
      polygon     Json?
      name        String @db.VarChar(50)
      /// @type(tsvector)
      /// @.generatedAlwaysAs(sql`prepare_search_field(name)`)
      fts          String
      deletedAt    DateTime? @db.Timestamptz(6)
    
      /// @.where(sql`"deletedAt" IS NULL`)
      @@unique([coordinates, name], name: "some_idx")
      @@map("warehouses")
    }

    converts to:

    import * as imports from './drizzleSchemaUtils';
    
    export const Warehouse = pgTable(
      'warehouses',
      {
        coordinates: geometry({ type: 'point', srid: 4326 })
          .$type<SomeNamespace.SomeType>()
          .notNull()
          .default([123, 123]),
        polygon: imports.polygon({ srid: 4326 }),
        name: varchar({ length: 50 }).notNull(),
        fts: tsvector()
          .generatedAlwaysAs(sql`prepare_search_field(name)`)
          .notNull(),
        deletedAt: timestamp({ mode: 'date', withTimezone: true, precision: 6 }),
      },
      (Warehouse) => ({
        some_idx: uniqueIndex('some_idx')
          .on(Warehouse.coordinates, Warehouse.name)
          .where(sql`"deletedAt" IS NULL`),
      })
    );

    Generated files:

    ./kyselyDatabase.ts:

    // generated by drizzle-prisma-generator
    import { Kyselify } from 'drizzle-orm/kysely';
    
    import { Warehouse } from './drizzleSchema';
    
    export interface Database {
      warehouses: Kyselify<typeof Warehouse>;
    }

    ./drizzleZodSchemas.ts:

    // generated by drizzle-prisma-generator
    import { createInsertSchema, createSelectSchema } from 'drizzle-zod';
    
    import { Warehouse } from './drizzleSchema';
    import { polygonDataSchema } from './drizzleSchemaUtils';
    
    export const warehouseSchema = createSelectSchema(Warehouse).extend({
      polygon: polygonDataSchema.nullable(),
    });
    export const warehouseInsertSchema = createInsertSchema(Warehouse).extend({
      polygon: polygonDataSchema.nullable(),
    });

    Imports file example:

    ./drizzleSchemaUtils.ts:

    import { customType } from 'drizzle-orm/pg-core';
    import { z } from 'zod';
    
    export const polygonDataSchema = z.array(z.tuple([z.number(), z.number()]));
    export type PolygonData = z.infer<typeof polygonDataSchema>;
    
    export const polygon = customType<{ data: PolygonData; driverData: string }>({
      dataType() {
        return 'geometry(polygon)';
      },
    });