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

database connections & drivers

99 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Drizzle ORM v0.11.0 supported databases

Drizzle ORM v0.11.0 released on 2022-07-20 supports PostgreSQL, with MySQL and SQLite support about to be released.

Connect to PostgreSQL database in v0.11.0

Connection to PostgreSQL is established with drizzle.connect(connectionString). Example: const db = await drizzle.connect('postgres://user:password@host:port/db'). Returns a database connection object used to instantiate table classes.

Postgres.js driver support

Drizzle ORM v0.16.2 added full support for postgres.js driver. To use it, import the drizzle function and PostgresJsDatabase type from drizzle-orm-pg/postgres.js, create a postgres client with postgres(connectionString), and pass it to drizzle(client). Example: import { drizzle, PostgresJsDatabase } from "drizzle-orm-pg/postgres.js"; import postgres from "postgres"; const client = postgres(connectionString); const db: PostgresJsDatabase = drizzle(client);

mysql2 driver requires mode config for relational queries in v0.28.0

When using the mysql2 driver with Drizzle relational queries, you must specify a mode configuration. For regular MySQL databases, use mode: "default". For PlanetScale, use mode: "planetscale". This is required because PlanetScale does not support lateral joins of subqueries that Drizzle uses for relational queries.

mysql2 mode planetscale configuration example

When connecting to PlanetScale with mysql2, pass mode: 'planetscale' to the drizzle function. Example: const db = drizzle({ client, schema, mode: 'planetscale' });

D1 test suite additions

Version 0.28.2 added a set of tests for D1 (Cloudflare's SQL database).

MySQL timestamp milliseconds truncation fixed

Version 0.28.2 resolved an issue where timestamp milliseconds were being truncated for MySQL.

SQLite .get() method type corrected

Version 0.28.2 corrected the type of the .get() method for sqlite-based dialects, addressing issue #565.

SQLite-proxy double execution bug fixed

Version 0.28.2 fixed a sqlite-proxy bug that caused queries to execute twice.

Fixed sqlite-proxy and SQL.js .get() empty result handling

In v0.28.3, fixed the response from .get() method in sqlite-proxy and SQL.js when the result is empty.

SQLite simplified query API added in v0.28.3

Drizzle ORM v0.28.3 added a simplified query API for SQLite.

PostgreSQL Proxy Driver usage example

Example of PostgreSQL Proxy Driver implementation: ```ts import axios from 'axios'; import { eq } from 'drizzle-orm/expressions'; import { drizzle } from 'drizzle-orm/pg-proxy'; import { migrate } from 'drizzle-orm/pg-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}/query`, { queries }); } catch (e) { console.log(e); throw new Error('Proxy server cannot run migrations'); } }, { migrationsFolder: 'drizzle' }); const insertedCity = await db.insert(cities).values({ id: 1, name: 'name' }).returning(); const insertedUser = 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)); } ```

withReplicas function for read replicas

The withReplicas function allows you to specify different database connections for read replicas and a main instance for write operations. By default, withReplicas uses a random read replica for read operations and the main instance for data modification operations. You can also specify custom logic for choosing which read replica to use.

Read replicas basic usage example

Example of using withReplicas with random replica selection: ```ts const primaryDb = drizzle({ client }); const read1 = drizzle({ client }); const read2 = drizzle({ client }); const db = withReplicas(primaryDb, [read1, read2]); // read from primary db.$primary.select().from(usersTable); // read from either read1 or read2 db.select().from(usersTable) // use primary database for write operation db.delete(usersTable).where(eq(usersTable.id, 1)) ```

Custom logic for read replica selection

Example of custom weighted logic for selecting read replicas: ```ts 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]! }); ```

withReplicas available for all dialects

The withReplicas function is available for all dialects in Drizzle ORM.

MySQL Proxy Driver implementation

