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 1 of 6.

Install packages for Bun SQLite

Install drizzle-orm@rc and dotenv as dependencies. Install drizzle-kit@rc, tsx, and @types/bun as dev dependencies.

Bun SQLite integration workflow

The workflow for integrating Drizzle ORM with Bun and SQLite in an existing project involves: installing required packages, setting up connection variables via environment file, setting up drizzle.config file with sqlite dialect, introspecting the existing database, transferring introspected code to the schema file, connecting Drizzle ORM to the database, querying the database, and optionally updating table schema and applying changes.

Bun SQLite setup prerequisites

To set up Drizzle ORM with Bun and SQLite in an existing project, you need: dotenv for managing environment variables, tsx for running TypeScript files, bun (JavaScript all-in-one toolkit), and bun:sqlite (native implementation of a high-performance SQLite3 driver).

D1 example query in Worker

To query a D1 database in a Cloudflare Worker: import drizzle from 'drizzle-orm/d1', create a db instance with drizzle(env.<BINDING_NAME>), then use db.select().from(users).all() to execute queries and return results as JSON.

Connect Drizzle ORM to D1 database

To connect Drizzle ORM to a Cloudflare D1 database, import drizzle from 'drizzle-orm/d1' and call drizzle(env.<BINDING_NAME>) where BINDING_NAME matches the binding specified in wrangler.toml. This is typically done within a Cloudflare Worker fetch handler.

D1 wrangler.toml configuration

A D1 database requires a wrangler.toml file with the following structure: name (project name), main (entry point), compatibility_date (version date), node_compat (set to true), and a [[d1_databases]] section with binding (name to bind the database), database_name (the D1 database name), database_id (the D1 database ID), and migrations_dir (path to migrations, typically 'drizzle').

Prerequisites for D1 setup

Setting up Drizzle ORM with Cloudflare D1 requires: dotenv package for managing environment variables, tsx package for running TypeScript files, Cloudflare D1 (Serverless SQL database), and wrangler (Cloudflare Developer Platform command-line interface).

Connect Drizzle to Cloudflare Durable Objects

Import drizzle and DrizzleSqliteDODatabase from 'drizzle-orm/durable-sqlite'. Pass the DurableObject's storage object to drizzle() to initialize the database instance. Example: this.db = drizzle(this.storage, { logger: false });

Access Durable Object from Worker fetch handler

In a Cloudflare Worker's fetch handler, access a bound Durable Object using env.[BINDING_NAME].idFromName() to get the ID, then env.[BINDING_NAME].get(id) to get the stub. Call methods on the stub to execute code in the Durable Object. Example: const stub = env.MY_DURABLE_OBJECT.get(env.MY_DURABLE_OBJECT.idFromName('durable-object'));

DrizzleSqliteDODatabase type annotation

When storing a Drizzle database instance for Cloudflare Durable Objects, use the type DrizzleSqliteDODatabase or DrizzleSqliteDODatabase<any>. This provides proper TypeScript typing for the Durable Object's database connection.

Durable Objects bindings in wrangler.toml

Declare Durable Object bindings in wrangler.toml using [[durable_objects.bindings]] sections. Specify a name for the binding and the class_name of the Durable Object. Example: [[durable_objects.bindings]] with name = 'MY_DURABLE_OBJECT' and class_name = 'MyDurableObject'.

Connecting to SQLite Durable Objects with drizzle function

Import drizzle and DrizzleSqliteDODatabase from 'drizzle-orm/durable-sqlite'. In a DurableObject constructor, call drizzle(storage, options) where storage is ctx.storage from the DurableObjectState. Options include logger as a boolean flag. The result is typed as DrizzleSqliteDODatabase.

Drizzle setup with Cloudflare SQLite Durable Objects

To set up Drizzle ORM with Cloudflare SQLite Durable Objects, you need to install wrangler, create a wrangler.toml configuration file with Durable Object bindings and migrations, import drizzle from 'drizzle-orm/durable-sqlite', and define a DurableObject class that initializes the database connection with the Durable Object storage. The drizzle function accepts the storage instance and options like logger configuration.

