new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Drizzle ORM · all subjects

drizzle-orm/setup

327 notes in this subject, read out of this brain and free to use. This is page 3 of 6.

Turso database URL and auth token environment variables

To connect to Turso, you need to set two environment variables: TURSO_DATABASE_URL and TURSO_AUTH_TOKEN. These should be added to a .env file in the root of your project.

Initialize Drizzle ORM connection to Turso with inline credentials

Import drizzle from 'drizzle-orm/libsql' and initialize the connection by passing an object with a connection property containing url and authToken from environment variables.

Initialize Drizzle ORM connection to Turso with existing libsql client

You can provide your own @libsql/client instance by creating a client with createClient and passing it to the drizzle function via the client property instead of inline credentials.

Turso connection code example with inline credentials

import 'dotenv/config'; import { drizzle } from 'drizzle-orm/libsql'; const db = drizzle({ connection: { url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN! } });

Turso connection code example with existing libsql client

import 'dotenv/config'; import { drizzle } from 'drizzle-orm/libsql'; import { createClient } from '@libsql/client'; const client = createClient({ url: process.env.TURSO_DATABASE_URL!, authToken: process.env.TURSO_AUTH_TOKEN! }); const db = drizzle({ client });

Drizzle supports libsql driver variations

Drizzle has native support for all @libsql/client driver variations for connecting to Turso.

Turso connection setup prerequisites

Before setting up Drizzle with Turso, you need dotenv package for managing environment variables, tsx package for running TypeScript files, turso (SQLite for Production), and libsql which is a fork of SQLite optimized for low query latency.

Vercel Postgres setup package

Install the @vercel/postgres package to use Vercel Postgres with Drizzle ORM.

Connect Drizzle ORM to Vercel Postgres

To connect Drizzle ORM to Vercel Postgres, import drizzle from 'drizzle-orm/vercel-postgres' and call drizzle() without arguments. The connection will automatically use the POSTGRES_URL environment variable.

Prerequisites for Drizzle with Vercel Postgres

To set up Drizzle ORM with Vercel Postgres in an existing project, you need: dotenv package for managing environment variables, tsx package for running TypeScript files, a Vercel Postgres database, and the Vercel Postgres driver.

Prerequisites for Drizzle and Vercel Postgres

The following packages and services are required: dotenv (for managing environment variables), tsx (for running TypeScript files), Vercel Postgres database, and the Vercel Postgres driver from the @vercel/storage package.

Vercel Postgres environment variable naming

The environment variable for Vercel Postgres must be named POSTGRES_URL. This variable can be found in the Vercel Postgres storage tab under the .env.local tab.

Drizzle ORM with Vercel Postgres setup steps

The setup process involves eight steps: install @vercel/postgres package, setup POSTGRES_URL connection variable in environment, connect Drizzle ORM to the database using drizzle-orm/vercel-postgres, create a table schema, setup drizzle.config.ts with postgresql dialect and POSTGRES_URL variable, apply changes to database with drizzle-kit, seed and query the database, and run the index.ts file.

Vercel Postgres get-started complete example

This example demonstrates seeding and querying a Vercel Postgres database with Drizzle ORM. It imports 'dotenv/config', the eq operator, drizzle from 'drizzle-orm/vercel-postgres', and a usersTable schema. It creates a drizzle instance with db = drizzle(), inserts a user record, selects all users, updates a user's age by email, and deletes a user by email.

Babel config for inline SQL imports in Expo

To support inline SQL imports in an Expo project with Drizzle ORM, add the `inline-import` plugin to babel.config.js with `extensions: [".sql"]` to the plugins array.

OP-SQLite required packages

For Drizzle ORM with OP-SQLite, install `drizzle-orm@rc` and `@op-engineering/op-sqlite` as production dependencies, and `drizzle-kit@rc` as a development dependency.

Run Expo app on iOS