A new MySQL Proxy Driver allows you to create your own HTTP driver implementation for MySQL databases. You must implement two endpoints: one for queries and one for migrations (the migrate endpoint is optional and only needed if using Drizzle migrations). Both server and driver implementation are customizable, allowing for custom mappings, logging, and more. Examples are available in ./examples/mysql-proxy folder.

PostgreSQL Proxy Driver implementation

A new PostgreSQL Proxy Driver allows you to create your own HTTP driver implementation for PostgreSQL databases. You must implement two endpoints: one for queries and one for migrations (the migrate endpoint is optional and only needed if using Drizzle migrations). Both server and driver implementation are customizable, allowing for custom mappings, logging, and more. Examples are available in ./examples/pg-proxy folder.

Fix withReplica feature argument forwarding

In Drizzle ORM v0.29.1, a bug was fixed where arguments were not being forwarded correctly when using the withReplica feature. This was addressed in pull request #1536.

Expo SQLite basic usage

The Expo SQLite driver is used by importing drizzle from 'drizzle-orm/expo-sqlite' and openDatabaseSync from 'expo-sqlite'. Create the database with openDatabaseSync('db.db'), then initialize Drizzle with drizzle(expoDb). Queries can be executed with await db.select().from(...), promise-based db.select().from(...).then(...), or synchronous db.select().from(...).all().

Expo SQLite driver installation

To use the Expo SQLite driver with Drizzle ORM v0.29.2, install the packages using: npm install drizzle-orm expo-sqlite@next

Drizzle supports Expo SQLite

Drizzle ORM supports Expo SQLite as a database option. Documentation is available for getting started with Expo SQLite and Drizzle.

Expo peer dependencies made optional in v0.29.3

In Drizzle ORM v0.29.3, Expo peer dependencies were made optional through pull request #1714. This change was released on January 2, 2024.

PlanetScale migration from connect() to Client

In v0.29.4, passing `connect()` result to drizzle triggers a deprecation warning. Starting from v0.30.0, using anything other than a Client instance will cause a runtime error. Users should migrate existing PlanetScale connections to use `new Client()` now to prevent future breakage.

PlanetScale Client instance required

For PlanetScale connections, use `new Client()` instance instead of `connect()`. Import Client from '@planetscale/database', create an instance with host, username, and password configuration, then pass it to `drizzle()`. The `connect()` function is deprecated as of v0.29.4 and will cause an error starting in v0.30.0.

SQLite Proxy batch callback configuration

To enable batch support with SQLite Proxy, pass a second callback parameter to drizzle() that receives an array of query objects. Each query object has sql (string), params (any[]), and method ('all' | 'run' | 'get' | 'values') properties. The callback should POST the queries array to your proxy server and return a ResponseType array of { rows: any[][] | any[] } in the same order as sent.

SQLite Proxy batch and relational queries support

SQLite Proxy driver now supports batch requests and relational queries. You can use .query.findFirst and .query.findMany syntax with sqlite proxy driver, and use db.batch([]) method to proxy all queries through the batch callback.

SQLite Proxy batch callback example

Example of SQLite Proxy batch configuration: const db = drizzle(async (sql, params, method) => { /* single query logic */ }, async (queries: { sql: string; params: any[]; method: 'all' | 'run' | 'get' | 'values'; }[]) => { try { const result: ResponseType = await axios.post('http://localhost:3000/batch', { queries }); return result; } catch (e: any) { console.error('Error from sqlite proxy server:', e); throw e; } });

SQLite Proxy batch response format requirement

The response from the batch callback must be an array of raw values (an array within an array) in the same order as the queries were sent to the proxy server.

postgres.js driver date handling change in v0.30.0

In Drizzle ORM v0.30.0, the postgres.js driver instance was modified to always return strings for dates, and then Drizzle provides either strings or mapped dates depending on the selected mode. When you provide a postgres.js driver instance to Drizzle, the behavior of that object will change for dates, which will always be strings in the response. For both timestamps with timezone and without timezone, the mapping uses .toISOString.

postgres.js parser override for date types

