Drizzle ORM Documentation

repository·main·Indexed 42 days ago

https://github.com/drizzle-team/drizzle-orm-docs

Documentation for Drizzle ORM, featuring guides on schema generation with Arktype, CockroachDB column types (including identity columns, geometry, and vectors), and caching strategies using Upstash CacheConfig.

Tokens
234.1K
Snippets
808
Records
962
Agent score
50%

What's inside Drizzle ORM

  1. Overview of Drizzle ORM

    main

    Drizzle ORM is a headless, lightweight, and typesafe TypeScript data framework designed to be serverless-ready. Unlike traditional 'data frameworks' that require you to build your project around them, Drizzle is a library that integrates into your existing structure without interference.

    Key features include:

    • Dual Query APIs: Provides both a SQL-like API for direct control and a Relational Queries API (RQB) for convenient nested data fetching.
    • Zero Dependencies: Extremely slim and performant, making it ideal for serverless environments.
    • Dialect Support: Native support for major database drivers including PostgreSQL, MySQL, SQLite, and SingleStore.
    • Type Safety: Full TypeScript support for schema definitions and queries.
  2. What is Drizzle ORM?

    main

    Drizzle ORM is a headless TypeScript ORM designed to be lightweight, performant, and serverless-ready. Unlike traditional 'data frameworks' that require you to build your project around them, Drizzle is a library that lets you manage database schemas in TypeScript and access data using two distinct patterns: a SQL-like API and a relational Queries API.

    Key characteristics:

    • Zero dependencies: It is slim and has no external dependencies.
    • Dialect-specific: Provides best-in-class support for various SQL dialects.
    • Dual Query APIs: Offers both SQL-like syntax and a high-level relational API.
    • Serverless-ready: Designed to work efficiently with serverless database drivers and minimize roundtrip costs.
  3. Overview of Drizzle Studio flavors

    main

    Drizzle Studio is a modern web-based database browser used to browse, edit, and manage database data and schemas. It is available in five distinct flavors depending on your use case:

    • Local Studio: Free. Run via drizzle-kit studio in your local Drizzle project for development.
    • Drizzle Gateway: Free. A self-hosted version deployed as a Docker container or binary for infrastructure/teams.
    • Chrome Extension: Free. Browses serverless databases (like PlanetScale, Cloudflare D1, and Vercel Postgres) directly within vendor consoles.
    • Studio Component: B2B offering. An embeddable version for your own products.
    • Desktop App: Coming soon. A native database browser.
  4. Drizzle ORM is serverless-ready and dependency-free

    main

    Drizzle is designed for modern serverless architectures. Key characteristics include:

    • Zero dependencies: Drizzle has exactly 0 dependencies, keeping your bundle size minimal.
    • Dialect-specific: It provides best-in-class support for specific SQL dialects.
    • Driver-native: It operates through industry-standard database drivers rather than heavy abstractions.
    • Supported Databases: Full support for PostgreSQL, MySQL, and SQLite.
  5. Understand the project structure

    main

    The documentation content is organized into specific directories within the src/ folder:

    • Documentation (MDX): Located in src/content/docs.
    • Announcements: Markdown files are stored in src/data/announcements.
    • Roadmap: The roadmap is defined in src/data/roadmap.md.
    • Shipping Data: Shipping information is managed via a YAML file at src/data/shipping.yaml.
  6. Project structure for Todo App with Neon Postgres

    main

    The following directory structure is used in this tutorial for a Next.js application integrated with Drizzle ORM and Neon Postgres:

    • migrations/: SQL migration files.
    • src/actions/: Server actions (e.g., todoActions.ts).
    • src/app/: Next.js App Router files (page.tsx, layout.tsx).
    • src/components/: UI components (addTodo.tsx, todo.tsx, todos.tsx).
    • src/db/: Database configuration (drizzle.ts, schema.ts).
    • src/types/: TypeScript type definitions (todoType.ts).
    • drizzle.config.ts: Drizzle ORM configuration file.
    • .env: Environment variables (e.g., database connection string).
    📦 <project root>
     ├ 📂 migrations
     │  ├ 📂 meta
     │  └ 📜 0000_heavy_doctor_doom.sql
     ├ 📂 public
     ├ 📂 src
     │  ├ 📂 actions
     │  │  └ 📜 todoActions.ts
     │  ├ 📂 app
     │  │  ├ 📜 favicon.ico
     │  │  ├ 📜 globals.css
     │  │  ├ 📜 layout.tsx
     │  │  └ 📜 page.tsx
     │  ├ 📂 components
     │  │  ├ 📜 addTodo.tsx
     │  │  ├ 📜 todo.tsx
     │  │  └ 📜 todos.tsx
     │  ├ 📂 db
     │  │  ├ 📜 drizzle.ts
     │  │  └ 📜 schema.ts
     │  └ 📂 types
     │     └ 📜 todoType.ts
     ├ 📜 .env
     ├ 📜 .eslintrc.json
     ├ 📜 .gitignore
     ├ 📜 drizzle.config.ts
     ├ 📜 next-env.d.ts
     ├ 📜 next.config.mjs
     ├ 📜 package-lock.json
     ├ 📜 package.json
     ├ 📜 postcss.config.mjs
     ├ 📜 README.md
     ├ 📜 tailwind.config.ts
     └ 📜 tsconfig.json
  7. What is the Drizzle Studio Component?

    main

    The Drizzle Studio Component is a paid B2B offering consisting of a pre-bundled, framework-agnostic, and secure web component. It is designed to be embedded directly into your own UI (supporting React, Vue, Svelte, VanillaJS, etc.).

    It is intended for:

    • Database-as-a-Service (DBaaS) providers looking to provide a built-in UI.
    • Data-centric SaaS solutions based on SQL.
    • Private in-house usage for internal data management.

    Key features include:

    • High Customizability: Access to an advanced theming platform to match your brand colors.
    • SQL Query Runner: An opt-in feature for executing queries.
    • Partner Customizations: Specific features can be added on demand.
  8. What is the Drizzle HTTP proxy and when to use it

    main

    Drizzle Proxy is used when you need to implement your own driver communication with the database. This is useful for adding custom logic at the query stage using existing drivers.

    A common use case is implementing an HTTP driver: your application sends queries to a server that holds the database connection, the server executes the query and returns raw data, and Drizzle ORM maps that data to results.

    Workflow:

    1. Drizzle ORM builds the query.
    2. The HTTP Proxy Driver sends the built query to the server.
    3. The server executes the query and sends raw results back.
    4. Drizzle ORM maps the data and returns it to the application.
  9. How `drizzle-seed` versioning works

    main

    The drizzle-seed library uses versioning to manage outputs for static and dynamic data. This ensures determinism: as long as the seed number remains unchanged, the generated values remain unchanged.

    When data generation logic or static data sources are updated, a new version is released. This allows you to:

    1. Upgrade to the latest version to access new generators and features.
    2. Pin to a previous version to maintain existing deterministic data outputs if you are not ready to migrate to new generation logic.

    By default, calling seed(db, schema) uses the latest available version. You can specify a maximum version to use via the version option in the configuration object.

    // Use the latest version
    await seed(db, schema);
    
    // Pin to a specific version
    await seed(db, schema, { version: '2' });
  10. Use generic types for dynamic query enhancement functions

    main

    When creating functions that modify a query builder (e.g., adding joins or filters), use generic types that extend the dialect-specific query types (like PgSelect, MySqlSelect, etc.). This allows the function to return a modified version of the query builder while preserving its type information.

    Note that these dialect-specific types are designed to be used in dynamic mode. For standalone query builder instances, use the ...QueryBuilder variants.

    function withFriends<T extends PgSelect>(qb: T) {
    	return qb.leftJoin(friends, eq(friends.userId, users.id));
    }
    
    let query = db.select().from(users).where(eq(users.id, 1)).$dynamic();
    query = withFriends(query);
  11. Use the 'with' option for one-to-many seeding

    main

    The with option in Drizzle Seed allows you to seed related data by defining a one-to-many relationship. When you use with, you specify that for every record of the parent table, a certain number of related records should be created in the child table.

    Important Constraint: The with option implies a one-to-many relationship. You can only use with to seed the "many" side of a relationship from the "one" side. For example, if one user has many posts, you can seed users with posts, but you cannot seed posts with users if the schema defines a user as the parent.

    users: {
        count: 2,
        with: {
            posts: 3,
        },
    },
  12. Refine Zod schemas for tables

    main

    You can extend, modify, or overwrite field schemas by passing an optional second argument to createSelectSchema, createInsertSchema, or createUpdateSchema.

    • To extend/modify: Pass a callback function that receives the current schema (e.g., (schema) => schema.max(20)).
    • To overwrite: Pass a new Zod schema directly (e.g., z.object({...})). This will overwrite the field entirely, including its nullability.
    import { int, mssqlTable, text } from 'drizzle-orm/mssql-core';
    import { createSelectSchema } from 'drizzle-orm/zod';
    import { z } from 'zod';
    
    const users = mssqlTable('users', {
      id: int().primaryKey(),
      name: text().notNull(),
      bio: text(),
      preferences: text()
    });
    
    const userSelectSchema = createSelectSchema(users, {
      name: (schema) => schema.max(20), // Extends schema
      bio: (schema) => schema.max(1000), // Extends schema
      preferences: z.object({ theme: z.string() }) // Overwrites the field
    });