To run an Expo app with Drizzle ORM on iOS, use one of: `npx expo run:ios`, `yarn expo run:ios`, `pnpm expo run:ios`, or `bun expo run:ios` after running prebuild.

OP-SQLite migration example code

Example of applying migrations and querying an OP-SQLite database in Expo: ```ts import { open } from '@op-engineering/op-sqlite'; import { drizzle } from 'drizzle-orm/op-sqlite'; import { useMigrations } from 'drizzle-orm/op-sqlite/migrator'; import migrations from './drizzle/migrations'; const opsqliteDb = open({ name: 'db' }); const db = drizzle(opsqliteDb); const { success, error } = useMigrations(db, migrations); if (success) { await db.delete(usersTable); await db.insert(usersTable).values([{ name: 'John', age: 30, email: 'john@example.com' }]); const users = await db.select().from(usersTable); } ```

OP-SQLite setup with Expo template

To set up Drizzle ORM with OP-SQLite in a React Native Expo project, start by creating an Expo project with the blank-typescript template using `create expo-app --template blank-typescript`.

OP-SQLite project file structure

After setting up an Expo project with Drizzle ORM for OP-SQLite, the project includes: assets folder, drizzle folder for SQL migration files and snapshots, db folder containing schema.ts with drizzle table definitions, .gitignore, .npmrc, app.json, App.tsx, babel.config.ts, drizzle.config.ts, package.json, and tsconfig.json.

Initialize OP-SQLite database connection

To connect Drizzle ORM to an OP-SQLite database, import `open` from `@op-engineering/op-sqlite` and `drizzle` from `drizzle-orm/op-sqlite`. Call `open({ name: 'db' })` to create the database instance, then pass it to `drizzle()` to create the Drizzle ORM instance.

Metro config for SQL files in Expo

When using Drizzle ORM with Expo and OP-SQLite, create a metro.config.js file in the root folder and configure it to support SQL files by adding 'sql' to the resolver's sourceExts array.

Install postgres package for Xata

The postgres package is required to connect Drizzle ORM to a Xata Postgres database.

DATABASE_URL environment variable for Xata

Set up a DATABASE_URL environment variable to store the connection string to your Xata Postgres database. The connection string can be obtained from the Xata documentation.

Connect Drizzle ORM to Xata database

Drizzle ORM connects to Xata using a postgres package and a DATABASE_URL connection string obtained from Xata documentation.

Xata setup prerequisites

To get started with Drizzle ORM and Xata, you need: dotenv package for managing environment variables, tsx package for running TypeScript files, and a Xata Postgres database.

Xata Drizzle setup workflow steps

The complete setup workflow for Drizzle and Xata consists of: installing the postgres package, setting up connection variables via DATABASE_URL, connecting Drizzle ORM to the database, creating a table, setting up the Drizzle config file with postgresql dialect, applying changes to the database, seeding and querying the database, and running the TypeScript file.

json mode option behavior in text columns

When using the mode: 'json' option with text columns, values are treated as JSON object literals in the application. The .$type<T>() method provides compile-time type protection for default values, insert, and select schemas, though it does not check runtime values.

PostgreSQL empty array default with sql operator

To set an empty array as a default value in PostgreSQL, use the sql operator with either '{}' or ARRAY[] syntax. The syntax is sql`'{}'::text[]` for the '{}' approach or sql`ARRAY[]::text[]` for the ARRAY[] approach, both with the appropriate type cast.

MySQL empty array default with JSON type

MySQL does not have a native array data type. Use the json data type instead for array values. Set empty array defaults using either default([]) directly, sql`('[]')`, or sql`(JSON_ARRAY())`. All approaches are equivalent in the generated SQL.

SQLite empty array default with json mode text

SQLite does not have a native array data type. Use text type with mode: 'json' option for array values. Set empty array defaults using either sql`(json_array())` or sql`'[]'`. Use .$type<string[]>() for compile-time type protection.