The postgres.js driver date parsers were changed by overriding the default date parsers for type codes 1184 (timestamp with time zone), 1082 (date), 1083 (time without time zone), and 1114 (timestamp without time zone). A transparent parser that returns values unchanged was applied to both the parsers and serializers for these types.

postgres.js driver mutation side effect

If you use the postgres.js driver outside of Drizzle and pass postgres.js clients to Drizzle, all dates will be strings in the response, resulting in mutated behavior of the postgres.js client. This is a side effect of how Drizzle currently needs to handle date parsing for this driver.

OP-SQLite driver support in Drizzle ORM v0.30.1

Drizzle ORM v0.30.1 added support for the OP-SQLite driver. To use it, import the open function from '@op-engineering/op-sqlite', open a database with a name parameter, and pass it to drizzle(). The example shows: import { open } from '@op-engineering/op-sqlite'; import { drizzle } from 'drizzle-orm/op-sqlite'; const opsqlite = open({ name: 'myDB' }); const db = drizzle(opsqlite); await db.select().from(users);

OP-SQLite driver setup

To use OP-SQLite driver with Drizzle ORM, import from 'drizzle-orm/op-sqlite' and pass an opened database connection from '@op-engineering/op-sqlite' to the drizzle() function.

AWS DataAPI session methods bug fix

DrizzleORM v0.30.10 fixed internal mappings for the .all(), .values(), and .execute() functions in AWS DataAPI sessions.

bun:sqlite findFirst query fix in v0.30.2

Version 0.30.2 of Drizzle ORM fixed a bug with the findFirst query for bun:sqlite driver.

Fixed @neondatabase/serverless HTTP driver types issue

v0.30.3 fixed a types issue in the @neondatabase/serverless HTTP driver.

Raw query support in Neon HTTP driver batch API

As of v0.30.3, the Neon HTTP driver batch API supports raw query execution using db.execute(...).

Fixed sqlite-proxy driver .run() result

v0.30.3 fixed the .run() result in the sqlite-proxy driver.

Xata connection methods

Drizzle ORM supports three methods for connecting to a Xata Postgres database: the native xata driver via the drizzle-orm/xata package, or the postgres driver, or the pg driver.

Xata driver support in Drizzle ORM

Drizzle ORM v0.30.4 added native support for the Xata driver. Xata is a Postgres data platform focused on reliability, scalability, and developer experience. The Xata Postgres service is in beta.

Xata HTTP driver setup

To use the Xata HTTP driver, install drizzle-orm and @xata.io/client packages, generate a Xata client using the xata init CLI command, then import the drizzle function from drizzle-orm/xata-http, pass the generated Xata client to drizzle(), and use the resulting db instance with select().from() and other query builder methods.

Xata HTTP driver example

Example of connecting to Xata with the HTTP driver: 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(...);

PGlite driver import and usage

To use PGlite with Drizzle ORM, import PGlite from '@electric-sql/pglite' and import the drizzle function from 'drizzle-orm/pglite'. Create a new PGlite instance for an in-memory Postgres database, then pass it to the drizzle function to get a database client. The resulting db client can be used with Drizzle query methods like select().from().

PGlite driver support in Drizzle ORM v0.30.6

Drizzle ORM v0.30.6 added support for the PGlite driver. PGlite is a WASM Postgres build packaged into a TypeScript client library that enables running Postgres in the browser, Node.js, and Bun without installing other dependencies. It is 2.6mb gzipped and can be used as an ephemeral in-memory database or with persistence to the file system (Node/Bun) or indexedDB (Browser). PGlite does not use a Linux virtual machine but is Postgres compiled to WASM.

@vercel/postgres package mappings added

Drizzle ORM v0.30.7 added mappings for the @vercel/postgres package to support Vercel Postgres as a database driver.

Neon driver interval mapping fix

Drizzle ORM v0.30.7 fixed interval mapping for neon drivers in issue #1542.

AWS Data API driver multiple issues fixed

Multiple issues with the AWS Data API driver have been fixed, including problems with inserting and updating array values.

db._.fullSchema provides schema information