Generating wrangler types for Cloudflare Workers

Run 'npx wrangler types' to generate a worker-configuration.d.ts file that provides type definitions for bindings and environment variables declared in wrangler.toml.

Drizzle ORM native support for Effect PostgreSQL

Drizzle has native support for Effect PostgreSQL connections with the @effect/sql-pg driver.

Effect PostgreSQL connection setup example

The example shows creating an Effect layer for PgClient with configuration including the DATABASE_URL and a custom type parser for PostgreSQL special types (1184, 1114, 1082, 1186, 1231, 1115, 1185, 1187, 1182). The PgDrizzle.makeWithDefaults() function creates a database instance within an Effect generator function.

Effect PostgreSQL type parser configuration

When configuring PgClient for Effect PostgreSQL, the types configuration accepts a getTypeParser function that receives typeId and format parameters. The function should return a parser function or fallback to types.getTypeParser(). PostgreSQL type IDs 1184, 1114, 1082, 1186, 1231, 1115, 1185, 1187, 1182 are commonly handled with identity parser (return value as-is).

Install packages for Effect PostgreSQL

To set up Drizzle with Effect PostgreSQL, install the main packages with: effect @effect/sql-pg pg. Install dev dependencies with: @types/pg.

Required packages for Gel setup

To set up Drizzle ORM with Gel database, install drizzle-orm and gel as production dependencies, and drizzle-kit and tsx as dev dependencies.

Install packages for Expo Drizzle setup

Install expo-sqlite with 'expo install expo-sqlite', then install drizzle-orm and drizzle-kit with 'npm install drizzle-orm@rc -D drizzle-kit@rc'.

Expo project file structure for Drizzle

The recommended file structure includes: db/schema.ts for table definitions, drizzle/ folder for migrations and snapshots, drizzle.config.ts in the root, metro.config.js for bundler config, and babel.config.js for plugin configuration.

Babel config for inline SQL imports in Expo

Configure babel.config.js to support inline SQL imports by adding the 'inline-import' plugin with '.sql' extension. Example: module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: [['inline-import', { 'extensions': ['.sql'] }]] }; };

Metro config setup for Expo with SQL files

When using Drizzle with Expo, create a metro.config.js file in the root folder and add 'sql' to the resolver.sourceExts array to allow bundling of SQL files. Example: const config = getDefaultConfig(__dirname); config.resolver.sourceExts.push('sql'); module.exports = config;

Expo SQLite setup with Drizzle ORM

To connect Drizzle ORM to an Expo SQLite database, import the expo-sqlite package and drizzle function, open the database with SQLite.openDatabaseSync(), then pass it to drizzle(). Example: const expo = SQLite.openDatabaseSync('db.db'); const db = drizzle(expo);

MySQL existing project setup steps

The setup process for MySQL in an existing Drizzle ORM project follows these steps: (1) Install the mysql2 package, (2) Setup connection variables using DATABASE_URL, (3) Setup Drizzle config file with mysql dialect, (4) Introspect your existing database, (5) Transfer the introspected code to your schema file, (6) Connect Drizzle ORM to the database, (7) Query the database, (8) Run the index.ts file, (9) Optionally update your table schema, (10) Optionally apply changes to the database, (11) Optionally query the database with new fields.

MySQL existing project prerequisites

To get started with Drizzle ORM and MySQL in an existing project, you need the dotenv package for managing environment variables, the tsx package for running TypeScript files, and the mysql2 package for querying your MySQL database.

MySQL get-started steps

The get-started workflow for MySQL with Drizzle follows these steps: (1) Install mysql2 package, (2) Setup connection variables in environment, (3) Connect Drizzle ORM to the database, (4) Create a table, (5) Setup Drizzle config file, (6) Apply changes to the database, (7) Seed and query the database, (8) Run the index.ts file.

Prerequisites for MySQL Drizzle setup

Before setting up Drizzle with MySQL, you need three packages: dotenv for managing environment variables, tsx for running TypeScript files, and mysql2 for querying your MySQL database.