PostgreSQL empty array column example

This example shows how to define PostgreSQL array columns with empty array defaults: ```ts import { sql } from 'drizzle-orm'; import { pgTable, serial, text } from 'drizzle-orm/pg-core'; export const users = pgTable('users', { id: serial('id').primaryKey(), name: text('name').notNull(), tags1: text('tags1') .array() .notNull() .default(sql`'{}'::text[]`), tags2: text('tags2') .array() .notNull() .default(sql`ARRAY[]::text[]`), }); ```

MySQL empty array column example

This example shows how to define MySQL json columns with empty array defaults: ```ts import { sql } from 'drizzle-orm'; import { json, mysqlTable, serial, varchar } from 'drizzle-orm/mysql-core'; export const users = mysqlTable('users', { id: serial('id').primaryKey(), name: varchar('name', { length: 255 }).notNull(), tags1: json('tags1').$type<string[]>().notNull().default([]), tags2: json('tags2') .$type<string[]>() .notNull() .default(sql`('[]')`), tags3: json('tags3') .$type<string[]>() .notNull() .default(sql`(JSON_ARRAY())`), }); ```

SQLite empty array column example

This example shows how to define SQLite text columns with json mode and empty array defaults: ```ts import { sql } from 'drizzle-orm'; import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'; export const users = sqliteTable('users', { id: integer('id').primaryKey(), tags1: text('tags1', { mode: 'json' }) .notNull() .$type<string[]>() .default(sql`(json_array())`), tags2: text('tags2', { mode: 'json' }) .notNull() .$type<string[]>() .default(sql`'[]'`), }); ```

Gel auth extension schema setup

To use the Gel auth extension with Drizzle ORM, define a schema in dbschema/default.esdl that imports the auth extension. The schema must include a global current_user that asserts a single User and filters by ext::auth::ClientTokenIdentity. The User type should have required fields: identity (ext::auth::Identity), username (str), and email (str).

PostGIS extension setup with Drizzle

Drizzle does not create the PostGIS extension automatically. To enable PostGIS support, create an empty migration file using 'npx drizzle-kit generate --custom' and add the SQL query 'CREATE EXTENSION postgis;' to it.

PostgreSQL full-text search prerequisites

To implement PostgreSQL full-text search with Drizzle ORM, you need drizzle-orm@0.31.0 and drizzle-kit@0.22.0 or higher.

Drizzle version requirements for case-insensitive email handling

Case-insensitive email handling with uniqueIndex and sql operator requires drizzle-orm@0.31.0 and drizzle-kit@0.22.0 or higher.

Enable JIT mappers in drizzle initialization

To enable JIT mappers, pass the `jit: true` option when calling the drizzle function during initialization. Example: `const db = drizzle({ client, jit: true });`

JIT mappers are disabled by default

JIT mappers are disabled by default. Enable them by passing the `jit: true` option when initializing Drizzle.

JIT option available in every driver's config

The `jit` option is available in every driver's config for enabling JIT mappers.

JIT mapper compatibility check fallback

On initialization, Drizzle runs a compatibility check to test whether the Function constructor works in the current runtime. If it does not work (such as in some edge runtimes or CSP-restricted environments), Drizzle falls back to regular mappers with a console warning.

typebox integration installation

To use typebox with Drizzle ORM, install the dependencies: drizzle-orm@rc and typebox.

Drizzle schema declaration example

Drizzle schemas are defined using TypeScript functions like pgTable() with column definitions. Example: export const countries = pgTable('countries', { id: serial('id').primaryKey(), name: varchar('name', { length: 256 }), });

Type assertion for text column enums

Use the .$type<T>() method on text columns to specify TypeScript types. Example: text('role').$type<'admin' | 'customer'>() ensures the column accepts only these values in TypeScript.

PostgreSQL schema declaration with pgTable