Drizzle instances now expose schema information via the db._.fullSchema property, which provides access to the full schema definition that was used to create the database instance.

useLiveQuery React Hook for Expo SQLite

As of v0.31.1, Drizzle ORM provides native support for Expo SQLite Live Queries through a useLiveQuery React Hook. The hook observes necessary database changes and automatically re-runs database queries. It works with both SQL-like queries (db.select().from(users)) and Drizzle relational queries (db.query.users.findFirst(), db.query.users.findMany()). The hook returns an object with data, error, and updatedAt fields for explicit error handling.

Enable change listeners in Expo SQLite for Live Queries

To use Live Queries with Expo SQLite in Drizzle ORM, you must open the database with the enableChangeListener option set to true. For example: openDatabaseSync('db.db', { enableChangeListener: true }). This enables the change listener that Live Queries depend on to detect database modifications.

useLiveQuery returns object with data, error, and updatedAt

The useLiveQuery hook returns an object containing three fields: data (the query result), error (any error that occurred), and updatedAt (timestamp of the last update). This follows the practices established by React Query and Electric SQL for explicit error handling.

useLiveQuery example with Expo SQLite

```tsx import { useLiveQuery, drizzle } from 'drizzle-orm/expo-sqlite'; import { openDatabaseSync } from 'expo-sqlite'; import { users } from './schema'; import { Text } from 'react-native'; const expo = openDatabaseSync('db.db', { enableChangeListener: true }); const db = drizzle(expo); const App = () => { const { data } = useLiveQuery(db.select().from(users)); return <Text>{JSON.stringify(data)}</Text>; }; export default App; ``` This example demonstrates how to use useLiveQuery with both SQL-like queries and relational queries (db.query.users.findFirst(), db.query.users.findMany()).

useLiveQuery hook API design rationale

Drizzle ORM intentionally maintains a conventional React Hook API for useLiveQuery, using useLiveQuery(databaseQuery) rather than db.select().from(users).useLive() or db.query.users.useFindMany(). This design decision keeps the API consistent with standard React Hook conventions.

drizzle-kit PostgreSQL SSL configuration options

Drizzle Kit v0.22.0 expands PostgreSQL SSL configuration to support full set of node:tls connection options. SSL parameter in dbCredentials can be: true (default), 'require', 'allow', 'prefer', 'verify-full', or an object with options from node:tls. Example: defineConfig({ dialect: 'postgresql', dbCredentials: { ssl: true } }).

drizzle-kit MySQL SSL configuration options

Drizzle Kit v0.22.0 allows MySQL SSL parameter in dbCredentials to be a string or SslOptions object from the mysql2 package. Example: defineConfig({ dialect: 'mysql', dbCredentials: { ssl: '' } }).

drizzle-kit normalized libsql and better-sqlite3 URLs

Drizzle Kit v0.22.0 normalizes SQLite file paths for libsql and better-sqlite3 drivers. These drivers have different file path patterns, but Drizzle Kit now accepts both patterns and creates the proper file path format for each driver automatically.

TiDB Cloud Serverless driver support

Drizzle ORM v0.31.2 added support for TiDB Cloud Serverless driver. Import the connect function from '@tidbcloud/serverless', call connect() with a url configuration to get a client, then pass it to drizzle() from 'drizzle-orm/tidb-serverless' to create a database instance.

TiDB Cloud Serverless setup example

import { connect } from '@tidbcloud/serverless'; import { drizzle } from 'drizzle-orm/tidb-serverless'; const client = connect({ url: '...' }); const db = drizzle(client); await db.select().from(...);

Prisma-Drizzle extension basic usage

The Prisma-Drizzle extension allows using Drizzle query builder within a Prisma client. Import PrismaClient from '@prisma/client', import drizzle from 'drizzle-orm/prisma/pg', and call $extends(drizzle()) on the client. Then access Drizzle queries via prisma.$drizzle, for example: const users = await prisma.$drizzle.select().from(User);

Give your agent this brain