NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
npm · #3545 most downloaded on npm
Drizzle Kit is a CLI migrator tool for Drizzle ORM. It is probably the one and only tool that lets you completely automatically generate SQL migrations and covers ~95% of the common cases like deletions and renames by prompting user input. <https://github
Last release 2 days ago
21 Sep 2026
Ships fairly regularly
a new release about every 2 weeks
Most releases are documented
notes for 39 of the last 60 stable releases
290 versions withdrawn
withdrawn after publishing
5 years old
506 releases · first in 2021
Nothing published for this version
Nothing published for this version
Nothing published for this version
One column per quarter.
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
drizzle-kit generate fails to generate correct migrations.js file on Windows
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_index statements could be reported as non-commutative even when they targeted different tables, and --ignore-conflicts could 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-conflicts preserves all open leaf parents for the next migration
fix: mark mssql and @types/mssql as optional peer dependencies
More fixes for the drizzle-kit migration process and commutativity checks
More fixes for the drizzle-kit migration process and commutativity checks
Previously all the values passed to this functions were not properly escaped causing a possible SQL Injection (CWE-89) vulnerability
sql.identifier(), sql.as() escaping issues. Previously all the values passed to this functions were not properly escaped
causing a possible SQL Injection (CWE-89) vulnerabilityThanks to @EthanKim88, @0x90sh and @wgoodall01 for reaching out to us with a reproduction and suggested fix
sqlcommenter support for PostgreSQL and MySQL
sqlcommenter support for PostgreSQL and MySQLYou can now add custom tags to the query. These tags will be appended to the end of each query, helping the database add metadata/tags to it. This will be especially useful with PlanetScale’s new Database Traffic Control feature
// raw string support
db.select().from().comment("key='val'");
db.select().from().comment("my_first_tag");
// developer friendly dedicated to tags
db.select().from().comment({ key: 'val' });Example:
db.select().from(comments).comment({ priority: 'high', category: "analytics" });select "id", "name" from "comments" /*priority='high',category='analytics'*/The only limitation is that you can't use comments with a prepared statement:
// can't be used
const p = db.select().from().prepare();
// ❌
p.comment({ key: 'val' }).execute();Updated migrate() function for mysql dialect to correctly manage multiple databases
The behavior for reading schema files has been updated. From now only files with the following extensions will be processed: .js .mjs .cjs .jsx .ts .mts .cts .tsx. All other file types will be ignored
Nothing published for this version
Warn about silent migration skips on drizzle-kit checks - thanks @shaneikennedy
Updated to hanji@0.0.8 - native bun stringWidth, stripANSI support, errors for non-TTY environments
hanji@0.0.8 - native bun stringWidth, stripANSI support, errors for non-TTY environmentsesbuild-register to tsx loader, it will now allow to use drizzle-kit seamlessly with both ESM and CJS modulesBun and Deno launch support, which will not trigger tsx loader and utilise native bun and deno imports capabilities and faster startup timesdrizzle-kit api improvements for D1 connections
Fixed algorythm => algorithm typo.
algorythm => algorithm typo.[[BUG]: Drizzle Kit push to Postgres 18 produces unecessary DROP SQL when the schema was NOT changed]
[[BUG]: Importing drizzle-kit/api fails in ESM modules]
Add casing support to studio configuration and related functions
Fixed halfvec, bit and sparsevec type generation bug in drizzle-kit
halfvec, bit and sparsevec type generation bug in drizzle-kitInternal changes to Studio context. Added databaseName and packageName properties for Studio
databaseName and packageName properties for Studioimport { PrismaClient } from '@prisma/client';
import { drizzle } from 'drizzle-orm/prisma/pg';
import { User } from './drizzle';
const prisma = new PrismaClient().$extends(drizzle());
const users = await prisma.$drizzle.select().from(User);
For more info, check docs: https://orm.drizzle.team/docs/prisma
Fixed relations extraction to not interfere with Drizzle Studio.
🎉 Added support for TiDB Cloud Serverless driver:
import { connect } from '@tidbcloud/serverless';
import { drizzle } from 'drizzle-orm/tidb-serverless';
const client = connect({ url: '...' });
const db = drizzle(client);
await db.select().from(...);
Because Gel extensions create schema names containing :: (for example, ext::auth), Drizzle previously handled these names incorrectly. Starting with t
drizzle-kit pull bugs when using Gel extensions.Because Gel extensions create schema names containing :: (for example, ext::auth), Drizzle previously handled these names incorrectly. Starting with this release, you can use Gel extensions without any problems. Here’s what you should do:
drizzle.config.tsimport { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: 'gel',
schemaFilter: ['ext::auth', 'public']
});
Run drizzle-kit pull
Done!
For a full explanation about Drizzle + Expo welcome to discussions
As of v0.31.1 Drizzle ORM now has native support for Expo SQLite Live Queries!
We've implemented a native useLiveQuery React Hook which observes necessary database changes and automatically re-runs database queries. It works with both SQL-like and Drizzle Queries:
import { useLiveQuery, drizzle } from 'drizzle-orm/expo-sqlite';
import { openDatabaseSync } from 'expo-sqlite/next';
import { users } from './schema';
import { Text } from 'react-native';
const expo = openDatabaseSync('db.db', { enableChangeListener: true }); // <-- enable change listeners
const db = drizzle(expo);
const App = () => {
// Re-renders automatically when data changes
const { data } = useLiveQuery(db.select().from(users));
// const { data, error, updatedAt } = useLiveQuery(db.query.users.findFirst());
// const { data, error, updatedAt } = useLiveQuery(db.query.users.findMany());
return <Text>{JSON.stringify(data)}</Text>;
};
export default App;
We've intentionally not changed the API of ORM itself to stay with conventional React Hook API, so we have useLiveQuery(databaseQuery) as opposed to db.select().from(users).useLive() or db.query.users.useFindMany()
We've also decided to provide data, error and updatedAt fields as a result of hook for concise explicit error handling following practices of React Query and Electric SQL
goog-vulnz flags CVE-2024-24790 in esbuild 0.19.7
For situations where you drop an enum value or reorder values in an enum, there is no native way to do this in PostgreSQL. To handle these cases, drizzle-kit used to:
However, there were a few scenarios that weren’t covered: PostgreSQL wasn’t updating default expressions for columns when their data types changed
Therefore, for cases where you either change a column’s data type from an enum to some other type, drop an enum value, or reorder enum values, we now do the following:
esbuild version upgradeFor drizzle-kit we upgraded the version to latest (0.25.2), thanks @paulmarsicloud
Note:
drizzle-orm@0.31.0can be used withdrizzle-kit@0.22.0or higher. The same applies to Drizzle Kit. If you run a Drizzle Kit command, it will check and prompt you for an upgrade (if needed). You can check for Drizzle Kit updates. below
The previous Drizzle+PostgreSQL indexes API was incorrect and was not aligned with the PostgreSQL documentation. The good thing is that it was not used in queries, and drizzle-kit didn't support all properties for indexes. This means we can now change the API to the correct one and provide full support for it in drizzle-kit
Previous API
.on..using and .on in our case are the same thing, so the API is incorrect here..asc(), .desc(), .nullsFirst(), and .nullsLast() should be specified for each column or expression on indexes, but not on an index itself.// Index declaration reference
index('name')
.on(table.column1, table.column2, ...) or .onOnly(table.column1, table.column2, ...)
.concurrently()
.using(sql``) // sql expression
.asc() or .desc()
.nullsFirst() or .nullsLast()
.where(sql``) // sql expression
Current API
// First example, with `.on()`
index('name')
.on(table.column1.asc(), table.column2.nullsFirst(), ...) or .onOnly(table.column1.desc().nullsLast(), table.column2, ...)
.concurrently()
.where(sql``)
.with({ fillfactor: '70' })
// Second Example, with `.using()`
index('name')
.using('btree', table.column1.asc(), sql`lower(${table.column2})`, table.column1.op('text_ops'))
.where(sql``) // sql expression
.with({ fillfactor: '70' })
There is no specific code to create an extension inside the Drizzle schema. We assume that if you are using vector types, indexes, and queries, you have a PostgreSQL database with the
pg_vectorextension installed.
You can now specify indexes for pg_vector and utilize pg_vector functions for querying, ordering, etc.
Let's take a few examples of pg_vector indexes from the pg_vector docs and translate them to Drizzle
// CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);
// CREATE INDEX ON items USING hnsw (embedding vector_ip_ops);
// CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
const table = pgTable('items', {
embedding: vector('embedding', { dimensions: 3 })
}, (table) => ({
l2: index('l2_index').using('hnsw', table.embedding.op('vector_l2_ops'))
ip: index('ip_index').using('hnsw', table.embedding.op('vector_ip_ops'))
cosine: index('cosine_index').using('hnsw', table.embedding.op('vector_cosine_ops'))
}))
// CREATE INDEX ON items USING hnsw (embedding vector_l1_ops);
// CREATE INDEX ON items USING hnsw (embedding bit_hamming_ops);
// CREATE INDEX ON items USING hnsw (embedding bit_jaccard_ops);
const table = pgTable('table', {
embedding: vector('embedding', { dimensions: 3 })
}, (table) => ({
l1: index('l1_index').using('hnsw', table.embedding.op('vector_l1_ops'))
hamming: index('hamming_index').using('hnsw', table.embedding.op('bit_hamming_ops'))
bit: index('bit_jaccard_index').using('hnsw', table.embedding.op('bit_jaccard_ops'))
}))
For queries, you can use predefined functions for vectors or create custom ones using the SQL template operator.
You can also use the following helpers:
import { l2Distance, l1Distance, innerProduct,
cosineDistance, hammingDistance, jaccardDistance } from 'drizzle-orm'
l2Distance(table.column, [3, 1, 2]) // table.column <-> '[3, 1, 2]'
l1Distance(table.column, [3, 1, 2]) // table.column <+> '[3, 1, 2]'
innerProduct(table.column, [3, 1, 2]) // table.column <#> '[3, 1, 2]'
cosineDistance(table.column, [3, 1, 2]) // table.column <=> '[3, 1, 2]'
hammingDistance(table.column, '101') // table.column <~> '101'
jaccardDistance(table.column, '101') // table.column <%> '101'
If pg_vector has some other functions to use, you can replicate implimentation from existing one we have. Here is how it can be done
export function l2Distance(
column: SQLWrapper | AnyColumn,
value: number[] | string[] | TypedQueryBuilder<any> | string,
): SQL {
if (is(value, TypedQueryBuilder<any>) || typeof value === 'string') {
return sql`${column} <-> ${value}`;
}
return sql`${column} <-> ${JSON.stringify(value)}`;
}
Name it as you wish and change the operator. This example allows for a numbers array, strings array, string, or even a select query. Feel free to create any other type you want or even contribute and submit a PR
Let's take a few examples of pg_vector queries from the pg_vector docs and translate them to Drizzle
import { l2Distance } from 'drizzle-orm';
// SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
db.select().from(items).orderBy(l2Distance(items.embedding, [3,1,2]))
// SELECT embedding <-> '[3,1,2]' AS distance FROM items;
db.select({ distance: l2Distance(items.embedding, [3,1,2]) })
// SELECT * FROM items ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1) LIMIT 5;
const subquery = db.select({ embedding: items.embedding }).from(items).where(eq(items.id, 1));
db.select().from(items).orderBy(l2Distance(items.embedding, subquery)).limit(5)
// SELECT (embedding <#> '[3,1,2]') * -1 AS inner_product FROM items;
db.select({ innerProduct: sql`(${maxInnerProduct(items.embedding, [3,1,2])}) * -1` }).from(items)
// and more!
point, lineYou can now use point and line from PostgreSQL Geometric Types
Type point has 2 modes for mappings from the database: tuple and xy.
tuple will be accepted for insert and mapped on select to a tuple. So, the database Point(1,2) will be typed as [1,2] with drizzle.
xy will be accepted for insert and mapped on select to an object with x, y coordinates. So, the database Point(1,2) will be typed as { x: 1, y: 2 } with drizzle
const items = pgTable('items', {
point: point('point'),
pointObj: point('point_xy', { mode: 'xy' }),
});
Type line has 2 modes for mappings from the database: tuple and abc.
tuple will be accepted for insert and mapped on select to a tuple. So, the database Line{1,2,3} will be typed as [1,2,3] with drizzle.
abc will be accepted for insert and mapped on select to an object with a, b, and c constants from the equation Ax + By + C = 0. So, the database Line{1,2,3} will be typed as { a: 1, b: 2, c: 3 } with drizzle.
const items = pgTable('items', {
line: line('line'),
lineObj: point('line_abc', { mode: 'abc' }),
});
There is no specific code to create an extension inside the Drizzle schema. We assume that if you are using postgis types, indexes, and queries, you have a PostgreSQL database with the
postgisextension installed.
geometry type from postgis extension:
const items = pgTable('items', {
geo: geometry('geo', { type: 'point' }),
geoObj: geometry('geo_obj', { type: 'point', mode: 'xy' }),
geoSrid: geometry('geo_options', { type: 'point', mode: 'xy', srid: 4000 }),
});
mode
Type geometry has 2 modes for mappings from the database: tuple and xy.
tuple will be accepted for insert and mapped on select to a tuple. So, the database geometry will be typed as [1,2] with drizzle.xy will be accepted for insert and mapped on select to an object with x, y coordinates. So, the database geometry will be typed as { x: 1, y: 2 } with drizzletype
The current release has a predefined type: point, which is the geometry(Point) type in the PostgreSQL PostGIS extension. You can specify any string there if you want to use some other type
drizzle-kit@0.22.0Release notes here are partially duplicated from drizzle-kit@0.22.0
Drizzle Kit can now handle:
point and line from PostgreSQLvector from the PostgreSQL pg_vector extensiongeometry from the PostgreSQL PostGIS extensionextensionsFiltersThe PostGIS extension creates a few internal tables in the public schema. This means that if you have a database with the PostGIS extension and use push or introspect, all those tables will be included in diff operations. In this case, you would need to specify tablesFilter, find all tables created by the extension, and list them in this parameter.
We have addressed this issue so that you won't need to take all these steps. Simply specify extensionsFilters with the name of the extension used, and Drizzle will skip all the necessary tables.
Currently, we only support the postgis option, but we plan to add more extensions if they create tables in the public schema.
The postgis option will skip the geography_columns, geometry_columns, and spatial_ref_sys tables
import { defineConfig } from 'drizzle-kit'
export default defaultConfig({
dialect: "postgresql",
extensionsFilters: ["postgis"],
})
import { defineConfig } from 'drizzle-kit'
export default defaultConfig({
dialect: "postgresql",
dbCredentials: {
ssl: true, //"require" | "allow" | "prefer" | "verify-full" | options from node:tls
}
})
import { defineConfig } from 'drizzle-kit'
export default defaultConfig({
dialect: "mysql",
dbCredentials: {
ssl: "", // string | SslOptions (ssl options from mysql2 package)
}
})
libsql and better-sqlite3 driversThose drivers have different file path patterns, and Drizzle Kit will accept both and create a proper file path format for each
In this release MySQL and SQLite will properly map expressions into SQL query. Expressions won't be escaped in string but columns will be
export const users = sqliteTable(
'users',
{
id: integer('id').primaryKey(),
email: text('email').notNull(),
},
(table) => ({
emailUniqueIndex: uniqueIndex('emailUniqueIndex').on(sql`lower(${table.email})`),
}),
);
-- before
CREATE UNIQUE INDEX `emailUniqueIndex` ON `users` (`lower("users"."email")`);
-- now
CREATE UNIQUE INDEX `emailUniqueIndex` ON `users` (lower("email"));
push and generate works for indexesExample
index().on(table.id, table.email) // will work well and name will be autogeneretaed
index('my_name').on(table.id, table.email) // will work well
// but
index().on(sql`lower(${table.email})`) // error
index('my_name').on(sql`lower(${table.email})`) // will work well
.on() and .using().where() statements.op() on columnsIf you are using push workflows and want to change these fields in the index, you would need to:
For the generate command, drizzle-kit will be triggered by any changes in the index for any property in the new drizzle indexes API, so there are no limitations here.
[[BUG]: d1 push locally is not working](https://github.com/drizzle-team/drizzle-orm/issues/4099) - thanks @mabels and @RomanNabukhotnyi
PGlite is a WASM Postgres build packaged into a TypeScript client library that enables you to run Postgres in the browser, Node.js and Bun, with no need to install any other dependencies. It is only 2.6mb gzipped.
It can be used as an ephemeral in-memory database, or with persistence either to the file system (Node/Bun) or indexedDB (Browser).
Unlike previous "Postgres in the browser" projects, PGlite does not use a Linux virtual machine - it is simply Postgres in WASM.
Usage Example
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);
There are currently 2 limitations, that should be fixed on Pglite side:
Drizzle is getting a new Gel dialect with its own types and Gel-specific logic. In this first iteration, almost all query-building features have been
Gel dialect support and gel-js client supportDrizzle is getting a new Gel dialect with its own types and Gel-specific logic. In this first iteration, almost all query-building features have been copied from the PostgreSQL dialect since Gel is fully PostgreSQL-compatible. The only change in this iteration is the data types. The Gel dialect has a different set of available data types, and all mappings for these types have been designed to avoid any extra conversions on Drizzle's side. This means you will insert and select exactly the same data as supported by the Gel protocol.
Drizzle + Gel integration will work only through drizzle-kit pull. Drizzle won't support generate, migrate, or push features in this case. Instead, drizzle-kit is used solely to pull the Drizzle schema from the Gel database, which can then be used in your drizzle-orm queries.
The Gel + Drizzle workflow:
gel CLI to manage your schema.gel CLI to generate and apply migrations to the database.On the drizzle-kit side you can now use dialect: "gel"
// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
dialect: 'gel',
});
For a complete Get Started tutorial you can use our new guides:
$onUpdate functionality for PostgreSQL, MySQL and SQLiteAdds a dynamic update value to the column.
The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
If no default (or $defaultFn) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
Note: This value does not affect the
drizzle-kitbehavior, it is only used at runtime indrizzle-orm.
const usersOnUpdate = pgTable('users_on_update', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
updateCounter: integer('update_counter').default(sql`1`).$onUpdateFn(() => sql`update_counter + 1`),
updatedAt: timestamp('updated_at', { mode: 'date', precision: 3 }).$onUpdate(() => new Date()),
alwaysNull: text('always_null').$type<string | null>().$onUpdate(() => null),
});
Thanks @Angelelz and @gabrielDonnantuoni!
Fix bug that generates incorrect syntax when introspect in mysql
According their official website, Xata is a Postgres data platform with a focus on reliability, scalability, and developer experience. The Xata Postgres service is currently in beta, please see the Xata docs on how to enable it in your account.
Drizzle ORM natively supports both the xata driver with drizzle-orm/xata package and the postgres or pg drivers for accessing a Xata Postgres database.
The following example use the Xata generated client, which you obtain by running the xata init CLI command.
pnpm add drizzle-orm @xata.io/client
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(...);
You can also connect to Xata using pg or postgres.js drivers
As SingleStore did not support certain DDL statements before this release, you might encounter an error indicating that some schema changes cannot be
push and generate improvementsAs SingleStore did not support certain DDL statements before this release, you might encounter an error indicating that some schema changes cannot be applied due to a database issue. Starting from this version, drizzle-kit will detect such cases and initiate table recreation with data transfer between the tables
db.execute(...)) to batch API in Neon HTTP driver@neondatabase/serverless HTTP driver types issue (#1945, neondatabase/serverless#66).run() result (https://github.com/drizzle-team/drizzle-orm/pull/2038)Fix certificates generation utility for Drizzle Studio; [[BUG]: [drizzle-kit]: drizzle-kit dependency on drizzle-studio perms error]
LibSQL migrations have been updated to utilize batch execution instead of transactions. As stated in the documentation, LibSQL now supports batch operations
A batch consists of multiple SQL statements executed sequentially within an implicit transaction. The backend handles the transaction: success commits all changes, while any failure results in a full rollback with no modifications.
To make drizzle-kit integration with other migration tools, like Atlas much easier, we've prepared a new command called export. It will translate your
drizzle-kit exportTo make drizzle-kit integration with other migration tools, like Atlas much easier, we've prepared a new command called export. It will translate your drizzle schema in SQL representation(DDL) statements and outputs to the console
// schema.ts
import { pgTable, serial, text } from 'drizzle-orm/pg-core'
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: text('email').notNull(),
name: text('name')
});
Running
npx drizzle-kit export
will output this string to console
CREATE TABLE "users" (
"id" serial PRIMARY KEY NOT NULL,
"email" text NOT NULL,
"name" text
);
By default, the only option for now is --sql, so the output format will be SQL DDL statements. In the future, we will support additional output formats to accommodate more migration tools
npx drizzle-kit export --sql
Usage Example
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);
For more usage and setup details, please check our op-sqlite docs
Starting from this update, the PostgreSQL dialect will align with the behavior of all other dialects. It will no longer include IF NOT EXISTS, $DO, or
Starting from this update, the PostgreSQL dialect will align with the behavior of all other dialects. It will no longer include IF NOT EXISTS, $DO, or similar statements, which could cause incorrect DDL statements to not fail when an object already exists in the database and should actually fail.
This change marks our first step toward several major upgrades we are preparing:
The Postgres timestamp mapping has been changed to align all drivers with the same behavior.
❗ We've modified the postgres.js driver instance to always return strings for dates, and then Drizzle will provide you with either strings of mapped dates, depending on the selected mode. The only issue you may encounter is that once you provide the `postgres.js`` driver instance inside Drizzle, the behavior of this object will change for dates, which will always be strings.
We've made this change as a minor release, just as a warning, that:
If you were using timestamps and were waiting for a specific response, the behavior will now be changed.
When mapping to the driver, we will always use .toISOString for both timestamps with timezone and without timezone.
If you were using the postgres.js driver outside of Drizzle, all postgres.js clients passed to Drizzle will have mutated behavior for dates. All dates will be strings in the response.
Parsers that were changed for postgres.js.
const transparentParser = (val: any) => val;
// Override postgres.js default date parsers: https://github.com/porsager/postgres/discussions/761
for (const type of ['1184', '1082', '1083', '1114']) {
client.options.parsers[type as any] = transparentParser;
client.options.serializers[type as any] = transparentParser;
}
Ideally, as is the case with almost all other drivers, we should have the possibility to mutate mappings on a per-query basis, which means that the driver client won't be mutated. We will be reaching out to the creator of the postgres.js library to inquire about the possibility of specifying per-query mapping interceptors and making this flow even better for all users.
If we've overlooked this capability and it is already available with `postgres.js``, please ping us in our Discord!
A few more references for timestamps without and with timezones can be found in our docs
Big thanks to @Angelelz!
Fix SingleStore generate migrations command
You can now access more information, hints, documentation links, etc. while developing and using JSDoc right in your IDE. Previously, we had them only for filter expressions, but now you can see them for all parts of the Drizzle query builder
Remember, aggregation functions are often used with the GROUP BY clause of the SELECT statement. So if you are selecting using aggregating functions and other columns in one query, be sure to use the
.groupByclause
Here is a list of functions and equivalent using sql template
count
await db.select({ value: count() }).from(users);
await db.select({ value: count(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`count('*'))`.mapWith(Number)
}).from(users);
await db.select({
value: sql`count(${users.id})`.mapWith(Number)
}).from(users);
countDistinct
await db.select({ value: countDistinct(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`count(${users.id})`.mapWith(Number)
}).from(users);
avg
await db.select({ value: avg(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`avg(${users.id})`.mapWith(String)
}).from(users);
avgDistinct
await db.select({ value: avgDistinct(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`avg(distinct ${users.id})`.mapWith(String)
}).from(users);
sum
await db.select({ value: sum(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`sum(${users.id})`.mapWith(String)
}).from(users);
sumDistinct
await db.select({ value: sumDistinct(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`sum(distinct ${users.id})`.mapWith(String)
}).from(users);
max
await db.select({ value: max(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`max(${expression})`.mapWith(users.id)
}).from(users);
min
await db.select({ value: min(users.id) }).from(users);
// It's equivalent to writing
await db.select({
value: sql`min(${users.id})`.mapWith(users.id)
}).from(users);
For cases where it's impossible to perform type checks for specific scenarios, or where it's possible but error messages would be challenging to understand, we've decided to create an ESLint package with recommended rules. This package aims to assist developers in handling crucial scenarios during development
Big thanks to @Angelelz for initiating the development of this package and transferring it to the Drizzle Team's npm
[ npm | yarn | pnpm | bun ] install eslint eslint-plugin-drizzle
You can install those packages for typescript support in your IDE
[ npm | yarn | pnpm | bun ] install @typescript-eslint/eslint-plugin @typescript-eslint/parser
Create a .eslintrc.yml file, add drizzle to the plugins, and specify the rules you want to use. You can find a list of all existing rules below
root: true
parser: '@typescript-eslint/parser'
parserOptions:
project: './tsconfig.json'
plugins:
- drizzle
rules:
'drizzle/enforce-delete-with-where': "error"
'drizzle/enforce-update-with-where': "error"
This plugin exports an all config that makes use of all rules (except for deprecated ones).
root: true
extends:
- "plugin:drizzle/all"
parser: '@typescript-eslint/parser'
parserOptions:
project: './tsconfig.json'
plugins:
- drizzle
At the moment, all is equivalent to recommended
root: true
extends:
- "plugin:drizzle/recommended"
parser: '@typescript-eslint/parser'
parserOptions:
project: './tsconfig.json'
plugins:
- drizzle
enforce-delete-with-where: Enforce using delete with the.where() clause in the .delete() statement. Most of the time, you don't need to delete all rows in the table and require some kind of WHERE statements.
Error Message:
Without `.where(...)` you will delete all the rows in a table. If you didn't want to do it, please use `db.delete(...).where(...)` instead. Otherwise you can ignore this rule here
Optionally, you can define a drizzleObjectName in the plugin options that accept a string or string[]. This is useful when you have objects or classes with a delete method that's not from Drizzle. Such a delete method will trigger the ESLint rule. To avoid that, you can define the name of the Drizzle object that you use in your codebase (like db) so that the rule would only trigger if the delete method comes from this object:
Example, config 1:
"rules": {
"drizzle/enforce-delete-with-where": ["error"]
}
class MyClass {
public delete() {
return {}
}
}
const myClassObj = new MyClass();
// ---> Will be triggered by ESLint Rule
myClassObj.delete()
const db = drizzle(...)
// ---> Will be triggered by ESLint Rule
db.delete()
Example, config 2:
"rules": {
"drizzle/enforce-delete-with-where": ["error", { "drizzleObjectName": ["db"] }],
}
class MyClass {
public delete() {
return {}
}
}
const myClassObj = new MyClass();
// ---> Will NOT be triggered by ESLint Rule
myClassObj.delete()
const db = drizzle(...)
// ---> Will be triggered by ESLint Rule
db.delete()
enforce-update-with-where: Enforce using update with the.where() clause in the .update() statement. Most of the time, you don't need to update all rows in the table and require some kind of WHERE statements.
Error Message:
Without `.where(...)` you will update all the rows in a table. If you didn't want to do it, please use `db.update(...).set(...).where(...)` instead. Otherwise you can ignore this rule here
Optionally, you can define a drizzleObjectName in the plugin options that accept a string or string[]. This is useful when you have objects or classes with a delete method that's not from Drizzle. Such as update method will trigger the ESLint rule. To avoid that, you can define the name of the Drizzle object that you use in your codebase (like db) so that the rule would only trigger if the delete method comes from this object:
Example, config 1:
"rules": {
"drizzle/enforce-update-with-where": ["error"]
}
class MyClass {
public update() {
return {}
}
}
const myClassObj = new MyClass();
// ---> Will be triggered by ESLint Rule
myClassObj.update()
const db = drizzle(...)
// ---> Will be triggered by ESLint Rule
db.update()
Example, config 2:
"rules": {
"drizzle/enforce-update-with-where": ["error", { "drizzleObjectName": ["db"] }],
}
class MyClass {
public update() {
return {}
}
}
const myClassObj = new MyClass();
// ---> Will NOT be triggered by ESLint Rule
myClassObj.update()
const db = drizzle(...)
// ---> Will be triggered by ESLint Rule
db.update()
…to upgrade Drizzle Kit. This may result in some breaking changes throughout the versions, especially if you need to upgrade Drizzle Kit and your Drizz…
Drizzle ORM version
0.29.0will require a minimum Drizzle Kit version of0.20.0, and vice versa. Therefore, when upgrading to a newer version of Drizzle ORM, you will also need to upgrade Drizzle Kit. This may result in some breaking changes throughout the versions, especially if you need to upgrade Drizzle Kit and your Drizzle ORM version is older than<0.28.0
unsigned option for bigintYou can now specify bigint unsigned type
const table = mysqlTable('table', {
id: bigint('id', { mode: 'number', unsigned: true }),
});
Read more in docs
Starting from 0.29.0 by default, as all the query builders in Drizzle try to conform to SQL as much as possible, you can only invoke most of the methods once. For example, in a SELECT statement there might only be one WHERE clause, so you can only invoke .where() once:
const query = db
.select()
.from(users)
.where(eq(users.id, 1))
.where(eq(users.name, 'John')); // ❌ Type error - where() can only be invoked once
This behavior is useful for conventional query building, i.e. when you create the whole query at once. However, it becomes a problem when you want to build a query dynamically, i.e. if you have a shared function that takes a query builder and enhances it. To solve this problem, Drizzle provides a special 'dynamic' mode for query builders, which removes the restriction of invoking methods only once. To enable it, you need to call .$dynamic() on a query builder.
Let's see how it works by implementing a simple withPagination function that adds LIMIT and OFFSET clauses to a query based on the provided page number and an optional page size:
function withPagination<T extends PgSelect>(
qb: T,
page: number,
pageSize: number = 10,
) {
return qb.limit(pageSize).offset(page * pageSize);
}
const query = db.select().from(users).where(eq(users.id, 1));
withPagination(query, 1); // ❌ Type error - the query builder is not in dynamic mode
const dynamicQuery = query.$dynamic();
withPagination(dynamicQuery, 1); // ✅ OK
Note that the withPagination function is generic, which allows you to modify the result type of the query builder inside it, for example by adding a join:
function withFriends<T extends PgSelect>(qb: T) {
return qb.leftJoin(friends, eq(friends.userId, users.id));
}
let query = db.select().from(users).where(eq(users.id, 1)).$dynamic();
query = withFriends(query);
Read more in docs
There is an issue when constraint names exceed the 64-character limit of the database. This causes the database engine to truncate the name, potentially leading to issues. Starting from 0.29.0, you have the option to specify custom names for both primaryKey() and foreignKey(). We have also deprecated the old primaryKey() syntax, which can still be used but will be removed in future releases
const table = pgTable('table', {
id: integer('id'),
name: text('name'),
}, (table) => ({
cpk: primaryKey({ name: 'composite_key', columns: [table.id, table.name] }),
cfk: foreignKey({
name: 'fkName',
columns: [table.id],
foreignColumns: [table.name],
}),
}));
Read more in docs
You can now use the Drizzle withReplica function to specify different database connections for read replicas and the main instance for write operations. By default, withReplicas will use a random read replica for read operations and the main instance for all other data modification operations. You can also specify custom logic for choosing which read replica connection to use. You have the freedom to make any weighted, custom decision for that. Here are some usage examples:
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 connection or read2 connection
db.select().from(usersTable)
// use primary database for delete operation
db.delete(usersTable).where(eq(usersTable.id, 1))
Implementation example of custom logic for selecting read replicas, where the first replica has a 70% chance of being chosen, and the second replica has a 30% chance of being chosen. Note that you can implement any type of random selection for read replicas
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 function is available for all dialects in Drizzle ORM
Read more in docs
Huge thanks to @Angelelz for the significant contribution he made, from API discussions to proper type checks and runtime logic, along with an extensive set of tests. This greatly assisted us in delivering this feature in this release
Usage examples:
All set operators can be used in a two ways: import approach or builder approach
import { union } from 'drizzle-orm/pg-core'
const allUsersQuery = db.select().from(users);
const allCustomersQuery = db.select().from(customers);
const result = await union(allUsersQuery, allCustomersQuery)
const result = await db.select().from(users).union(db.select().from(customers));
Read more in docs
A new driver has been released, allowing you to create your own implementation for an HTTP driver using a MySQL database. You can find usage examples in the ./examples/mysql-proxy folder
You need to implement two endpoints on your server that will be used for queries and migrations(Migrate endpoint is optional and only if you want to use drizzle migrations). Both the server and driver implementation are up to you, so you are not restricted in any way. You can add custom mappings, logging, and much more
You can find both server and driver implementation examples in the ./examples/mysql-proxy folder
// Driver
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),
);
}
Same as MySQL you can now implement your own http driver for PostgreSQL database. You can find usage examples in the ./examples/pg-proxy folder
You need to implement two endpoints on your server that will be used for queries and migrations (Migrate endpoint is optional and only if you want to use drizzle migrations). Both the server and driver implementation are up to you, so you are not restricted in any way. You can add custom mappings, logging, and much more
You can find both server and driver implementation examples in the ./examples/pg-proxy folder
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));
}
D1 Batch API supportReference: https://developers.cloudflare.com/d1/platform/client-api/#dbbatch
Batch API usage example:
const batchResponse = await db.batch([
db.insert(usersTable).values({ id: 1, name: 'John' }).returning({
id: usersTable.id,
}),
db.update(usersTable).set({ name: 'Dan' }).where(eq(usersTable.id, 1)),
db.query.usersTable.findMany({}),
db.select().from(usersTable).where(eq(usersTable.id, 1)),
db.select({ id: usersTable.id, invitedBy: usersTable.invitedBy }).from(
usersTable,
),
]);
Type for batchResponse in this example would be:
type BatchResponse = [
{
id: number;
}[],
D1Result,
{
id: number;
name: string;
verified: number;
invitedBy: number | null;
}[],
{
id: number;
name: string;
verified: number;
invitedBy: number | null;
}[],
{
id: number;
invitedBy: number | null;
}[],
];
All possible builders that can be used inside db.batch:
`db.all()`,
`db.get()`,
`db.values()`,
`db.run()`,
`db.query.<table>.findMany()`,
`db.query.<table>.findFirst()`,
`db.select()...`,
`db.update()...`,
`db.delete()...`,
`db.insert()...`,
More usage examples here: integration-tests/tests/d1-batch.test.ts and in docs
defineConfig functionbigint unsigned supportprimaryKeys and foreignKeys now can have custom namesYou can read more about drizzle-kit updates here
SingleStore dialect is now available in DrizzleThanks to the SingleStore team for creating a PR with all the necessary changes to support the MySQL-compatible part of SingleStore. You can already start using it with Drizzle. The SingleStore team will also help us iterate through updates and make more SingleStore-specific features available in Drizzle
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!,
},
});
You can check out our Getting started guides to try SingleStore!
SQLite Durable Objects driver is now available in DrizzleYou can now query SQLite Durable Objects in Drizzle!
For the full example, please check our Get Started Section
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'sqlite',
driver: 'durable-sqlite',
});
Fixed typos in repository: thanks @armandsalle, @masto, @wackbyte, @Asher-JH, @MaxLeiter
Added an OHM static imports checker to identify unexpected imports within a chain of imports in the drizzle-kit repo. For example, it checks if drizzl
Current example won't work in 0.28.0:
const usersWithPosts = await db.query.users.findMany({
where: (table, { sql }) => (sql`json_array_length(${table.posts}) > 0`),
with: {
posts: true,
},
});
The table object in the where callback won't have fields from with and extras. We removed them to be able to build more efficient relational queries, which improved row reads and performance.
If you have used those fields in the where callback before, there are several workarounds:
mode config for mysql2 driverDrizzle relational queries always generate exactly one SQL statement to run on the database and it has certain caveats. To have best in class support for every database out there we've introduced modes.
Drizzle relational queries use lateral joins of subqueries under the hood and for now PlanetScale does not support them.
When using mysql2 driver with regular MySQL database - you should specify mode: "default".
When using mysql2 driver with PlanetScale - you need to specify mode: "planetscale".
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
import * as schema from './schema';
const connection = await mysql.createConnection({
uri: process.env.PLANETSCALE_DATABASE_URL,
});
const db = drizzle(connection, { schema, mode: 'planetscale' });
We've run the diagnostics on a database schema with 85 tables, 666 columns, 26 enums, 172 indexes and 133 foreign keys. We've optimized internal types which resulted in 430% speed up in IntelliSense.
In this release we've fully changed a way query is generated for Relational Queri API.
As a summary we've made current set of changes in query generation startegy:
Lateral Joins: In the new version we're utilizing lateral joins, denoted by the "LEFT JOIN LATERAL" clauses, to retrieve specific data from related tables efficiently For MySQL in PlanetScale and SQLite, we've used simple subquery selects, which improved a query plan and overall performance
Selective Data Retrieval: In the new version we're retrieving only the necessary data from tables. This targeted data retrieval reduces the amount of unnecessary information fetched, resulting in a smaller dataset to process and faster execution.
Reduced Aggregations: In the new version we've reduced the number of aggregation functions (e.g., COUNT, json_agg). By using json_build_array directly within the lateral joins, drizzle is aggregating the data in a more streamlined manner, leading to improved query performance.
Simplified Grouping: In the new version the GROUP BY clause is removed, as the lateral joins and subqueries already handle data aggregation more efficiently.
For this drizzle query
const items = await db.query.comments.findMany({
limit,
orderBy: comments.id,
with: {
user: {
columns: { name: true },
},
post: {
columns: { title: true },
with: {
user: {
columns: { name: true },
},
},
},
},
});
Query that Drizzle generates now
select "comments"."id",
"comments"."user_id",
"comments"."post_id",
"comments"."content",
"comments_user"."data" as "user",
"comments_post"."data" as "post"
from "comments"
left join lateral (select json_build_array("comments_user"."name") as "data"
from (select *
from "users" "comments_user"
where "comments_user"."id" = "comments"."user_id"
limit 1) "comments_user") "comments_user" on true
left join lateral (select json_build_array("comments_post"."title", "comments_post_user"."data") as "data"
from (select *
from "posts" "comments_post"
where "comments_post"."id" = "comments"."post_id"
limit 1) "comments_post"
left join lateral (select json_build_array("comments_post_user"."name") as "data"
from (select *
from "users" "comments_post_user"
where "comments_post_user"."id" = "comments_post"."user_id"
limit 1) "comments_post_user") "comments_post_user"
on true) "comments_post" on true
order by "comments"."id"
limit 1
Query generated before:
SELECT "id",
"user_id",
"post_id",
"content",
"user"::JSON,
"post"::JSON
FROM
(SELECT "comments".*,
CASE
WHEN count("comments_post"."id") = 0 THEN '[]'
ELSE json_agg(json_build_array("comments_post"."title", "comments_post"."user"::JSON))::text
END AS "post"
FROM
(SELECT "comments".*,
CASE
WHEN count("comments_user"."id") = 0 THEN '[]'
ELSE json_agg(json_build_array("comments_user"."name"))::text
END AS "user"
FROM "comments"
LEFT JOIN
(SELECT "comments_user".*
FROM "users" "comments_user") "comments_user" ON "comments"."user_id" = "comments_user"."id"
GROUP BY "comments"."id",
"comments"."user_id",
"comments"."post_id",
"comments"."content") "comments"
LEFT JOIN
(SELECT "comments_post".*
FROM
(SELECT "comments_post".*,
CASE
WHEN count("comments_post_user"."id") = 0 THEN '[]'
ELSE json_agg(json_build_array("comments_post_user"."name"))
END AS "user"
FROM "posts" "comments_post"
LEFT JOIN
(SELECT "comments_post_user".*
FROM "users" "comments_post_user") "comments_post_user" ON "comments_post"."user_id" = "comments_post_user"."id"
GROUP BY "comments_post"."id") "comments_post") "comments_post" ON "comments"."post_id" = "comments_post"."id"
GROUP BY "comments"."id",
"comments"."user_id",
"comments"."post_id",
"comments"."content",
"comments"."user") "comments"
LIMIT 1
You can now provide an empty object or an array of empty objects, and Drizzle will insert all defaults into the database.
// Insert 1 row with all defaults
await db.insert(usersTable).values({});
// Insert 2 rows with all defaults
await db.insert(usersTable).values([{}, {}]);
Fix [[BUG]: Undefined properties when using drizzle-kit push]
drizzle-orm/supabaseUNIQUE constraints in PostgreSQL, MySQL, SQLiteFor PostgreSQL, unique constraints can be defined at the column level for single-column constraints, and in the third parameter for multi-column constraints. In both cases, it will be possible to define a custom name for the constraint. Additionally, PostgreSQL will receive the NULLS NOT DISTINCT option to restrict having more than one NULL value in a table. Reference
Examples that just shows a different unique usage. Please don't search a real usage for those tables
// single column
const table = pgTable('table', {
id: serial('id').primaryKey(),
name: text('name').notNull().unique(),
state: char('state', { length: 2 }).unique('custom'),
field: char('field', { length: 2 }).unique('custom_field', { nulls: 'not distinct' }),
});
// multiple columns
const table = pgTable('table', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
state: char('state', { length: 2 }),
}, (t) => ({
first: unique('custom_name').on(t.name, t.state).nullsNotDistinct(),
second: unique('custom_name1').on(t.name, t.state),
}));
For MySQL, everything will be the same except for the NULLS NOT DISTINCT option. It appears that MySQL does not support it
Examples that just shows a different unique usage. Please don't search a real usage for those tables
// single column
const table = mysqlTable('table', {
id: serial('id').primaryKey(),
name: text('name').notNull().unique(),
state: text('state').unique('custom'),
field: text('field').unique('custom_field'),
});
// multiple columns
const table = mysqlTable('cities1', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
state: text('state'),
}, (t) => ({
first: unique().on(t.name, t.state),
second: unique('custom_name1').on(t.name, t.state),
}));
In SQLite unique constraints are the same as unique indexes. As long as you can specify a name for the unique index in SQLite - we will treat all unique constraints as unique indexes in internal implementation
// single column
const table = sqliteTable('table', {
id: int('id').primaryKey(),
name: text('name').notNull().unique(),
state: text('state').unique('custom'),
field: text('field').unique(),
});
// multiple columns
const table = sqliteTable('table', {
id: int('id').primaryKey(),
name: text('name').notNull(),
state: text('state'),
}, (t) => ({
first: unique().on(t.name, t.state),
second: unique('custom').on(t.name, t.state),
}));
Fix: [[BUG]: When using RLS policies and Views, the view is the last clause generated]
import { neon, neonConfig } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
neonConfig.fetchConnectionCache = true;
const sql = neon(process.env.DRIZZLE_DATABASE_URL!);
const db = drizzle(sql);
db.select(...)
Nothing published for this version
> This version of drizzle-jit requires drizzle-orm@0.36.0 to enable all new features
This version of
drizzle-jitrequiresdrizzle-orm@0.36.0to enable all new features
With Drizzle, you can enable Row-Level Security (RLS) for any Postgres table, create policies with various options, and define and manage the roles those policies apply to.
Drizzle supports a raw representation of Postgres policies and roles that can be used in any way you want. This works with popular Postgres database providers such as Neon and Supabase.
In Drizzle, we have specific predefined RLS roles and functions for RLS with both database providers, but you can also define your own logic.
If you just want to enable RLS on a table without adding policies, you can use .enableRLS()
As mentioned in the PostgreSQL documentation:
If no policy exists for the table, a default-deny policy is used, meaning that no rows are visible or can be modified. Operations that apply to the whole table, such as TRUNCATE and REFERENCES, are not subject to row security.
import { integer, pgTable } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: integer(),
}).enableRLS();
If you add a policy to a table, RLS will be enabled automatically. So, there’s no need to explicitly enable RLS when adding policies to a table.
Currently, Drizzle supports defining roles with a few different options, as shown below. Support for more options will be added in a future release.
import { pgRole } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin', { createRole: true, createDb: true, inherit: true });
If a role already exists in your database, and you don’t want drizzle-kit to ‘see’ it or include it in migrations, you can mark the role as existing.
import { pgRole } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin').existing();
To fully leverage RLS, you can define policies within a Drizzle table.
In PostgreSQL, policies should be linked to an existing table. Since policies are always associated with a specific table, we decided that policy definitions should be defined as a parameter of
pgTable
Example of pgPolicy with all available properties
import { sql } from 'drizzle-orm';
import { integer, pgPolicy, pgRole, pgTable } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin');
export const users = pgTable('users', {
id: integer(),
}, (t) => [
pgPolicy('policy', {
as: 'permissive',
to: admin,
for: 'delete',
using: sql``,
withCheck: sql``,
}),
]);
Link Policy to an existing table
There are situations where you need to link a policy to an existing table in your database.
The most common use case is with database providers like Neon or Supabase, where you need to add a policy
to their existing tables. In this case, you can use the .link() API
import { sql } from "drizzle-orm";
import { pgPolicy } from "drizzle-orm/pg-core";
import { authenticatedRole, realtimeMessages } from "drizzle-orm/supabase";
export const policy = pgPolicy("authenticated role insert policy", {
for: "insert",
to: authenticatedRole,
using: sql``,
}).link(realtimeMessages);
If you are using drizzle-kit to manage your schema and roles, there may be situations where you want to refer to roles that are not defined in your Drizzle schema. In such cases, you may want drizzle-kit to skip managing these roles without having to define each role in your drizzle schema and marking it with .existing().
In these cases, you can use entities.roles in drizzle.config.ts. For a complete reference, refer to the the drizzle.config.ts documentation.
By default, drizzle-kit does not manage roles for you, so you will need to enable this feature in drizzle.config.ts.
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: 'postgresql',
schema: "./drizzle/schema.ts",
dbCredentials: {
url: process.env.DATABASE_URL!
},
verbose: true,
strict: true,
entities: {
roles: true
}
});
In case you need additional configuration options, let's take a look at a few more examples.
You have an admin role and want to exclude it from the list of manageable roles
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
...
entities: {
roles: {
exclude: ['admin']
}
}
});
You have an admin role and want to include it in the list of manageable roles
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
...
entities: {
roles: {
include: ['admin']
}
}
});
If you are using Neon and want to exclude Neon-defined roles, you can use the provider option
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
...
entities: {
roles: {
provider: 'neon'
}
}
});
If you are using Supabase and want to exclude Supabase-defined roles, you can use the provider option
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
...
entities: {
roles: {
provider: 'supabase'
}
}
});
You may encounter situations where Drizzle is slightly outdated compared to new roles specified by your database provider. In such cases, you can use the
provideroption andexcludeadditional roles:
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
...
entities: {
roles: {
provider: 'supabase',
exclude: ['new_supabase_role']
}
}
});
With Drizzle, you can also specify RLS policies on views. For this, you need to use security_invoker in the view's WITH options. Here is a small example:
...
export const roomsUsersProfiles = pgView("rooms_users_profiles")
.with({
securityInvoker: true,
})
.as((qb) =>
qb
.select({
...getTableColumns(roomsUsers),
email: profiles.email,
})
.from(roomsUsers)
.innerJoin(profiles, eq(roomsUsers.userId, profiles.id))
);
The Neon Team helped us implement their vision of a wrapper on top of our raw policies API. We defined a specific
/neon import with the crudPolicy function that includes predefined functions and Neon's default roles.
Here's an example of how to use the crudPolicy function:
import { crudPolicy } from 'drizzle-orm/neon';
import { integer, pgRole, pgTable } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin');
export const users = pgTable('users', {
id: integer(),
}, (t) => [
crudPolicy({ role: admin, read: true, modify: false }),
]);
This policy is equivalent to:
import { sql } from 'drizzle-orm';
import { integer, pgPolicy, pgRole, pgTable } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin');
export const users = pgTable('users', {
id: integer(),
}, (t) => [
pgPolicy(`crud-${admin.name}-policy-insert`, {
for: 'insert',
to: admin,
withCheck: sql`false`,
}),
pgPolicy(`crud-${admin.name}-policy-update`, {
for: 'update',
to: admin,
using: sql`false`,
withCheck: sql`false`,
}),
pgPolicy(`crud-${admin.name}-policy-delete`, {
for: 'delete',
to: admin,
using: sql`false`,
}),
pgPolicy(`crud-${admin.name}-policy-select`, {
for: 'select',
to: admin,
using: sql`true`,
}),
]);
Neon exposes predefined authenticated and anaonymous roles and related functions. If you are using Neon for RLS, you can use these roles, which are marked as existing, and the related functions in your RLS queries.
// drizzle-orm/neon
export const authenticatedRole = pgRole('authenticated').existing();
export const anonymousRole = pgRole('anonymous').existing();
export const authUid = (userIdColumn: AnyPgColumn) => sql`(select auth.user_id() = ${userIdColumn})`;
For example, you can use the Neon predefined roles and functions like this:
import { sql } from 'drizzle-orm';
import { authenticatedRole } from 'drizzle-orm/neon';
import { integer, pgPolicy, pgRole, pgTable } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin');
export const users = pgTable('users', {
id: integer(),
}, (t) => [
pgPolicy(`policy-insert`, {
for: 'insert',
to: authenticatedRole,
withCheck: sql`false`,
}),
]);
We also have a /supabase import with a set of predefined roles marked as existing, which you can use in your schema.
This import will be extended in a future release with more functions and helpers to make using RLS and Supabase simpler.
// drizzle-orm/supabase
export const anonRole = pgRole('anon').existing();
export const authenticatedRole = pgRole('authenticated').existing();
export const serviceRole = pgRole('service_role').existing();
export const postgresRole = pgRole('postgres_role').existing();
export const supabaseAuthAdminRole = pgRole('supabase_auth_admin').existing();
For example, you can use the Supabase predefined roles like this:
import { sql } from 'drizzle-orm';
import { serviceRole } from 'drizzle-orm/supabase';
import { integer, pgPolicy, pgRole, pgTable } from 'drizzle-orm/pg-core';
export const admin = pgRole('admin');
export const users = pgTable('users', {
id: integer(),
}, (t) => [
pgPolicy(`policy-insert`, {
for: 'insert',
to: serviceRole,
withCheck: sql`false`,
}),
]);
The /supabase import also includes predefined tables and functions that you can use in your application
// drizzle-orm/supabase
const auth = pgSchema('auth');
export const authUsers = auth.table('users', {
id: uuid().primaryKey().notNull(),
});
const realtime = pgSchema('realtime');
export const realtimeMessages = realtime.table(
'messages',
{
id: bigserial({ mode: 'bigint' }).primaryKey(),
topic: text().notNull(),
extension: text({
enum: ['presence', 'broadcast', 'postgres_changes'],
}).notNull(),
},
);
export const authUid = sql`(select auth.uid())`;
export const realtimeTopic = sql`realtime.topic()`;
This allows you to use it in your code, and Drizzle Kit will treat them as existing databases, using them only as information to connect to other entities
import { foreignKey, pgPolicy, pgTable, text, uuid } from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm/sql";
import { authenticatedRole, authUsers } from "drizzle-orm/supabase";
export const profiles = pgTable(
"profiles",
{
id: uuid().primaryKey().notNull(),
email: text().notNull(),
},
(table) => [
foreignKey({
columns: [table.id],
// reference to the auth table from Supabase
foreignColumns: [authUsers.id],
name: "profiles_id_fk",
}).onDelete("cascade"),
pgPolicy("authenticated can view all profiles", {
for: "select",
// using predefined role from Supabase
to: authenticatedRole,
using: sql`true`,
}),
]
);
Let's check an example of adding a policy to a table that exists in Supabase
import { sql } from "drizzle-orm";
import { pgPolicy } from "drizzle-orm/pg-core";
import { authenticatedRole, realtimeMessages } from "drizzle-orm/supabase";
export const policy = pgPolicy("authenticated role insert policy", {
for: "insert",
to: authenticatedRole,
using: sql``,
}).link(realtimeMessages);
Replacing all instanceof statements with a custom is() function allowed us to handle multiple Drizzle packages interacting properly.
It also fixes one of our biggest Discord tickets: maximum call stack exceeded 🎉
You should now use is() instead of instanceof to check if specific objects are instances of specific Drizzle types. It might be useful if you are building something on top of the Drizzle API.
import { is, Column } from 'drizzle-orm'
if (is(value, Column)) {
// value's type is narrowed to Column
}
distinct clause supportawait db.selectDistinct().from(usersDistinctTable).orderBy(
usersDistinctTable.id,
usersDistinctTable.name,
);
Also, distinct on clause is available for PostgreSQL:
await db.selectDistinctOn([usersDistinctTable.id]).from(usersDistinctTable).orderBy(
usersDistinctTable.id,
);
await db.selectDistinctOn([usersDistinctTable.name], { name: usersDistinctTable.name }).from(
usersDistinctTable,
).orderBy(usersDistinctTable.name);
bigint and boolean support for SQLiteContributed by @MrRahulRamkumar (#558), @raducristianpopa (#411) and @meech-ward (#725)
const users = sqliteTable('users', {
bigintCol: blob('bigint', { mode: 'bigint' }).notNull(),
boolCol: integer('bool', { mode: 'boolean' }).notNull(),
});
where callback in RQB for tables without relationsUpdated internal versions for the drizzle-kit and drizzle-orm packages. Changes were introduced in the last minor release, and you are required to upg
Fix data is malformed for views
data is malformed for views> While writing this update, we found one bug that may occur with views in MySQL and SQLite, so please use the drizzle-kit@0.26.1 release
While writing this update, we found one bug that may occur with views in MySQL and SQLite, so please use the
drizzle-kit@0.26.1release
drizzle-kitYou can use drizzle-kit to manage your check constraint defined in drizzle-orm schema definition
For example current drizzle table:
import { sql } from "drizzle-orm";
import { check, pgTable } from "drizzle-orm/pg-core";
export const users = pgTable(
"users",
(c) => ({
id: c.uuid().defaultRandom().primaryKey(),
username: c.text().notNull(),
age: c.integer(),
}),
(table) => ({
checkConstraint: check("age_check", sql`${table.age} > 21`),
})
);
will be generated into
CREATE TABLE IF NOT EXISTS "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"username" text NOT NULL,
"age" integer,
CONSTRAINT "age_check" CHECK ("users"."age" > 21)
);
The same is supported in all dialects
generate will work as expected for all check constraint changes.push will detect only check renames and will recreate the constraint. All other changes to SQL won't be detected and will be ignored.So, if you want to change the constraint's SQL definition using only push, you would need to manually comment out the constraint, push, then put it back with the new SQL definition and push one more time.
drizzle-kitYou can use drizzle-kit to manage your views defined in drizzle-orm schema definition. It will work with all existing dialects and view options
For example current drizzle table:
import { sql } from "drizzle-orm";
import {
check,
pgMaterializedView,
pgTable,
pgView,
} from "drizzle-orm/pg-core";
export const users = pgTable(
"users",
(c) => ({
id: c.uuid().defaultRandom().primaryKey(),
username: c.text().notNull(),
age: c.integer(),
}),
(table) => ({
checkConstraint: check("age_check", sql`${table.age} > 21`),
})
);
export const simpleView = pgView("simple_users_view").as((qb) =>
qb.select().from(users)
);
export const materializedView = pgMaterializedView(
"materialized_users_view"
).as((qb) => qb.select().from(users));
will be generated into
CREATE TABLE IF NOT EXISTS "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"username" text NOT NULL,
"age" integer,
CONSTRAINT "age_check" CHECK ("users"."age" > 21)
);
CREATE VIEW "public"."simple_users_view" AS (select "id", "username", "age" from "users");
CREATE MATERIALIZED VIEW "public"."materialized_users_view" AS (select "id", "username", "age" from "users");
Views supported in all dialects, but materialized views are supported only in PostgreSQL
generate will work as expected for all view changespush limitations:push, you would need to manually comment out the view, push, then put it back with the new SQL definition and push one more time.We've updated enum behavior in Drizzle with PostgreSQL:
Add value after or before in enum: With this change, Drizzle will now respect the order of values in the enum and allow adding new values after or before a specific one.
Support for dropping a value from an enum: In this case, Drizzle will attempt to alter all columns using the enum to text, then drop the existing enum and create a new one with the updated set of values. After that, all columns previously using the enum will be altered back to the new enum.
If the deleted enum value was used by a column, this process will result in a database error.
Support for dropping an enum
Support for moving enums between schemas
Support for renaming enums
The documentation has been completely reworked and updated with additional examples and explanations. You can find it here: https://orm.drizzle.team.
Furthermore, the entire documentation has been made open source, allowing you to edit and add any information you deem important for the community.
Visit https://github.com/drizzle-team/drizzle-orm-docs to access the open-sourced documentation.
Additionally, you can create specific documentation issues in this repository
Introducing our first helper built on top of Drizzle Core API syntax: the Relational Queries! 🎉
With Drizzle RQ you can do:
where statements, allowing you to define custom conditions beyond the predefined ones available in the Drizzle Core API.Most importantly, regardless of the size of your query, Drizzle will always generate a SINGLE optimized query.
This efficiency extends to the usage of Prepared Statements, which are fully supported within the Relational Query Builder.
For more info: Prepared Statements in Relational Query Builder
Example of setting one-to-many relations
As you can observe,
relationsare a distinct concept that coexists alongside the main Drizzle schema. You have the flexibility to opt-in or opt-out of them at any time without affecting thedrizzle-kitmigrations or the logic for Core API's types and runtime.
import { integer, serial, text, pgTable } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
});
export const usersConfig = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
content: text('content').notNull(),
authorId: integer('author_id').notNull(),
});
export const postsConfig = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));
Example of querying you database
Step 1: Provide all tables and relations to drizzle function
drizzleimport depends on the database driver you're using
import * as schema from './schema';
import { drizzle } from 'drizzle-orm/...';
const db = drizzle(client, { schema });
await db.query.users.findMany(...);
If you have schema in multiple files
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(...);
Step 2: Query your database with Relational Query Builder
Select all users
const users = await db.query.users.findMany();
Select first users
.findFirst()will add limit 1 to the query
const user = await db.query.users.findFirst();
Select all users
Get all posts with just id, content and include comments
const posts = await db.query.posts.findMany({
columns: {
id: true,
content: true,
},
with: {
comments: true,
}
});
Select all posts excluding content column
const posts = await db.query.posts.findMany({
columns: {
content: false,
},
});
For more examples you can check full docs for Relational Queries
You can now specify the configuration not only in the .json format but also in .ts and .js formats.
</br>
TypeScript example
import { Config } from "drizzle-kit";
export default {
schema: "",
connectionString: process.env.DB_URL,
out: "",
breakpoints: true
} satisfies Config;
JavaScript example
/** @type { import("drizzle-kit").Config } */
export default {
schema: "",
connectionString: "",
out: "",
breakpoints: true
};
drizzle-kit push:mysqlYou can now push your MySQL schema directly to the database without the need to create and manage migration files. This feature proves to be particularly useful for rapid local development and when working with PlanetScale databases.
By pushing the MySQL schema directly to the database, you can streamline the development process and avoid the overhead of managing migration files. This allows for more efficient iteration and quick deployment of schema changes during local development.
For this feature, you need to create a drizzle.config.[ts|js|json] file. We recommend using .ts or .js files as they allow you to easily provide the database connection information as secret variables
You'll need to specify schema and connectionString(or db, port, host, password, etc.) to make drizzle-kit push:mysql work
drizzle.config.ts example
import { Config } from "src";
export default {
schema: "./schema.ts",
connectionString: process.env.DB_URL,
} satisfies Config;
Run drizzle-kit push:mysql
If Drizzle detects any potential data-loss issues during a migration, it will prompt you to approve whether the data should be truncated or not in order to ensure a successful migration
Approve or reject the action that Drizzle needs to perform in order to push your schema changes to the database.
Done ✅
If you are using Turso and libsql, you will need to upgrade your drizzle.config and @libsql/client package.
If you are using Turso and libsql, you will need to upgrade your drizzle.config and @libsql/client package.
@libsql/client@0.10.0 or higher if you are using the migrate function. For other use cases, you can continue using previous versions(But the suggestion is to upgrade)
To install the latest version, use the command:npm i @libsql/client@latest
drizzle.config for SQLite and Turso users, which allowed a shared strategy for both dialects. Starting with this release, we are introducing the turso dialect in drizzle-kit. We will evolve and improve Turso as a separate dialect with its own migration strategies.Before
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,
});
After
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,
});
If you are using only SQLite, you can use dialect: "sqlite"
Starting from this release, we will no longer generate comments like this:
'/*\n SQLite does not support "Changing existing column type" out of the box, we do not generate automatic migration for that, so it has to be done manually'
+ '\n Please refer to: https://www.techonthenet.com/sqlite/tables/alter_table.php'
+ '\n https://www.sqlite.org/lang_altertable.html'
+ '\n https://stackoverflow.com/questions/2083543/modify-a-columns-type-in-sqlite3'
+ "\n\n Due to that we don't generate migration automatically and it has to be done manually"
+ '\n*/'
We will generate a set of statements, and you can decide if it's appropriate to create data-moving statements instead. Here is an example of the SQL file you'll receive now:
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;
Since LibSQL supports more ALTER statements than SQLite, we can generate more statements without recreating your schema and moving all the data, which can be potentially dangerous for production environments.
LibSQL and Turso will now have a separate dialect in the Drizzle config file, meaning that we will evolve Turso and LibSQL independently from SQLite and will aim to support as many features as Turso/LibSQL offer.
With the updated LibSQL migration strategy, you will have the ability to:
You can find more information in the LibSQL documentation
This is because LibSQL/Turso does not support dropping this type of foreign key.
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
);
If the table has indexes, altering columns will cause index recreation: Drizzle-Kit will drop the indexes, modify the columns, and then create the indexes.
Adding or dropping composite foreign keys is not supported and will cause table recreation.
Primary key columns can not be altered and will cause table recreation.
Altering columns that are part of foreign key will cause table recreation.
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!
NOTE: The foreign key for the table child5 is an error because, although the parent key column has a unique index, the index uses a different collating sequence.
See more: https://www.sqlite.org/foreignkeys.html
casing param in drizzle-orm and drizzle-kitThere are more improvements you can make to your schema definition. The most common way to name your variables in a database and in TypeScript code is usually snake_case in the database and camelCase in the code. For this case, in Drizzle, you can now define a naming strategy in your database to help Drizzle map column keys automatically. Let's take a table from the previous example and make it work with the new casing API in Drizzle
Table can now become:
import { pgTable } from "drizzle-orm/pg-core";
export const ingredients = pgTable("ingredients", (t) => ({
id: t.uuid().defaultRandom().primaryKey(),
name: t.text().notNull(),
description: t.text(),
inStock: t.boolean().default(true),
}));
As you can see, inStock doesn't have a database name alias, but by defining the casing configuration at the connection level, all queries will automatically map it to snake_case
const db = await drizzle('node-postgres', { connection: '', casing: 'snake_case' })
For drizzle-kit migrations generation you should also specify casing param in drizzle config, so you can be sure you casing strategy will be applied to drizzle-kit as well
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
schema: "./schema.ts",
dbCredentials: {
url: "postgresql://postgres:password@localhost:5432/db",
},
casing: "snake_case",
});
drizzle-orm in both ESM and CJS environments.drizzle-orm/sql and drizzle-orm/expressions should now be imported from drizzle-orm instead.Nothing published for this version
You can now use pglite with all drizzle-kit commands, including Drizzle Studio!
pglite driverYou can now use pglite with all drizzle-kit commands, including Drizzle Studio!
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
driver: "pglite",
schema: "./schema.ts",
dbCredentials: {
url: "local-pg.db",
},
verbose: true,
strict: true,
});
> Big thanks to @L-Mario564 for his PR. It conflicted in most cases with a PR that was merged, but we incorporated some of his logic. Merging it would
Big thanks to @L-Mario564 for his PR. It conflicted in most cases with a PR that was merged, but we incorporated some of his logic. Merging it would have caused more problems and taken more time to resolve, so we just took a few things from his PR, like removing "::<type>" mappings in introspect and some array type default handlers
introspect command.::<type> was included in the introspected output.preserve casing option was broken🐛 Fix onConflict targets in #475 - thanks @wkunert ❤️
Thanks to @tmcw we have started our way to get JSDoc documentation
📄 JSDoc for conditions in #467 - thanks @tmcw ❤️
🎉 Added iterator support to mysql2 (sponsored by @rizen ❤). Read more in the docs
mysql2 (sponsored by @rizen ❤). Read more in the docs.prepare() in MySQL no longer requires a name argumentsort in SQLite and to be consistent with the same logic in PostgreSQL and MySQLThe issue that may arise for SQLite users with any driver using composite primary keys is that the order in the database may differ from the Drizzle schema.
If you are using push, you MAY be prompted to update your table with a new order of columns in the composite primary key. You will need to either change it manually in the database or push the changes, but this may lead to data loss, etc.
If you are using generate, you MAY also be prompted to update your table with a new order of columns in the composite primary key. You can either keep that migration or skip it by emptying the SQL migration file.
If nothing works for you and you are blocked, please reach out to me @AndriiSherman. I will try to help you!
🐛 Rolled back some breaking changes for drizzle-kit
schemaFilter object was passed. It was detecting enums even in schemas that were not defined in the schemaFilter.drizzle-kit up command to work as expected, starting from the sequences release.🐛 Re-export InferModel from drizzle-orm
InferModel from drizzle-ormThe spread syntax is now deprecated and will be removed in one of the next releases.
🎉 Added Knex and Kysely adapters! They allow you to manage the schemas and migrations with Drizzle and query the data with your favorite query builder. See documentation for more details:
🎉 Added "type maps" to all entities. You can access them via the special _ property. For example:
const users = mysqlTable('users', {
id: int('id').primaryKey(),
name: text('name').notNull(),
});
type UserFields = typeof users['_']['columns'];
type InsertUser = typeof users['_']['model']['insert'];
Full documentation on the type maps is coming soon.
🎉 Added .$type() method to all column builders to allow overriding the data type. It also replaces the optional generics on columns.
// Before
const test = mysqlTable('test', {
jsonField: json<Data>('json_field'),
});
// After
const test = mysqlTable('test', {
jsonField: json('json_field').$type<Data>(),
});
❗ Changed syntax for text-based enum columns:
// Before
const test = mysqlTable('test', {
role: text<'admin' | 'user'>('role'),
});
// After
const test = mysqlTable('test', {
role: text('role', { enum: ['admin', 'user'] }),
});
🎉 Allowed passing an array of values into .insert().values() directly without spreading:
const users = mysqlTable('users', {
id: int('id').primaryKey(),
name: text('name').notNull(),
});
await users.insert().values([
{ name: 'John' },
{ name: 'Jane' },
]);
The spread syntax is now deprecated and will be removed in one of the next releases.
🎉 Added "table creators" to allow for table name customization:
import { mysqlTableCreator } from 'drizzle-orm/mysql-core';
const mysqlTable = mysqlTableCreator((name) => `myprefix_${name}`);
const users = mysqlTable('users', {
id: int('id').primaryKey(),
name: text('name').notNull(),
});
// Users table is a normal table, but its name is `myprefix_users` in runtime
🎉 Implemented support for selecting/joining raw SQL expressions:
// select current_date + s.a as dates from generate_series(0,14,7) as s(a);
const result = await db
.select({
dates: sql`current_date + s.a`,
})
.from(sql`generate_series(0,14,7) as s(a)`);
🐛 Fixed a lot of bugs from user feedback on GitHub and Discord (thank you! ❤). Fixes #293 #301 #276 #269 #253 #311 #312
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Your coding agent can read these notes before it upgrades. Set up the MCP server →