Import serial, text, timestamp, and pgTable from 'drizzle-orm/pg-core'. Create a table using pgTable('table_name', { columns }). Example: const user = pgTable('user', { id: serial('id'), name: text('name'), email: text('email'), password: text('password'), role: text('role').$type<'admin' | 'customer'>(), createdAt: timestamp('created_at'), updatedAt: timestamp('updated_at') }).

Install Drizzle ORM and Drizzle Kit

Install drizzle-orm and drizzle-kit using npm. The command is 'npm install drizzle-orm postgres -D drizzle-kit' (drizzle-kit is a dev dependency).

Quick start workflow with PostgreSQL

The quick start workflow is: 1) Install drizzle-orm and drizzle-kit, 2) Create schema.ts with pgTable definitions, 3) Create drizzle.config.ts with dialect, schema path, and output directory, 4) Run 'npm run generate' to create SQL migration files, 5) Run 'npm run migrate' to apply migrations to the database.

SingleStore driver support with Drizzle ORM

Drizzle ORM supports SingleStore database connections using the SingleStore driver. Documentation for SingleStore setup is available in the SingleStore get-started guide.

SingleStore connection with mysql2 driver

To use Drizzle with SingleStore, import drizzle from 'drizzle-orm/singlestore' and pass a mysql2 connection or pool to the drizzle function. The mysql2 driver is required and is natively supported by Drizzle ORM.

Initialize SingleStore connection with config object

To initialize a SingleStore connection with a config object: import { drizzle } from 'drizzle-orm/singlestore'; const db = drizzle({ connection: { uri: process.env.DATABASE_URL } }); This accepts any property from the mysql2 connection options.

Initialize SingleStore with existing mysql2 client connection

To use an existing mysql2 client connection with SingleStore: import { drizzle } from 'drizzle-orm/singlestore'; import mysql from 'mysql2/promise'; const connection = await mysql.createConnection({ host: 'host', user: 'user', database: 'database' }); const db = drizzle({ client: connection });

Initialize SingleStore with mysql2 pool connection

To use a mysql2 pool connection with SingleStore: import { drizzle } from 'drizzle-orm/singlestore'; import mysql from 'mysql2/promise'; const poolConnection = mysql.createPool({ host: 'host', user: 'user', database: 'database' }); const db = drizzle({ client: poolConnection });

Install packages for SingleStore with Drizzle

To set up Drizzle with SingleStore, install drizzle-orm@rc, mysql2, and drizzle-kit@rc as a dev dependency.

Initialize SingleStore connection with URI string

To initialize a SingleStore connection using a URI string: import { drizzle } from 'drizzle-orm/singlestore'; const db = drizzle(process.env.DATABASE_URL);

v2 no mode parameter needed in drizzle()

In Relational Queries v2, the mode parameter is no longer needed when creating a drizzle instance for MySQL dialects. The same strategy is used for all MySQL dialects, eliminating the need to specify 'planetscale' or 'default' modes.

v2 drizzle instance creation with relations

In v2, create the drizzle database instance by passing the relations object instead of schema: import { relations } from './relations'; import { drizzle } from 'drizzle-orm/...'; const db = drizzle('<url>', { relations });

v2 internal generic changes in database instances

In v2, drizzle database, session, migrator, and transaction instances use new generic arguments for RQB v2 queries. NodePgDatabase now uses TRelations extends AnyRelations instead of TSchema extends Record<string, unknown>. Similar changes apply to NodePgSession and NodePgTransaction.

v2 DrizzleConfig interface changes

The DrizzleConfig interface now has a TRelationConfigs extends AnyRelations generic parameter and includes relations?: TRelationConfigs field. The schema field has been removed. New fields include cache and jit options.

Server-side functions with revalidatePath in Next.js

Use "use server" directive to mark functions as server-side. After database operations, call revalidatePath("/") to revalidate the Next.js cache for the specified path, ensuring the UI reflects the latest data.

Give your agent this brain