### Quick Start with Drizzle ORM and better-sqlite3 Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/README.md This example demonstrates a basic Drizzle ORM setup using `better-sqlite3`. It shows how to define a SQLite table schema using `sqliteTable`, `text`, and `integer` types, initialize the Drizzle client, and perform a simple `SELECT` query to fetch all users. ```typescript import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'; import { drizzle } from 'drizzle-orm/better-sqlite3'; import Database from 'better-sqlite3'; const users = sqliteTable('users', { id: integer('id').primaryKey(), // 'id' is the column name fullName: text('full_name'), }) const sqlite = new Database('sqlite.db'); const db = drizzle(sqlite); const allUsers = db.select().from(users).all(); ``` -------------------------------- ### Install Netlify DB Driver Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.45.3.md Install the Netlify DB driver package using npm. ```bash npm i @netlify/db ``` -------------------------------- ### Initialize PGlite Database with Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.30.6.md Creates an in-memory Postgres instance using PGlite and initializes a Drizzle ORM database client. This example demonstrates the basic setup for using PGlite as an ephemeral database. The client can be configured with persistence options for file system or indexedDB storage. ```typescript import { PGlite } from '@electric-sql/pglite'; import { drizzle } from 'drizzle-orm/pglite'; // In-memory Postgres const client = new PGlite(); const db = drizzle(client); await db.select().from(users); ``` -------------------------------- ### Connect to Gel Database with Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.40.0.md Initialize a Drizzle ORM instance with a Gel client to query a Gel database. This example demonstrates creating a Gel client and passing it to the drizzle function for database operations. Requires the 'gel' package to be installed. ```typescript // Make sure to install the 'gel' package import { drizzle } from "drizzle-orm/gel"; import { createClient } from "gel"; const gelClient = createClient(); const db = drizzle({ client: gelClient }); const result = await db.execute('select 1'); ``` -------------------------------- ### Update LibSQL Client Dependency Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md Install the latest version of the @libsql/client package to ensure compatibility with the updated migration functions in Drizzle ORM. ```bash npm i @libsql/client@latest ``` -------------------------------- ### Install TypeScript ESLint Support Packages Source: https://github.com/drizzle-team/drizzle-orm/blob/main/eslint-plugin-drizzle/readme.md This command installs the necessary `@typescript-eslint` packages for enabling TypeScript support in your ESLint setup. These packages are crucial for parsing TypeScript files and leveraging Drizzle's type-aware linting capabilities within an IDE. ```sh [ npm | yarn | pnpm | bun ] install @typescript-eslint/eslint-plugin @typescript-eslint/parser ``` -------------------------------- ### Drizzle ORM Simplified node-postgres Connection (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.34.0.md This TypeScript example introduces the new simplified API for connecting Drizzle ORM with `node-postgres`. It demonstrates various ways to establish a connection: using a direct connection URL, an object with a connection URL and additional configurations like a logger, or a detailed connection object with specific credentials. ```ts // Finally, one import for all available clients and dialects! import { drizzle } from 'drizzle-orm' // Choose a client and use a connection URL — nothing else is needed! const db1 = await drizzle("node-postgres", process.env.POSTGRES_URL); // If you need to pass a logger, schema, or other configurations, you can use an object and specify the client-specific URL in the connection const db2 = await drizzle("node-postgres", { connection: process.env.POSTGRES_URL, logger: true }); // And finally, if you need to use full client/driver-specific types in connections, you can use a URL or host/port/etc. as an object inferred from the underlying client connection types const db3 = await drizzle("node-postgres", { connection: { connectionString: process.env.POSTGRES_URL, }, }); const db4 = await drizzle("node-postgres", { connection: { user: process.env.DB_USER, password: process.env.DB_PASSWORD, host: process.env.DB_HOST, port: process.env.DB_PORT, database: process.env.DB_NAME, ssl: true, }, }); ``` -------------------------------- ### SQLite Data-Moving Migration Pattern Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md Example of the new SQL generation for SQLite that handles column type changes by creating a new table, moving data, and renaming, rather than generating manual comments. ```sql PRAGMA foreign_keys=OFF; --> statement-breakpoint CREATE TABLE `__new_worker` ( `id` integer PRIMARY KEY NOT NULL, `name` text NOT NULL, `salary` text NOT NULL, `job_id` integer, FOREIGN KEY (`job_id`) REFERENCES `job`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint INSERT INTO `__new_worker`("id", "name", "salary", "job_id") SELECT "id", "name", "salary", "job_id" FROM `worker`; --> statement-breakpoint DROP TABLE `worker`; --> statement-breakpoint ALTER TABLE `__new_worker` RENAME TO `worker`; --> statement-breakpoint PRAGMA foreign_keys=ON; ``` -------------------------------- ### Install Drizzle ESLint Plugin Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.1.md Install the Drizzle ESLint plugin along with TypeScript ESLint dependencies to enable static analysis for database queries. ```shell npm install eslint eslint-plugin-drizzle @typescript-eslint/eslint-plugin @typescript-eslint/parser ``` -------------------------------- ### Install ESLint and Drizzle ESLint Plugin Source: https://github.com/drizzle-team/drizzle-orm/blob/main/eslint-plugin-drizzle/readme.md This command installs the core ESLint package and the `eslint-plugin-drizzle` plugin using various package managers. It's the first step to integrate Drizzle-specific linting rules into your project. ```sh [ npm | yarn | pnpm | bun ] install eslint eslint-plugin-drizzle ``` -------------------------------- ### LibSQL Table Structure with Foreign Keys Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md A table definition example for LibSQL. Note that altering columns in tables with indexes or composite foreign keys may still trigger table recreation due to engine limitations. ```sql CREATE TABLE `users` ( `id` integer NOT NULL, `name` integer, `age` integer PRIMARY KEY NOT NULL FOREIGN KEY (`name`) REFERENCES `users1`("id") ON UPDATE no action ON DELETE no action ); ``` -------------------------------- ### Initialize Database Connection with drizzle function Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm-pg/0.14.0.md The PgConnector class and its manual connect method have been deprecated in favor of the drizzle function. This new pattern simplifies the setup process by directly wrapping the database client. ```typescript import { drizzle } from 'drizzle-orm-pg/node'; // Replaces: await new PgConnector(client).connect(); const db = drizzle(client); ``` -------------------------------- ### Configure and Execute Migration Generation Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-kit/README.md Setup a migration script in package.json using CLI options to specify the output folder and schema path, followed by the command to execute the generation process. ```jsonc // package.json { "scripts": { "generate": "drizzle-kit generate --out migrations-folder --schema src/db/schema.ts" } } ``` ```shell npm run generate ``` -------------------------------- ### Install Drizzle ORM and Postgres.js dependencies Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/postgres-js/README.md Install the core Drizzle ORM package along with the Postgres.js driver and Drizzle Kit for development. Commands are provided for npm, yarn, and pnpm package managers. ```bash # npm npm i drizzle-orm postgres npm i -D drizzle-kit # yarn yarn add drizzle-orm postgres yarn add -D drizzle-kit # pnpm pnpm add drizzle-orm postgres pnpm add -D drizzle-kit ``` -------------------------------- ### Install Drizzle ORM and Drizzle Kit with npm Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/README.md This snippet provides the npm commands to install the Drizzle ORM library for SQLite and the Drizzle Kit CLI for generating automatic SQL migrations. `drizzle-orm` is the core library, and `drizzle-kit` is a development dependency. ```bash npm install drizzle-orm better-sqlite3 ## opt-in automatic migrations generator npm install -D drizzle-kit ``` -------------------------------- ### Drizzle Kit configuration for SQLite dialect (Before update) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.34.0.md This TypeScript configuration shows the previous `drizzle.config.ts` setup where both SQLite and Turso users shared the `sqlite` dialect. This approach is now deprecated for Turso users, who should switch to the dedicated `turso` dialect for improved migration strategies. ```typescript import { defineConfig } from "drizzle-kit"; export default defineConfig({ dialect: "sqlite", schema: "./schema.ts", out: "./drizzle", dbCredentials: { url: "database.db" }, breakpoints: true, verbose: true, strict: true }); ``` -------------------------------- ### Install Drizzle Seed and Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-seed/README.md Instructions to install the `drizzle-seed` library and its peer dependency `drizzle-orm` using npm. `drizzle-seed` requires `drizzle-orm@0.36.4` or higher for full compatibility and type safety. ```bash npm install drizzle-seed ``` ```bash npm install drizzle-orm ``` -------------------------------- ### Initialize Drizzle ORM connection with Postgres.js Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/postgres-js/README.md Create a database connection by wrapping a Postgres.js client with the Drizzle ORM instance. This setup enables type-safe queries and schema management within the application. ```typescript import { drizzle } from 'drizzle-orm/postgres-js'; import postgres from 'postgres'; const client = postgres(connectionString); const db = drizzle(client); ``` -------------------------------- ### Install Drizzle Kit CLI Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-kit/README.md Command to add Drizzle Kit to your project as a development dependency using the Node Package Manager. ```shell npm install -D drizzle-kit ``` -------------------------------- ### Build Drizzle ORM monorepo using pnpm Source: https://github.com/drizzle-team/drizzle-orm/blob/main/CONTRIBUTING.md This command installs all project dependencies and then builds the entire Drizzle ORM monorepo. It should be run from the root directory of the cloned repository to ensure all packages are correctly built. ```bash pnpm install && pnpm build ``` -------------------------------- ### Initialize Drizzle ORM with schema in TypeScript Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.26.0.md These examples illustrate how to initialize the Drizzle ORM client by providing your database schema. It covers two common scenarios: providing a schema from a single file and combining schemas from multiple files into a single configuration object. ```typescript import * as schema from './schema'; import { drizzle } from 'drizzle-orm/...'; const db = drizzle(client, { schema }); await db.query.users.findMany(...); ``` ```typescript import * as schema1 from './schema1'; import * as schema2 from './schema2'; import { drizzle } from 'drizzle-orm/...'; const db = drizzle(client, { schema: { ...schema1, ...schema2 } }); await db.query.users.findMany(...); ``` -------------------------------- ### Setup MySQL Proxy Driver and Migrations in TypeScript Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.0.md Implement a custom HTTP-based MySQL driver using the mysql-proxy package. This snippet shows how to handle remote queries and migrations using Axios. ```typescript import axios from 'axios'; import { eq } from 'drizzle-orm/expressions'; import { drizzle } from 'drizzle-orm/mysql-proxy'; import { migrate } from 'drizzle-orm/mysql-proxy/migrator'; import { cities, users } from './schema'; async function main() { const db = drizzle(async (sql, params, method) => { try { const rows = await axios.post(`${process.env.REMOTE_DRIVER}/query`, { sql, params, method, }); return { rows: rows.data }; } catch (e: any) { console.error('Error from pg proxy server:', e.response.data); return { rows: [] }; } }); await migrate(db, async (queries) => { try { await axios.post(`${process.env.REMOTE_DRIVER}/migrate`, { queries }); } catch (e) { console.log(e); throw new Error('Proxy server cannot run migrations'); } }, { migrationsFolder: 'drizzle' }); await db.insert(cities).values({ id: 1, name: 'name' }); await db.insert(users).values({ id: 1, name: 'name', email: 'email', cityId: 1, }); const usersToCityResponse = await db.select().from(users).leftJoin( cities, eq(users.cityId, cities.id), ); } ``` -------------------------------- ### Initialize Drizzle ORM with Vercel Postgres Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.25.4.md Sets up a Drizzle ORM database instance connected to Vercel Postgres using the sql client from @vercel/postgres. This initialization enables database queries and operations through the db object. Requires @vercel/postgres and drizzle-orm packages to be installed. ```typescript import { drizzle } from 'drizzle-orm/vercel-postgres'; import { sql } from "@vercel/postgres"; const db = drizzle(sql); db.select(...) ``` -------------------------------- ### Connect to PostgreSQL using node-postgres Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Initialize a database instance using a connection string or a configuration object. The schema property is necessary for enabling relational queries. ```typescript import { drizzle } from 'drizzle-orm/node-postgres'; import { pgTable, serial, text, integer, timestamp } from 'drizzle-orm/pg-core'; import * as schema from './schema'; // Connect with connection string const db = drizzle('postgresql://user:password@localhost:5432/mydb'); // Connect with configuration object const db = drizzle({ connection: { host: 'localhost', port: 5432, user: 'postgres', password: 'password', database: 'mydb', }, schema, // Pass schema for relational queries logger: true, // Enable query logging }); // Access the underlying pg Pool const pool = db.$client; ``` -------------------------------- ### Seed PostgreSQL Array Columns with Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-seed/0.1.3.md Shows how to seed PostgreSQL tables with array columns using Drizzle ORM. Includes examples of manual array seeding with arraySize parameter and automatic seeding that handles arrays of any dimension. ```typescript import { pgTable, integer, text, varchar } from "drizzle-orm/pg-core"; import { drizzle } from "drizzle-orm/node-postgres"; import { seed } from "drizzle-seed"; const users = pgTable("users", { id: integer().primaryKey(), name: text().notNull(), phone_numbers: varchar({ length: 256 }).array(), }); async function main() { const db = drizzle(process.env.DATABASE_URL!); await seed(db, { users }, { count: 1000 }).refine((funcs) => ({ users: { columns: { phone_numbers: funcs.phoneNumber({ arraySize: 3 }), }, }, })); } main(); ``` ```typescript async function main() { const db = drizzle(process.env.DATABASE_URL!); await seed(db, { users }); } main(); ``` -------------------------------- ### Initialize Drizzle ORM with Netlify DB (Environment Variables) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.45.3.md Initialize Drizzle ORM for Netlify DB, automatically reading connection details from NETLIFY_DB_URL and NETLIFY_DB_DRIVER environment variables. ```typescript import { drizzle } from 'drizzle-orm/netlify-db'; // reads NETLIFY_DB_URL and NETLIFY_DB_DRIVER env vars const db = drizzle(); const result = await db.execute('select 1'); ``` -------------------------------- ### Initialize Drizzle ORM with Netlify DB (Explicit Client) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.45.3.md Initialize Drizzle ORM for Netlify DB using an explicitly provided Netlify DB client, allowing consumer control over the driver. ```typescript import { drizzle } from 'drizzle-orm/netlify-db'; // Explicit client — consumer controls the driver const db = drizzle({ client: netlifyDbClient }); const result = await db.execute('select 1'); ``` -------------------------------- ### SQLite Foreign Key References - Valid and Invalid Examples Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md Demonstrates SQLite foreign key constraint rules showing which column references are valid (those with unique indexes or primary keys) and which are invalid. Referenced columns must have unique indexes or primary keys for insert operations to succeed. The example shows six child tables with varying reference scenarios, including collation sequence mismatches that cause errors. ```sql CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f); CREATE UNIQUE INDEX i1 ON parent(c, d); CREATE INDEX i2 ON parent(e); CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase); CREATE TABLE child1(f, g REFERENCES parent(a)); -- Ok CREATE TABLE child2(h, i REFERENCES parent(b)); -- Ok CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); -- Ok CREATE TABLE child4(l, m REFERENCES parent(e)); -- Error! CREATE TABLE child5(n, o REFERENCES parent(f)); -- Error! CREATE TABLE child6(p, q, FOREIGN KEY(p, q) REFERENCES parent(b, c)); -- Error! CREATE TABLE child7(r REFERENCES parent(c)); -- Error! ``` -------------------------------- ### Initialize Drizzle ORM with Netlify DB (Explicit URL) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.45.3.md Initialize Drizzle ORM for Netlify DB by providing the database URL directly. ```typescript import { drizzle } from 'drizzle-orm/netlify-db'; const db = drizzle(process.env.DATABASE_URL); const result = await db.execute('select 1'); ``` -------------------------------- ### Generate database migrations using Drizzle Kit CLI Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Uses the `drizzle-kit generate` command to create SQL migration files based on schema changes for various database dialects. ```bash # Generate migrations for PostgreSQL npx drizzle-kit generate --dialect postgresql --schema ./src/schema.ts --out ./drizzle ``` ```bash # Generate migrations for MySQL npx drizzle-kit generate --dialect mysql --schema ./src/schema.ts --out ./drizzle ``` ```bash # Generate migrations for SQLite npx drizzle-kit generate --dialect sqlite --schema ./src/schema.ts --out ./drizzle ``` ```bash # With custom migration name npx drizzle-kit generate --dialect postgresql --schema ./src/schema.ts --out ./drizzle --name add_users_table ``` -------------------------------- ### Connect to MySQL using mysql2 Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Establish a MySQL connection using the mysql2 driver. Note that the mode option is mandatory when utilizing relational queries. ```typescript import { drizzle } from 'drizzle-orm/mysql2'; import { mysqlTable, serial, varchar, int, timestamp } from 'drizzle-orm/mysql-core'; import * as schema from './schema'; // Connect with connection string const db = drizzle('mysql://user:password@localhost:3306/mydb'); // Connect with configuration and schema (mode required for relational queries) const db = drizzle({ connection: { host: 'localhost', port: 3306, user: 'root', password: 'password', database: 'mydb', }, schema, mode: 'default', // or 'planetscale' for PlanetScale logger: true, }); ``` -------------------------------- ### Drizzle ORM d1 (Cloudflare Worker) Connection (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.34.0.md This TypeScript example demonstrates connecting Drizzle ORM with Cloudflare D1 within a Cloudflare Worker environment. It shows how to pass the `env.DB` object, which contains the necessary Cloudflare Worker types for the D1 database connection. ```ts drizzle("d1", { connection: env.DB // CloudFlare Worker Types }) ``` -------------------------------- ### SQL Foreign Key Constraints and Unique Index Requirements Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.34.0.md This SQL snippet demonstrates the rules for defining foreign key constraints. It illustrates that a referenced column must have a unique index or primary key to be valid, showing examples of both successful and erroneous foreign key definitions based on index types and collation sequences. ```sql CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f); CREATE UNIQUE INDEX i1 ON parent(c, d); CREATE INDEX i2 ON parent(e); CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase); CREATE TABLE child1(f, g REFERENCES parent(a)); CREATE TABLE child2(h, i REFERENCES parent(b)); CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d)); CREATE TABLE child4(l, m REFERENCES parent(e)); CREATE TABLE child5(n, o REFERENCES parent(f)); CREATE TABLE child6(p, q, FOREIGN KEY(p, q) REFERENCES parent(b, c)); CREATE TABLE child7(r REFERENCES parent(c)); ``` -------------------------------- ### Connect to SQLite using better-sqlite3 Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Connect to SQLite via file path, an existing client, or an in-memory instance. This driver provides synchronous access suitable for edge environments. ```typescript import { drizzle } from 'drizzle-orm/better-sqlite3'; import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core'; import Database from 'better-sqlite3'; import * as schema from './schema'; // Connect with file path const db = drizzle('sqlite.db'); // Connect with existing client const sqlite = new Database('sqlite.db'); const db = drizzle({ client: sqlite, schema }); // In-memory database const db = drizzle(':memory:'); ``` -------------------------------- ### Install Node.js using NVM for Drizzle ORM development Source: https://github.com/drizzle-team/drizzle-orm/blob/main/CONTRIBUTING.md This script installs Node.js version 18.13.0 using Node Version Manager (NVM). It first installs NVM, then uses NVM to install and activate the specified Node.js version, which is required for Drizzle ORM development. ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash nvm install 18.13.0 nvm use 18.13.0 ``` -------------------------------- ### Install Drizzle ORM and Xata Client Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.30.4.md Install the necessary dependencies to use Xata with Drizzle ORM using the pnpm package manager. ```bash pnpm add drizzle-orm @xata.io/client ``` -------------------------------- ### Basic Database Seeding with Drizzle Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Import seed and reset functions from drizzle-seed, then seed your database with default or custom row counts. Use reset() to clear all data before seeding. ```typescript import { seed, reset } from 'drizzle-seed'; import { db } from './db'; import * as schema from './schema'; // Basic seeding (10 rows per table by default) await seed(db, schema); // Seed with custom count await seed(db, schema, { count: 100 }); // Seed with deterministic results (same seed = same data) await seed(db, schema, { count: 50, seed: 12345 }); // Reset (delete all data) before seeding await reset(db, schema); await seed(db, schema, { count: 100 }); ``` -------------------------------- ### Configure Drizzle Kit with snake_case Casing for Migrations Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md Sets up drizzle-kit configuration with the casing parameter to ensure migration generation respects the snake_case naming strategy. This guarantees consistent casing application across both the ORM and migration tools when generating database schemas. ```typescript import { defineConfig } from "drizzle-kit"; export default defineConfig({ dialect: "postgresql", schema: "./schema.ts", dbCredentials: { url: "postgresql://postgres:password@localhost:5432/db", }, casing: "snake_case", }); ``` -------------------------------- ### Configure Drizzle Kit Migration Prefix for Supabase (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.32.0-beta.md This configuration example demonstrates how to set up `drizzle-kit` to use the `supabase` prefix format for generated migration files. It specifies the `postgresql` dialect and customizes the `migrations.prefix` option within the `drizzle-kit.config.ts` file. This ensures migration filenames follow a `YYYYMMDDHHMMSS_name.sql` pattern suitable for Supabase or similar timestamp-based migration tools. ```typescript import { defineConfig } from "drizzle-kit"; export default defineConfig({ dialect: "postgresql", migrations: { prefix: 'supabase' } }); ``` -------------------------------- ### Install pnpm globally for Drizzle ORM development Source: https://github.com/drizzle-team/drizzle-orm/blob/main/CONTRIBUTING.md This command installs pnpm, a fast, disk space-efficient package manager, globally using npm. pnpm is used as the package manager for the Drizzle ORM monorepo. ```bash npm install -g pnpm ``` -------------------------------- ### Initialize Drizzle ORM with Bun SQL Driver Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.39.0.md Demonstrates how to connect Drizzle to Bun's native SQL driver using either a connection string or an existing Bun SQL instance. Note that current limitations apply to JSON types, array types, and specific date modes. ```ts import { drizzle } from "drizzle-orm/bun-sql"; // Direct initialization const db = drizzle(process.env.PG_DB_URL!); const result = await db.select().from(...); // Using Bun SQL instance import { drizzle as drizzleBun } from "drizzle-orm/bun-sqlite"; import { SQL } from "bun"; const client = new SQL(process.env.PG_DB_URL!); const dbWithClient = drizzleBun({ client }); const resultWithClient = await dbWithClient.select().from(...); ``` -------------------------------- ### Initialize Drizzle ORM with Planetscale Serverless Driver (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.17.5.md This snippet demonstrates how to establish a database connection to Planetscale Serverless using the `@planetscale/database` driver and initialize Drizzle ORM. It imports `drizzle` from `drizzle-orm/planetscale-serverless` and `connect` from `@planetscale/database`, then uses environment variables for host, username, and password to create the connection. The `drizzle` function then wraps this connection for ORM operations. ```typescript import { drizzle } from 'drizzle-orm/planetscale-serverless'; import { connect } from '@planetscale/database'; // create the connection const connection = connect({ host: process.env['DATABASE_HOST'], username: process.env['DATABASE_USERNAME'], password: process.env['DATABASE_PASSWORD'], }); const db = drizzle(connection); ``` -------------------------------- ### Install Drizzle ORM and Expo SQLite Driver Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.2.md Install the necessary packages to use Drizzle ORM with the Expo SQLite driver. This includes `drizzle-orm` for the ORM functionalities and `expo-sqlite@next` for the database driver. ```bash npm install drizzle-orm expo-sqlite@next ``` -------------------------------- ### Install Babel Plugin for Drizzle Migrations Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.2.md Install `babel-plugin-inline-import`, which is required for Drizzle migrations to correctly handle SQL files within an Expo project. This plugin allows Babel to inline the content of specified file types. ```bash npm install babel-plugin-inline-import ``` -------------------------------- ### Connect Drizzle ORM to various SQLite database drivers Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/README.md This section provides multiple examples for connecting Drizzle ORM to different SQLite database drivers. Each code block illustrates the necessary imports, driver initialization, and how to create a Drizzle client for `better-sqlite3`, `bun:sqlite`, Cloudflare D1, `libSQL`/Turso, and a custom HTTP proxy driver. ```typescript // better-sqlite3 or fly.io LiteFS import { drizzle, BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'; import Database from 'better-sqlite3'; const sqlite = new Database('sqlite.db'); const db/*: BetterSQLite3Database*/ = drizzle(sqlite); const result = db.select().from(users).all() ``` ```typescript // bun js embedded sqlite connector import { drizzle, BunSQLiteDatabase } from 'drizzle-orm/bun-sqlite'; import { Database } from 'bun:sqlite'; const sqlite = new Database('nw.sqlite'); const db/*: BunSQLiteDatabase*/ = drizzle(sqlite); const result = db.select().from(users).all() ``` ```typescript // Cloudflare D1 connector import { drizzle, DrizzleD1Database } from 'drizzle-orm/d1'; // env.DB from cloudflare worker environment const db/*: DrizzleD1Database*/ = drizzle(env.DB); const result = await db.select().from(users).all(); // pay attention this one is async ``` ```typescript // libSQL or Turso import { drizzle, LibSQLDatabase } from 'drizzle-orm/libsql'; import { Database } from '@libsql/sqlite3'; const sqlite = new Database('libsql://...'); // Remote server // or const sqlite = new Database('sqlite.db'); // Local file const db/*: LibSQLDatabase*/ = drizzle(sqlite); const result = await db.select().from(users).all(); // pay attention this one is async ``` ```typescript // Custom Proxy HTTP driver const db = drizzle(async (sql, params, method) => { try { const rows = await axios.post('http://localhost:3000/query', { sql, params, method }); return { rows: rows.data }; } catch (e: any) { console.error('Error from sqlite proxy server: ', e.response.data) return { rows: [] }; } }); ``` -------------------------------- ### Initialize Drizzle ORM with `@libsql/client/web` driver (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.35.3.md This snippet illustrates initializing Drizzle ORM for full-stack web frameworks like Next.js, Nuxt.js, or Astro using the `@libsql/client/web` driver. It's designed for browser-compatible environments. Connection details like `url` and `authToken` are provided via environment variables. ```typescript import { drizzle } from 'drizzle-orm/libsql/web'; const db = drizzle({ connection: { url: process.env.DATABASE_URL, authToken: process.env.DATABASE_AUTH_TOKEN }}}); ``` -------------------------------- ### Install Drizzle ESLint Plugin Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.2.md Install the Drizzle ESLint plugin to enable linting for Drizzle ORM usage in your project. This helps in identifying potential issues and improving code quality related to Drizzle ORM queries and schema definitions. ```bash npm i eslint-plugin-drizzle@0.2.3 ``` -------------------------------- ### Configure transaction isolation level in Drizzle ORM (PostgreSQL) Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Specifies how a transaction interacts with other concurrent transactions, ensuring data consistency. This example sets 'serializable' isolation. ```typescript // Transaction with isolation level (PostgreSQL) await db.transaction(async (tx) => { // ... queries }, { isolationLevel: 'serializable', accessMode: 'read write', }); ``` -------------------------------- ### Configure Drizzle Kit for Gel Dialect (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.30.5.md This configuration snippet demonstrates how to set up your `drizzle.config.ts` file to use the new `gel` dialect. This is essential for `drizzle-kit` to correctly interact with a Gel database, specifically for pulling schema definitions. It imports `defineConfig` from `drizzle-kit` and exports a configuration object specifying 'gel' as the dialect. ```typescript // drizzle.config.ts import { defineConfig } from 'drizzle-kit'; export default defineConfig({ dialect: 'gel', }); ``` -------------------------------- ### Import Migrations from better-sqlite3 Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm-sqlite/0.14.1.md Separated migrations functionality into a dedicated import path for better-sqlite3. This allows for modular imports and cleaner dependency management when working with SQLite migrations. ```typescript import { migrate } from 'drizzle-orm-sqlite/better-sqlite3/migrate'; ``` -------------------------------- ### Use PostgreSQL Array Operators in TypeScript Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.28.6.md Provides examples of using arrayContains, arrayContained, and arrayOverlaps operators for filtering PostgreSQL array columns, including subquery support. ```typescript const contains = await db.select({ id: posts.id }).from(posts) .where(arrayContains(posts.tags, ['Typescript', 'ORM'])); const contained = await db.select({ id: posts.id }).from(posts) .where(arrayContained(posts.tags, ['Typescript', 'ORM'])); const overlaps = await db.select({ id: posts.id }).from(posts) .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM'])); const withSubQuery = await db.select({ id: posts.id }).from(posts) .where(arrayContains( posts.tags, db.select({ tags: posts.tags }).from(posts).where(eq(posts.id, 1)), )); ``` -------------------------------- ### Run Migrations Programmatically (MySQL) Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Apply pending migrations to MySQL using drizzle-orm/mysql2. Requires mysql2/promise connection. ```typescript // Programmatic migration (MySQL) import { drizzle } from 'drizzle-orm/mysql2'; import { migrate } from 'drizzle-orm/mysql2/migrator'; import mysql from 'mysql2/promise'; const connection = await mysql.createConnection(process.env.DATABASE_URL!); const db = drizzle(connection); await migrate(db, { migrationsFolder: './drizzle' }); console.log('Migrations completed!'); await connection.end(); ``` -------------------------------- ### Setup SingleStore Dialect with Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.37.0.md Initialize SingleStore dialect in Drizzle ORM by importing core types and creating a database connection. Define table schemas using singlestoreTable with column definitions like int, varchar, and constraints. This enables querying SingleStore databases with Drizzle's type-safe query builder. ```typescript import { int, singlestoreTable, varchar } from 'drizzle-orm/singlestore-core'; import { drizzle } from 'drizzle-orm/singlestore'; export const usersTable = singlestoreTable('users_table', { id: int().primaryKey(), name: varchar({ length: 255 }).notNull(), age: int().notNull(), email: varchar({ length: 255 }).notNull().unique(), }); const db = drizzle(process.env.DATABASE_URL!); db.select()... ``` -------------------------------- ### Connect to Xata using drizzle-orm/xata-http Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.30.4.md Initialize the Drizzle ORM instance using the Xata generated client. This setup enables type-safe database operations on the Xata Postgres platform. ```typescript import { drizzle } from 'drizzle-orm/xata-http'; import { getXataClient } from './xata'; // Generated client const xata = getXataClient(); const db = drizzle(xata); const result = await db.select().from(...); ``` -------------------------------- ### Execute raw SQL query with multiple template literal parameters Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Demonstrates passing multiple JavaScript variables as parameters to a raw SQL query, ensuring proper escaping. ```typescript // Raw query with template literal const minAge = 21; const status = 'active'; const filteredUsers = await db.execute(sql` SELECT * FROM users WHERE age >= ${minAge} AND status = ${status} ORDER BY created_at DESC LIMIT 10 `); ``` -------------------------------- ### Insert Records and Handle Results in Drizzle ORM Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/sqlite-core/README.md Examples of inserting single or multiple records into a table. Includes usage of .returning() to retrieve inserted data and handling both individual arguments and arrays. ```typescript // Single insert db.insert(users).values(newUser).run(); // Insert with returning values const insertedUsers = db.insert(users).values(newUser).returning().all(); // Insert several items db.insert(users) .values( { name: 'Andrew', createdAt: new Date() }, { name: 'Dan', createdAt: new Date() } ) .run(); // Insert array of items const newUsers: NewUser[] = [ { name: 'Andrew', createdAt: new Date() }, { name: 'Dan', createdAt: new Date() } ]; db.insert(users).values(newUsers).run(); ``` -------------------------------- ### Initialize Drizzle with Custom Cache Implementation Source: https://github.com/drizzle-team/drizzle-orm/blob/main/drizzle-orm/src/cache/readme.md Configure a Drizzle database instance with a custom cache implementation. This example uses TestGlobalCache, a custom Cache class that manages query caching with table-based invalidation. ```typescript const db = drizzle(process.env.DB_URL!, { cache: new TestGlobalCache() }) ``` -------------------------------- ### Configure Drizzle Kit with drizzle.config.ts Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Define database dialect, schema location, and credentials for code generation. Required for running drizzle-kit commands. ```typescript // drizzle.config.ts import { defineConfig } from 'drizzle-kit'; export default defineConfig({ dialect: 'postgresql', schema: './src/schema.ts', out: './drizzle', dbCredentials: { url: process.env.DATABASE_URL!, }, }); ``` -------------------------------- ### Run Migrations Programmatically (PostgreSQL) Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Apply pending migrations to PostgreSQL using drizzle-orm/node-postgres. Requires a Pool connection and migrations folder. ```typescript // Programmatic migration (PostgreSQL) import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const db = drizzle(pool); await migrate(db, { migrationsFolder: './drizzle' }); console.log('Migrations completed!'); await pool.end(); ``` -------------------------------- ### Replace SQLiteConnector with drizzle() Function Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm-sqlite/0.14.1.md Simplified connector initialization by replacing the SQLiteConnector class instantiation and connect() method with the drizzle() function. This provides a more intuitive and streamlined API for establishing database connections. ```typescript // Old approach await new SQLiteConnector(client).connect(); // New approach drizzle(client); ``` -------------------------------- ### Run Migrations Programmatically (SQLite) Source: https://context7.com/drizzle-team/drizzle-orm/llms.txt Apply pending migrations to SQLite using drizzle-orm/better-sqlite3. Synchronous operation, no await needed. ```typescript // Programmatic migration (SQLite) import { drizzle } from 'drizzle-orm/better-sqlite3'; import { migrate } from 'drizzle-orm/better-sqlite3/migrator'; import Database from 'better-sqlite3'; const sqlite = new Database('sqlite.db'); const db = drizzle(sqlite); migrate(db, { migrationsFolder: './drizzle' }); console.log('Migrations completed!'); ``` -------------------------------- ### Update SQLiteConnector Import Path Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm-sqlite/0.14.1.md Updated import statement for drizzle function from SQLiteConnector module. The new import path reflects the better-sqlite3 driver integration and replaces the previous generic SQLiteConnector import. ```typescript // Old import import { SQLiteConnector } from 'drizzle-orm-sqlite'; // New import import { drizzle } from 'drizzle-orm-sqlite/better-sqlite3'; ``` -------------------------------- ### Configure Turso Dialect in Drizzle Config Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.25.0.md Update the drizzle.config file to use the new 'turso' dialect. This allows Drizzle to use Turso-specific migration strategies independently from standard SQLite. ```typescript import { defineConfig } from "drizzle-kit"; export default defineConfig({ dialect: "turso", schema: "./schema.ts", out: "./drizzle", dbCredentials: { url: "database.db", }, breakpoints: true, verbose: true, strict: true, }); ``` -------------------------------- ### Execute Raw SQL Using SQL Templates (Legacy) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.34.0.md Previous method for executing raw SQL queries using sql template literals or sql.raw() function. Still supported but the plain string approach is now preferred for simpler cases. ```typescript import { sql } from 'drizzle-orm' db.execute(sql`select * from ${users}`); // or db.execute(sql.raw(`select * from ${users}`)); ``` -------------------------------- ### Configure Drizzle Kit for SingleStore Dialect (TypeScript) Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-kit/0.29.0.md This configuration snippet for `drizzle-kit` sets up the project to use the SingleStore dialect. It specifies the output directory for migrations, the path to the database schema, and retrieves database credentials from an environment variable. This allows Drizzle ORM to generate migrations and interact with a SingleStore database. ```typescript import 'dotenv/config'; import { defineConfig } from 'drizzle-kit'; export default defineConfig({ dialect: 'singlestore', out: './drizzle', schema: './src/db/schema.ts', dbCredentials: { url: process.env.DATABASE_URL!, }, }); ``` -------------------------------- ### Map from Driver Value for Integer Type Override Source: https://github.com/drizzle-team/drizzle-orm/blob/main/docs/custom-types.md Demonstrates the mapFromDriverValue() interceptor method that transforms database values after retrieval. This example shows type conversion from string to number for integer data types. ```typescript override mapFromDriverValue(value: number | string): number { if (typeof value === 'string') { return parseInt(value); } return value; } ``` -------------------------------- ### Map to Driver Value for JSONB Type Override Source: https://github.com/drizzle-team/drizzle-orm/blob/main/docs/custom-types.md Demonstrates the mapToDriverValue() interceptor method that transforms user input before sending to the database. This example shows JSON serialization for JSONB data types in PostgreSQL. ```typescript override mapToDriverValue(value: TData): string { return JSON.stringify(value); } ``` -------------------------------- ### Implement Custom Read Replica Selection Logic in TypeScript Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.29.0.md Define custom routing logic for read replicas, such as weighted random selection. This example demonstrates a 70/30 split between two replica instances. ```typescript const db = withReplicas(primaryDb, [read1, read2], (replicas) => { const weight = [0.7, 0.3]; let cumulativeProbability = 0; const rand = Math.random(); for (const [i, replica] of replicas.entries()) { cumulativeProbability += weight[i]!; if (rand < cumulativeProbability) return replica; } return replicas[0]! }); ``` -------------------------------- ### Define PostgreSQL Sequences with pgSequence Source: https://github.com/drizzle-team/drizzle-orm/blob/main/changelogs/drizzle-orm/0.32.0.md Allows the creation and configuration of PostgreSQL sequences within specific schemas. Supports parameters such as start value, increment, min/max values, and caching. ```typescript import { pgSchema, pgSequence } from "drizzle-orm/pg-core"; // Basic sequence definition export const customSequence = pgSequence("name"); // Sequence with advanced parameters export const customSequenceWithParams = pgSequence("name", { startWith: 100, maxValue: 10000, minValue: 100, cycle: true, cache: 10, increment: 2 }); // Sequence within a custom schema export const customSchema = pgSchema('custom_schema'); export const sequenceInSchema = customSchema.sequence("name"); ```