Repository navigation
Releases
v1.0.0-rc.5
ORM
- [BREAKING] Fixed
postgres-jstransparent parsers set bydrizzle()constructors breaking driver's own serializers fortimestamptz,timestamp,date,time,json,jsonbtypes (fixes #3171, #4426, #5789) paramsInErrors
❗ Any existing workarounds with manualJSON.stringify(jsonValue)in raw sql or raw driver calls must be removed to prevent double stringification of JSON params; For array-type JSON params insqlusesql.param(jsonArrayValue)to avoid it being parsed as value list instead of param. - [BREAKING] Restricted
undefinedvalue passed to fields in relational queries'where- now throws an error upon encounteringundefinedin filters, addedEmptyFiltersymbol (import { EmptyFilter } from 'drizzle-orm/relations') that can be used as an explicit replacement ofundefinedwhere possibly absent filter is desired by design rather than possible bug (fixes #5636)
Example:db.query.users.findMany({ where: { isActive: params.isActive ?? EmptyFilter } })
- [BREAKING] Relation filters without conditions (
{}, or containing only empty conditions) are now skipped like any other empty filter instead of generatingexists (...)check of relation's presence - usetrueto filter by relation's presence,false- by its absence
Example:// Previously: `where exists (select * from "posts" ...)`, now: no filter db.query.users.findMany({ where: { posts: {} } }) // Users with at least one post db.query.users.findMany({ where: { posts: true } })
- [BREAKING] Updated
postgrescodecs: now generic codecs contain only in-json codecs (mirroringmysql), contents of drivers' codecs remain unchanged - [BREAKING] Switched
pgbyteain-json codecs fromencode(..., 'base64')casts to decodingto_json's native hex output - [BREAKING] Made nested select join nullification consider
SQLfield data during nullification - [BREAKING] Fixed
sqliteignoring.$defaultFn(...)on insert when.default(...)is present - [BREAKING] Untied
bun-sql/mysql,mysql2,singlestorecolumn mapping from connection config, removed forcedbigintparams on their respective configs, replaced with more stablecastcodecs - [BREAKING] Reworked
cockroachcolumn builders to mirrorpg- now both have same.array('[][]...')syntax - [BREAKING] Moved
Viewexports fromdrizzle-orm/sql/sqltodrizzle-orm/view - [BREAKING]
getTableUniqueNameno longer prefixes aliased views or tables with theirschema - [BREAKING]
getTableUniqueNameno longer setspublic.prefix for entities withoutschema - [BREAKING] Updated
Viewclass: switched toTable-like object config for type template, typedschemaproperty - [BREAKING] Updated
withReplicas(indirectly fixes #4185):- Now every query goes to primary db by default
- To query replica, explicitly call
db.$replica
- [BREAKING] Added
withCastCodecs = falseswitch togetSQL(),withCastCodecs = trueswitch totoSQL()of non-relational query builders - nowdb.select(...).from(...).getSQL()emits query without cast codecs by default - [BREAKING] Reworked
sqlite-proxy:- Added
rowMode: 'array' | 'object'switch for'all' | 'get'execute methods - Dropped
{ rows: Result[] }callback result wrapping - now expected direct return of expected data - Replaced
callback,batchCallbackwithSqliteProxyExecutorsobject - must providerun,all,gethandlers & optionalbatchhandler - Dropped
valuesexecute method due to it being duplicate of array-modeall - Added
TRunResulttype inferrence based on return type ofrunexecutor, updatedSqliteRemoteDatabasetemplate withTRunResultargument - Added per-item
rowMode: 'array' | 'object'tobatch,batchis expected to mirror executors' return types per query
- Added
- [BREAKING] Fixed runtime-type expected result mismatch for
get(data | undefinedin runtime,data[]in types) (fixes #5461, #3394) - [BREAKING] Fixed
sqlitedb.get(sql)return type lacking| undefinedfor queries without returned rows - [BREAKING] Omitted query
paramsfromDrizzleQueryErrorby default, addedparamsInErrorsoption todrizzleconstructor to enable queryparamsinDrizzleQueryError(fixes #5939)
Example:const db = drizzle({ connection: 'postgres://...', paramsInErrors: true })
- [BREAKING] For
mysql,postgres,cockroach,mssqlset RQBv2 to new query build strategy to fix slow query plans (fixes #5245)
Can be opted out of per query viastrategyswitch:db.query.findMany({ strategy: 'basic' })
When used, may break direct references to relations in raw SQL syntaxwhere,orderBy:// posts with the most comments first db.query.posts.findMany({ with: { author: true, comments: true }, orderBy: (t, { sql }) => sql`json_array_length("comments"."r") desc, ${t.id}`, // "comments" becomes unreachable due to query nesting limit: 2, }); // posts of verified authors db.query.posts.findMany({ with: { author: true }, where: { RAW: (t, { sql }) => sql`("author"."r"->>'verified')::boolean` }, // "author" becomes unreachable due to query nesting });
- [BREAKING] Moved
StringChunk,commonStringChunksexports fromdrizzle-orm/sql/sqltodrizzle-orm/sql/common-chunks(still exported fromdrizzle-orm/sql) - [BREAKING] Switched RQBv2 build functions to chunk collection: each accepts optional trailing
collectTo: SQLChunk[]array to push chunks to and returns chunk arrays instead ofSQL
❗ Chunk arrays embedded intosqldirectly are rendered as value lists - wrap them innew SQL(chunks)to use them as query partsrelationsFilterToSQL(...).sql:SQL | undefined->SQLChunk[] | undefined, addedcollectToparameterrelationsOrderToSQL(...):SQL | undefined->SQLChunk[] | undefined, addedcollectToparameterrelationsOrderEntriesToSQL(...): replacedparts: SQL[]parameter withcollectTo: SQLChunk[],start?: number;RelationsOrderSource'sfrom,filtersare nowSQLChunk[],SQLChunk[][]relationExtrasToSQL(...).sql:SQL | undefined->SQLChunk[] | undefined, addedcollectToparameterrelationToSQL(...):{ filter?: SQL; joinCondition?: SQL }->{ filter: SQLChunk[]; joinCondition?: SQLChunk[] }, addedfilterTo,joinConditionToparametersgetTableAsAliasSQL(...):SQL->SQLChunk[], addedcollectToparameter
- [BREAKING] Relational queries are now cached by caches with
allstrategy (global: true), opt out per query viawithCache: false - [BREAKING] Replaced
DBQueryConfigWithCommenttype withDBQueryConfigRoot- config of root relational query containing all root-only options (strategy,comment,withCache); dialects' relational query builders accept it with options they don't support omitted - Updated RQB filters to allow branded types in shortcut-form
eqfilter (fixes #5298) - Fixed
$onUpdateFnbeing executed without need (fixes #5780) - Fixed
$onUpdateFnpotentially overriding explicitnulls - Fixed
zodschema generator returningunknown-templated coerced types (fixes #5659) - Fixed
mysql2constructor setting param in potentially undefined mistyped config (fixes #5972) - Fixed non-jit mapper nullification triggering on single null column (fixes #1603)
- Preserved qualifiers for column chunks of
sqlfields in selection when non-current table's column is referenced (fixes #5734) - Optimized query building, mapper generation
- Allowed empty returns in callback-style
orderBy,extras,RAWof relational queries - Removed unused
_field inRelationsHelperStatic - Fixed naming:
isReversedtoisFilterReversedinRelation objects,arraysdb.executemodes (db.all,db.getinsqlite) (bypasses #4464)- Fixed jit mapper nullifying nested selection objects with columns from different tables
- Fixed selection group nullification not triggering on objects with deeply nested fields (joined view or subquery)
- Fixed
geometry,geography&boxarray types data getting reduced to one item due to wrong delimiter used duringpgArrayconstruction\parsing - Added delimiter customization to
makePgArray,parsePgArrayutilities - Optional explicit column lists for
db.insert(workaround for #5001, #5309)- Usage:
db.insert(users, 'name', 'email').values([{ name: 'First', email: '[email protected]' }, { name: 'Second', email: '[email protected]' }])
- Usage:
- Transaction snapshot support for
pgdialect - Fixed
pgtransaction config related errors on empty but present config (fixes #1772) - Supported transaction config in effect
pgdrivers - Bump
tursodatabaselibrary versions - Supported transaction configs for
tursodatabasedrivers - Fixed
mysqltransaction options being joined on wrong separator - Supported
isolationLevelinbun-sql/mysqltransactions - Removed transaction config from
effect-sqlite,effect-mysqldue to lack of support in drivers - Explicit error throws on unsupported transaction configs
- Partial transaction config support for
libsql,tidbdrivers - Improved error messages on unknown fields in RQBv2 selection (fixes #5367)
- Fixed
op-sqlitetransaction being handled as synchronous - Fixed broken
op-sqlitequery executors (fixes #5936) - Bumped
op-sqliteto v17 (fixes #5928) - Fixed
expo-sqlitenot finalizing prepared statements - Added
expo-sqlite/asyncfor async querying (fixes #5240) - Added local
sha256hash function as a fallback for cache query hashing in environments withoutglobalThis.cryptoavailable - Fixed dynamic query builders blocking query builder's variable reassignment after applying nullable joins by defaulting to
not-nullbehavior on not yet...
0.45.4
0.45.3
New Netlify DB Driver
Note: The Netlify DB driver is developed and maintained by the Netlify team.
Installation:
npm i @netlify/dbUsage example:
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');import { drizzle } from 'drizzle-orm/netlify-db';
const db = drizzle(process.env.DATABASE_URL);
const result = await db.execute('select 1');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');[email protected]
- Warn about silent migration skips on drizzle-kit checks - thanks @shaneikennedy
v1.0.0-rc.4
v1.0.0-rc.4
- Fixed broken
Viewtypes when usingSubqueryin selection - Fixed custom types' JSON field API not being applied when column is used as a decoder on
SQLfields - Fixed codecs not getting applied to
SQLfield when.mapWith(column)is set (fixes #5724) - Fixed
Subqueryfields' columns' codecs not being applied to subquery - Fixed broken in
rc.3db.selectinbun-sql/pgdriver (fixes #5779) - Updated SQLite
db.$countbuilder to include.sync()executor for sync drivers - Removed RQBv1 from
sqlite, removed RQBv1TSchema,TFullSchemaarguments fromsqliteentities' generics - Fixed instances of
sqlitequery errors not being wrapped inDrizzleQueryError(db.batch()excluded due to api incompatibility) - Fixed type error on
CockroachArrayBuilderconstructor caused by referencing internal field's type - Removed
mapResultmethod fromPreparedQueryinterface, removedmapResult,mapBatchResultfrompgandsqliteraw queries - Fixed wrong
bun-sqliterun result type - Switched
sqliteRQBv2 to array mode - Enabled optimized default query mappers for
sqlite - Reworked
sqlitesessions: replaced per-driverPreparedQueryinstances with executors passed via sessions, similar to currentpostgresqlandmysqlimplementations, moveduseJitMappersflag handling to dialect - Fixed missing
stringoverload on.comment(sqlCommenterComment)in query builders - Supported nested transactions in
@tursodatabase/database,@tursodatabase/database-wasm - Added filesytem-less migrator for
@tursodatabase/database-wasmatdrizzle-orm/tursodatbase/wasm-migrator - Split SQLite into
async,effectversions (syncremains subtype ofasync) - Removed
SQLiteSyncDialect,SQLiteAsyncDialect, moved generic SQLiteasync\syncmigrators tosqlite-core/async/sessionasmigrateSync,migrateAsync - Fixed
sqlitecache using same cache entry for different execute methods - Moved
EffectDrizzlePgConfigtodrizzle-orm/pg-core/effect/utils - Made
cachefield inEffectCacheShapeoptional - Split
mysqlintoasync,effectversions - Added codec system to
mysql - Fixed
mysqlfloatrounding to either 6 digits or double - Fixed
mysqlcropping.000fromtimestamp(3) - Moved subquery mapper selection from
dialect.buildSelectiontoorderSelectedFields; - [
PG,MySQL] Improved codec system in set operators:- When different db types are crossed in a union, db casts them to type it deems as closest compatible to all types involved
- If columns with codecs are set on both sides of union - codec of combined type will apply
- If only the left-hand side of union has field with codec - left hand side's codec is preserved
- If left-hand side field is devoid of codecs - field is not processed by codecs;
- Set operator queries are switched from
[QUERY 1] UNION [QUERY 2]toSELECT ... FROM ([QUERY 1] UNION [QUERY 2]) "drizzle_union"so cast codecs would apply after union's type mutation - Retrieved data of union with different types still may be lossy due to db's own conversion
- Bump required
effectpackage versions to4.0.0-beta.83 - Fixed
sql.parampassingPlaceholderas expected input value to encoder function instead ofPlaceholder's value type - Fixed unguarded
Bufferreference indrizzle-orm/effect-schemathat caused error in environments withoutBuffer - Fixed
sqliteblobcolumn runtime-type default mode mismatch (fixes #1064) - Improved typed
sqloperator - preserved nullability, inferred initial data type tomapWithcallback argument, added.nullable()method to modify output type with| null(fixes #571):// Before: sql<Type | null>`...`.mapWith((v: any) => String(v)) // Output type: string // After: sql<Type | null>`...`.mapWith((v: Type) => String(v)) // Output type: string | null // `.nullable()` method: sql`...`.mapWith((v: unknown) => new Type(v)).nullable() // Output type: Type | null
- Fixed
generatedByDefaultAsIdentitycolumns not being filtered from inserts in runtime inpostgresdialect - Improved
db.insert(table).select(...): removed column order match requirement, allowed skipping selection for columns with defaults or nullability (fixes #3608)
Drivers
-
Updated
@tursodatabase/database,@tursodatabase/database-wasmto v0.6.0, updated session internals for asynchronous prepare on driver side -
Added
@tursodatabase/serverlessdriver support -
Added
@tursodatabase/syncdriver support -
Added
@effect/sql-pglitedriver support -
Added
@effect/sql-sqlite-nodedriver support -
Added
@effect/sql-sqlite-bundriver support -
Added
@effect/sql-sqlite-dodriver support -
Added
@effect/sql-sqlite-wasmdriver support -
Added
@effect/sql-libsqldriver support -
Added
@effect/sql-d1driver support -
Added
@effect/sql-mysql2driver support -
Fixed
@effect/sql-pgdriver returning object response instead of raw response ondb.execute -
pg-proxy: added dialect config to optional dialect creator callback -
Fixed postgres pull from failing for non-admin roles (fixes #5568)
Drizzle Kit
Machine-readable output & programmatic SDK
- Added an
--output text|jsonmode togenerate,push,pull,up,export, andcheck. Injsonmode each command emits a typed JSON envelope (status, errors, payloads) for programmatic and agent consumption (see OUTPUT_MODES.md, JSON_CONTRACT.md) - Shipped a public programmatic SDK at the
drizzle-kit/clisubpath exposinggenerate(),push(),pull(),up(),exportSql(), andcheck()with typed options and results matching the CLI JSON contract (see SDK.md) - Auto-detected non-interactive mode (
--output json, or--output textwith a non-TTY stdin) no longer renders interactive prompts. Instead, unresolved renames and destructive changes (confirm_data_loss) are surfaced as amissing_hintsenvelope (or a missing-decisions report undertext) and resolved by supplying a structuredhintsarray up front via--hints/--hints-file(see HINTS.md)
MCP server
- Added
drizzle-kit mcp, a Model Context Protocol server over stdio that exposes the migration lifecycle (generate,push,check,export,up,pull) as MCP tools for any MCP-capable AI agent (see MCP.md)
Agent skills
- Added
drizzle-kit skills, which installs Drizzle Kit's bundled Agent Skills into your project for AI coding assistants. Ships 8 skills:drizzle,drizzle-generate,drizzle-hints,drizzle-migrations,drizzle-output-modes,drizzle-pull,drizzle-push, anddrizzle-responses-and-errors(seedrizzle-kit/skillsfolder)
v1.0.0-rc.3
v1.0.0-rc.3
Porting all the changes that were made in PostgreSQL to other dialects. This release is about MySQL:
- Removed RQBv1 from
mysqldialect (._query) - Internal MySQL sessions refactoring and moving to a unified query preparation function
- Fallback to regular queries on iterators for drivers that don't support streaming instead of throwing an error for compatibility
- Enabled optimized non-jit mappers for regular queries for MySQL dialect
- Switched RQBv2 to array mode querying, disabled root query level JSON conversions
- Fixed MySQL proxy driver not using
lastInsertId,affectedRowsfrom dedicated response fields
Next releases will include:
- Effect MySQL support
- SQLite rework (same as this release for MySQL)
- SQLite Effect Support
v1.0.0-rc.1
v1.0.0-rc.1
casing API(see below) and removes RQB v1 ._query for postgres
JIT mappers
Drizzle ORM now has an opt-in API for JIT(just in time compilated) mappers which make most expensive part of the db request pipeline(row mapping) as fast as humanly possible.
const db = drizzle({ ..., jit: true })
const query = db.select().from(users).prepare();
// ^ here drizzle generates a jit mapper which will then be reused during each invocation
server.get('users', (c) => {
const users = await query.execute(); // as fast as using raw driver
return c.json(users)
})We've reworked internals of Drizzle ORM with the new system of codecs. Those are now in charge of normalising responses and requests for diffrent drivers across pg dialect. They helped us not only properly fix a set of data mapping issues but also massively improve performance by not doing unnecessary work.
We've seen a 25%-30% reduction in latency, while +800rps(14500->15300) in our benchmarks
Give it a go and let us know if everything works just fine!
Effect v4
[email protected] comes with native support for Effect v4 via:
import { PgClient } from '@effect/sql-pg';
import * as PgDrizzle from 'drizzle-orm/effect-postgres';
import * as Effect from 'effect/Effect';
import * as Redacted from 'effect/Redacted';
import { relations } from '../relations';
const connectionStr = Redacted.make(process.env['PG_CONNECTION_STRING']!);
const PgClientLive = PgClient.layer({
url: connectionStr,
});
const DB = PgDrizzle.make({ relations }).pipe(Effect.provide(PgDrizzle.DefaultServices));
const program = Effect.gen(function*() {
const db = yield* DB;
const users = yield* db.select().from(usersTable);
}).pipe(Effect.provide(PgClientLive));
await Effect.runPromise(program);New Casing API
In rc.1 we've finally reworked our legacy casing API of const db = drizzle({..., casing: "camel" }) which turned out to not be a proper solution, it required duplication in drizzle-orm instantiation and drizzle-kit config and introduced and set of endless bugs all around query builder chain. All of the above is now fixed with new API:
import * as d from "drizzle-orm/pg-core";
const users = d.snakeCase.table("users", {
id: d.serial().primaryKey(),
email: d.text().unique(),
fullName: d.text(), // full_name in db
createdAt: d.timestamp().defaultNow(), // created_at in db
})
// --- for namespaces/schemas you can use
const schema2 = d.camelCase.schema("schema2");
const usersInSchema2 = schema2.table("users", ...);
const ordersInSchema2 = schema2.table("orders", ...);
// ^ all entities in schema2 will be snake_cased
// --- all available entities
import { snakeCase, camelCase } from "drizzle-orm/pg-core";
snakeCase.view
snakeCase.materializedView
snakeCase.schema
snakeCase.table
camelCase.view
camelCase.materializedView
camelCase.schema
camelCase.tableNew Netlify Database Driver
Note: The Netlify Database driver is developed and maintained by the Netlify team.
Installation:
npm install @netlify/databaseUsage example:
import { drizzle } from 'drizzle-orm/netlify-db';
const db = drizzle();
const result = await db.execute('select 1');import { drizzle } from 'drizzle-orm/netlify-db';
const db = drizzle(process.env.DATABASE_URL);
const result = await db.execute('select 1');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');Bug fixes and improvements:
- Codec system for
postgres- resolves issues created by differences of data types returned by different drivers or different contexts of query (regular select, JSON object, postgres array). Currently only handles supported by drizzle constructors column types. (fixes #3018, #5090, #5287) - Optimized query mappers for
postgres - Opt-in JIT-generated mappers for all dialects
- Optimized RQBv2 mappers for all dialects
⚠️ BREAKING CHANGE: Removed RQBv1 (db._query) frompostgres- Moved pg array utils (
makePgArray,parsePgArray) fromdrizzle-orm/pg-core/utils[/array]todrizzle-orm/pg-core/array - Simplified
postgressessions & prepared queries - Fixed
neon-httpbyteadata corruption - Fixed
bun-sql/postgrestimestamp timezone truncation,json[b]data double stringification ⚠️ BREAKING CHANGE: Reworked casing API - moved casing control fromdbinstance totable\view\schemaviaimport { snakeCase, camelCase } from "drizzle-orm/dialect-core", fixed #5112 #5282 #4181 #4209- Switched from Effect V3 to Effect V4 beta for
effect-schema,effect-postgres(fixes #5414)
v1.0.0-rc.2
Updates
- Disabled default codec type selectors for custom columns (fixes #5711)
- Сallback type overload for codec selector in custom pg columns (
codec: (config) => config?.withTimeZone ? 'timestamptz' : 'timestamp') - Extended list of postgis types for codecs (improvement for #5711)
- Updated codecs:
geometry->geometry(point),geometry:tuple->geometry(point):tuple - Switched PG transactions from class properties back to class methods (fixes #5709)
- Updated
AWS Data Apicodecs, removed query typings, improved input param mapping - Removed prepared query
typingsfield from all builders - Added
columnargument toCastParam,CastArrayParamcodecs
Migration updates in SQLite
- Added migration conflict detection for SQLite. When migration history has multiple open branches,
drizzle-kit generatenow checks whether those branches can be merged safely before creating the next migration. This helps catch cases where two migrations were created from the same parent and then changed the same SQLite object in incompatible ways, for example two branches changing the same table, index, or view.
npx drizzle-kit generate- If the conflict is expected and you want to continue anyway, pass
--ignore-conflictsto skip the conflict check for that command.
npx drizzle-kit generate --ignore-conflicts
npx drizzle-kit check --ignore-conflicts- Added proper SQLite migration tree merging. New snapshots now collect all open leaf snapshot IDs and write them as parents, instead of keeping only one latest parent. This means a new migration generated after branching can merge all open leaves and use the combined SQLite state for the next snapshot diff.
{
"prevIds": ["first-open-leaf-id", "second-open-leaf-id"]
}- Fixed
DrizzleQueryErrorandTransactionRollbackErrorconstructors to properly set the error name for better instanceof checks - Fixed error handling in aws-data-api to properly show database error messages
v1.0.0-beta.22
Bug fixed
-
drizzle-kit generate fails to generate correct migrations.js file on Windows
-
[BUG]: MSSQL real() column returns imprecise float64 values -- missing mapFromDriverValue
-
[BUG]: [Drizzle-kit][Pg] Altering a UNIQUE constraint: generated SQL ignores the new changes
-
[BUG]: Non-commutative migration false positive: create_index commutativity check ignores table name
-
Commutativity checks were updated for PostgreSQL and MySQL. Before,
create_indexstatements could be reported as non-commutative even when they targeted different tables, and--ignore-conflictscould still collapse multi-parent history down to a single parent. Now index/table/schema footprints are resolved more accurately, unrelated index branches are accepted, and--ignore-conflictspreserves all open leaf parents for the next migration -
fix: mark mssql and @types/mssql as optional peer dependencies
1.0.0-beta.21
More fixes for the drizzle-kit migration process and commutativity checks
- Adding a value to a PostgreSQL enum will no longer be treated as commutative
- Enum values added in different leaves will now be merged properly