Neon existing project setup steps

The steps to set up Drizzle ORM with Neon in an existing project are: (1) install @neondatabase/serverless package, (2) setup connection variables via DATABASE_URL environment variable, (3) setup Drizzle config file with postgresql dialect, (4) introspect your database, (5) transfer code to your actual schema file, (6) connect Drizzle ORM to the database, (7) query the database, (8) run index.ts file, (9) optionally update your table schema, (10) optionally apply changes to the database, (11) optionally query the database with new fields.

Neon existing project setup prerequisites

To set up Drizzle ORM with Neon in an existing project, you need three prerequisites: dotenv package for managing environment variables, tsx package for running TypeScript files, and Neon serverless Postgres platform.

Neon setup requires DATABASE_URL environment variable

When setting up Drizzle ORM with Neon, configure the DATABASE_URL environment variable to store your Neon database connection string.

Install @neondatabase/serverless package for Neon

To set up Drizzle ORM with Neon, install the @neondatabase/serverless package.

Neon driver options: neon-http vs neon-websockets

Drizzle ORM has native support for Neon connections with two drivers: neon-http and neon-websockets. Both drivers use the neon-serverless driver under the hood. The neon-http driver accesses a Neon database from serverless environments over HTTP, and is faster for single, non-interactive transactions. The neon-websockets driver provides WebSocket-based access. If you need session or interactive transaction support, or a fully compatible drop-in replacement for the pg driver, use the WebSocket-based neon-serverless driver. You can also connect to a Neon database directly using the Postgres driver.

Prerequisites for Gel with Drizzle

Before starting a Gel project with Drizzle, install tsx (package for running TypeScript files) and gel-js (package for querying Gel database).

Gel migration creation and application

Create a Gel migration file with: gel migration create. Apply Gel migrations to the database with: gel migration apply

Gel table definition example

A Gel table is defined using gelTable with table name and column definitions. Columns can have default values (e.g., sql`uuid_generate_v4()`), constraints like primaryKey() and notNull(), and indexed definitions. Example: gelTable("users", { id: uuid().default(sql`uuid_generate_v4()`).primaryKey().notNull(), age: smallint(), email: text().notNull(), name: text() }, (table) => [ uniqueIndex("...").using("btree", table.id.asc().nullsLast().op("uuid_ops")) ])

Gel project initialization command

To initialize a new Gel project, run: gel project init

Generated Gel schema imports

Generated Drizzle schema for Gel uses imports from drizzle-orm/gel-core: gelTable, uniqueIndex, uuid, smallint, text. The sql helper is imported from drizzle-orm.

Gel schema definition in esdl

Gel schemas are defined in dbschema/default.esdl files. A basic Gel schema module contains type definitions with fields. Fields can be marked as required. Example: a user type with name (str), required email (str), and age (int16) fields.

Gel setup file structure for Drizzle

The basic file structure for a Gel project with Drizzle includes: a drizzle folder for generated schema, a src directory with index.ts for table definitions, drizzle.config.ts for configuration, package.json, and tsconfig.json. After Gel initialization and migration, the structure expands to include dbschema folder with migrations subfolder, default.esdl, scoping.esdl, and edgedb.toml.

Connect Drizzle to Gel database

Import drizzle from drizzle-orm/gel and createClient from gel. Create a Gel client with createClient() and pass it to drizzle() to initialize the database connection. Example: const gelClient = createClient(); const db = drizzle({ client: gelClient });

Install Drizzle with Gel support

Install drizzle-orm@rc gel -D drizzle-kit@rc tsx to add Drizzle ORM with Gel database support and required development dependencies.

Gel table type inference

Drizzle provides typeof table.$inferInsert to infer the insert type for a table, which includes all the column types defined in the table schema.

Getting started workflow with Node:SQLite and existing database

The workflow for integrating Drizzle ORM with an existing Node:SQLite database includes: installing required packages, setting up connection variables, configuring Drizzle, introspecting the existing database, transferring introspected code to the schema file, connecting Drizzle to the database, and querying the database. Optionally, you can update your table schema and apply changes.

