Drizzle ORM

website·Indexed 31 days ago

https://drizzle.docsforall.com

A modern, lightweight TypeScript ORM (~7.4kb minified+gzipped) providing a SQL-like syntax for data querying and CRUD operations. It supports a wide range of database connections including PostgreSQL (Neon, Vercel, Supabase, Prisma, PlanetScale), MySQL (PlanetScale, AWS Data API), and SQLite (Cloudflare D1, Turso, Bun, Expo, PGlite). Features include custom type definitions, explicit caching, and a plugin ecosystem including drizzle-arktype.

Tokens
121.7K
Snippets
748
Records
809
Agent score
45%

What's inside Drizzle

  1. Overview of Drizzle ORM

    Drizzle is a modern, lightweight TypeScript ORM (~7.4kb minified+gzipped) designed to be tree-shakeable with zero dependencies. It is serverless-ready and provides support for PostgreSQL, MySQL, SQLite, and SingleStore databases.
  2. Perform Database Introspection with Drizzle Kit

    Drizzle Kit provides CLI commands to introspect an existing database. This process analyzes the database and automatically generates schema files containing information about tables, columns, relationships, and indexes, which can then be used for migrations.
  3. Understand Drizzle ORM migration strategies

    Drizzle ORM supports both 'Database-First' and 'Codebase-First' approaches for managing database schemas.

    • Database-First: The database schema is the source of truth. You manage the schema directly in the database or via external tools, then import that schema into your TypeScript code.
    • Codebase-First: The TypeScript schema definition is the source of truth and is version-controlled. You define the schema in code and apply changes to the database using Drizzle tools.
  4. Integrate Drizzle ORM with Effect Postgres

    Drizzle ORM provides native support for Effect PostgreSQL connections via the @effect/sql-pg driver. This integration requires Drizzle version 1.0.0-beta.9 or higher. Currently, this Effect support is only available for PostgreSQL.
  5. Generate fake data with drizzle-seed

    drizzle-seed is a TypeScript library that generates deterministic, realistic fake data to populate databases. It uses a pseudo-random number generator (pRNG) to ensure that the same seed value produces the same data sequence, making it ideal for testing, debugging, and collaboration across teams.

    Requirement: drizzle-seed requires drizzle-orm@0.36.4 or higher to avoid type issues and identity column problems.

  6. Generate Valibot schemas using drizzle-valibot

    The drizzle-valibot plugin allows developers to create Valibot validation schemas directly from Drizzle ORM schemas. It provides three primary functions: createSelectSchema for API response validation, createInsertSchema for request body validation, and createUpdateSchema for update request validation. It supports tables, views, and enums.
    npm install drizzle-valibot
  7. Manage database migrations with Drizzle Kit

    Drizzle Kit is a CLI tool used to manage SQL database migrations. It allows developers to generate migration files based on schema definitions, apply them to the database, push schemas directly, and introspect existing databases.
    npm install -D drizzle-kit
  8. Set up Drizzle ORM with Netlify Edge Functions and Neon Postgres

    To integrate Drizzle ORM with Netlify Edge Functions and Neon Postgres, follow these setup steps:

    1. Install Dependencies: Install drizzle-orm, drizzle-kit, and dotenv (if Node.js < v20.6.0).
    2. Environment Variables: Add your Neon connection string to .env as DATABASE_URL.
    3. Import Map: Create import_map.json to map Drizzle and Neon serverless packages for the Deno runtime used by Edge Functions.
    4. Netlify Config: Configure netlify.toml to use the import map and route requests to your edge functions.
    5. Schema Definition: Define your database tables using pgTable from drizzle-orm/pg-core.
    // import_map.json
    {
      "imports": {
        "drizzle-orm/": "https://esm.sh/drizzle-orm/",
        "@neondatabase/serverless": "https://esm.sh/@neondatabase/serverless"
      }
    }
    # netlify.toml
    [functions]
      deno_import_map = "./import_map.json"
    
    [[edge_functions]]
      path = "/user"
      function = "user"
  9. Integrate Drizzle ORM with Supabase in an existing project

    To integrate Drizzle ORM with an existing Supabase project, follow these steps: 1. Install the postgres package. 2. Set the DATABASE_URL environment variable. 3. Configure the Drizzle setup file using the postgresql dialect. 4. Perform database introspection to pull existing schemas. 5. Transfer the introspected code to actual schema files. 6. Connect Drizzle ORM to the Supabase database. 7. Execute database queries using the postgres-js dialect. 8. Run the index.ts file using tsx. Optionally, update the table schema and apply changes to the database.
  10. Integrate Drizzle ORM with Effect PostgreSQL

    To use Drizzle with the Effect ecosystem and PostgreSQL, use the drizzle-orm/effect-postgres package. You must set up a PgClient layer from @effect/sql-pg and pass that client to the drizzle function. This requires Drizzle version 1.0.0-beta.9 or higher.
    import 'dotenv/config';
    import { drizzle } from 'drizzle-orm/effect-postgres';
    import { Effect, Redacted } from 'effect';
    import { PgClient } from '@effect/sql-pg'
    import { types } from 'pg';
    import { usersTable } from './db/schema'
    
    const clientLayer = PgClient.layer({
        url: Redacted.make(process.env.DATABASE_URL!),
        types: {
            getTypeParser: (typeId, format) => {
                if ([1184, 1114, 1082, 1186, 1231, 1115, 1185, 1187, 1182].includes(typeId)) return (val: any) => val;
                return types.getTypeParser(typeId, format);
            },
        },
    });
    
    const program = Effect.gen(function*() {
    	const client = yield* PgClient.PgClient;
    	const db = drizzle(client, { logger: true });
    
    	const user: typeof usersTable.$inferInsert = {
            name: 'John',
            age: 30,
            email: 'john@example.com',
        };
    
    	yield* db.insert(usersTable).values(user);
        console.log('New user created!')
    });
  11. Install Drizzle ORM for Supabase

    To use Drizzle ORM with Supabase, install the Drizzle ORM core, the postgres driver, and the Drizzle Kit CLI for migrations and schema management.
    npm install drizzle-orm postgres
    npm install -D drizzle-kit