Node:SQLite setup packages to install

For Drizzle ORM with Node:SQLite, install drizzle-orm@rc and dotenv as dependencies, and drizzle-kit@rc and tsx as dev dependencies.

Node:SQLite prerequisites

To use Drizzle ORM with Node:SQLite, you need node v22.5.0 or higher and node:sqlite, which is a native implementation of a high-performance SQLite3 driver.

Node:SQLite environment variable for database file

Configure a DB_FILE_NAME environment variable to specify the path to your SQLite database file. For example, DB_FILE_NAME=mydb.sqlite creates a database file in the project root.

Nile database built-in tables included in introspection

When introspecting a Nile database with drizzle-kit pull, Nile's built-in tables such as the tenants table are included in the generated schema. These tables allow operations like creating new tenants and listing existing tenants.

Environment variable NILEDB_URL for Nile connection

The Nile database connection string is configured using the NILEDB_URL environment variable in the drizzle config file.

Nile environment variable for connection

Set the NILEDB_URL environment variable to configure the connection to Nile database.

Nile schema example with tenant-aware tables

Create a schema.ts file with tenant-aware tables for Nile multi-tenant apps. Example schema with tenantsTable and todos table: ```typescript import { pgTable, uuid, text, timestamp, varchar, vector, boolean } from "drizzle-orm/pg-core" import { sql } from "drizzle-orm" export const tenantsTable = pgTable("tenants", { id: uuid().default(sql`public.uuid_generate_v7()`).primaryKey().notNull(), name: text(), created: timestamp({ mode: 'string' }).default(sql`LOCALTIMESTAMP`).notNull(), updated: timestamp({ mode: 'string' }).default(sql`LOCALTIMESTAMP`).notNull(), deleted: timestamp({ mode: 'string' }), }); export const todos = pgTable("todos", { id: uuid().defaultRandom(), tenantId: uuid("tenant_id"), title: varchar({ length: 256 }), estimate: varchar({ length: 256 }), embedding: vector({ dimensions: 3 }), complete: boolean(), }); ```

Nile database setup prerequisites

To get started with Drizzle ORM and Nile, you need dotenv package for managing environment variables, tsx package for running TypeScript files, and Nile which is PostgreSQL re-engineered for multi-tenant apps.

Install postgres package for Nile connection

For connecting to Nile, install the 'pg' package as the main library and '@types/pg' as a dev dependency.

PGlite get started prerequisites

To get started with Drizzle and PGlite, you need the dotenv package for managing environment variables, the tsx package for running TypeScript files, ElectricSQL, and the pglite driver from electric-sql/pglite.

PGlite package to install

The PGlite driver package to install is @electric-sql/pglite.

PGlite setup steps overview

Getting started with Drizzle and PGlite involves: installing packages including @electric-sql/pglite, setting up DATABASE_URL environment variable, connecting Drizzle ORM to the database, creating a table, setting up a Drizzle config file with postgresql dialect, applying changes to the database, seeding and querying the database, and running the index.ts file.

PostgreSQL get started prerequisites

The PostgreSQL get started guide requires dotenv package for managing environment variables, tsx package for running TypeScript files, and node-postgres package for querying PostgreSQL database.

PostgreSQL native driver support

Drizzle has native support for PostgreSQL connections with node-postgres and postgres.js drivers.

PostgreSQL get started setup steps

To set up Drizzle with PostgreSQL: (1) Install node-postgres package with types, (2) Setup connection variables via DATABASE_URL environment variable, (3) Connect Drizzle ORM to the database, (4) Create a table, (5) Setup Drizzle config file with postgresql dialect, (6) Apply changes to database using drizzle-kit, (7) Seed and query the database, (8) Run the TypeScript file with tsx.

PostgreSQL setup prerequisites

To set up Drizzle ORM with PostgreSQL in an existing project, you need three prerequisite packages: dotenv for managing environment variables, tsx for running TypeScript files, and node-postgres for querying your PostgreSQL database.

Give your agent this brain