Update prisma monorepo to v5 (major)
This MR contains the following updates:
Package | Type | Update | Change |
---|---|---|---|
@prisma/client (source) | dependencies | major | ^3.14.0 -> ^5.0.0 |
prisma (source) | devDependencies | major | ^3.14.0 -> ^5.0.0 |
⚠ Dependency Lookup Warnings ⚠
Warnings were logged while processing this repo. Please check the Dependency Dashboard for more information.
Release Notes
prisma/prisma (@prisma/client)
v5.2.0
Highlights
Improved Prisma Client experience for Prisma Accelerate and Data Proxy
In this release, we’ve made the following improvements to Prisma Client when using Prisma Accelerate or Prisma Data Proxy:
-
Prisma Client will now automatically determine how it should connect to the database depending on the protocol in the connection string. If the connection string starts with
prisma://
, Prisma Client will try to connect to your database using Prisma Accelerate or Prisma Data Proxy. -
Prisma Studio now works with Prisma Data Proxy and Prisma Accelerate.
-
We’ve introduced a new
--no-engine
flag which will prevent a Query Engine file from being included in the generated Prisma Client. This flag will also help ensure the bundle size of your application remains small by excluding the Query Engine files from the generated Prisma Client.prisma generate --no-engine
The
--data-proxy
and--accelerate
flags have not been removed but are now aliases for the new--no-engine
flag.We recommend using the
--no-engine
flag when generating Prisma Client that uses either Accelerate or Data Proxy.
Simplified connection string override in Prisma Client
This release simplifies the API used when programmatically overriding the connection string by introducing the datasourceUrl
property in Prisma Client’s constructor. This means you do not have to use the datasource name defined in your Prisma schema.
const prisma = new PrismaClient({
datasourceUrl: "postgresql://johndoe:randompassword@localhost:5432/mydb",
})
Query performance improvements
Continuing our work from 5.1.0 we made further performance improvements around the queries Prisma executes, targeting one-to-many relation fields and nested updates.
LIMIT
in one-to-many relations on a single parent
Use In cases where there is a single parent with a one-to-many relation included (findFirst
, findUnique
, findMany({ take: 1 })
), we now utilize LIMIT
at the database level to restrict the number of related items returned instead of retrieving all related items into memory and performing a take
in memory.
For situations where you have many related objects but only need a few, you should see a dramatic improvement in speed and memory usage.
Note: we are still working on bringing this improvement to other parts of Prisma Client in upcoming releases. If multiple parent records are returned, the previous behavior is used.
Further improvements for nested writes
Thanks to our introduction of using RETURNING
in some cases in 5.1.0, we could now improve performance in nested writes by removing reload nodes. This will now result in one less query per relation traversed in a nested write. For more info, check out the pull request.
Prisma Client query
await prisma.post.update({
where: { id: 1 },
data: {
comment: {
update: {
data: {
body: "Updated comment body"
}
}
}
},
select: {
id: true,
title: true,
}
})
Before v5.2.0
SELECT "Post"."id", "Post"."title" FROM "Post" WHERE ("Post"."id" = $1 AND 1=1) LIMIT $2 OFFSET $3
SELECT "Post"."id", "Post"."userId" FROM "Post" WHERE "Post"."id" = $1 OFFSET $2
SELECT "User"."id" FROM "User" WHERE (1=1 AND "User"."id" IN ($1)) OFFSET $2
SELECT "User"."id" FROM "User" WHERE ("User"."id" = $1 AND 1=1) LIMIT $2 OFFSET $3
SELECT "User"."id", "User"."commentId" FROM "User" WHERE "User"."id" = $1 OFFSET $2
SELECT "Comment"."id" FROM "Comment" WHERE (1=1 AND "Comment"."id" IN ($1)) OFFSET $2
UPDATE "Comment" SET "body" = $1 WHERE ("Comment"."id" = $2 AND 1=1) RETURNING "Comment"."id"
SELECT "Post"."id", "Post"."title" FROM "Post" WHERE "Post"."id" = $1 LIMIT $2 OFFSET $3
5.2.0 and later
SELECT "Post"."id", "Post"."title", "Post"."userId" FROM "Post" WHERE ("Post"."id" = $1 AND 1=1) LIMIT $2 OFFSET $3
SELECT "User"."id" FROM "User" WHERE (1=1 AND "User"."id" IN ($1)) OFFSET $2
SELECT "User"."id", "User"."commentId" FROM "User" WHERE ("User"."id" = $1 AND 1=1) LIMIT $2 OFFSET $3
SELECT "Comment"."id" FROM "Comment" WHERE (1=1 AND "Comment"."id" IN ($1)) OFFSET $2
UPDATE "Comment" SET "body" = $1 WHERE ("Comment"."id" = $2 AND 1=1) RETURNING "Comment"."id"
SELECT "Post"."id", "Post"."title" FROM "Post" WHERE "Post"."id" = $1 LIMIT $2 OFFSET $3
Fixes and improvements
Prisma Client
- CFW: Avoid including Query Engine when data proxy is enabled
- Local Prisma Studio does not work with Data Proxy
- Postinstall hook always generates non Data Proxy Prisma Client
limit
is gone whenfindUnique
with include relationCannot fetch data from service: include is not a function
Error while using Next.js with Data Proxytake
key doesn't work correctly for nested query that returns one item with its nested children- Prisma Client Edge: environment variables are not working with the "new" Module Worker syntax for Cloudflare Workers
- Add documentation to "PrismaClient is unable to be run in the browser"
- Change how Data Proxy Client deals with unsupported preview features
- Custom Prisma Client output location breaks Prisma Data Proxy in NextJS
- GetPayload type error since 4.16.1 "Two different types with this name exist, but they are unrelated."
- Browser bundle: Unhandled Runtime Error when upgrading to 5.1.0 from 5.0.0
- Prisma Client:
disconnect: true
does not appear to delete the foreign key in the returned data - Prisma Client errors with "TypeError: Cannot create proxy with a non-object as target or handler" when using result client extension with no
needs
andcount
method - Upgrading from Prisma 5.0.0 -> 5.1.0 results in "TS2321: Excessive stack depth comparing types" error using
mockDeep<PrismaClient>()
- Unnecessary reads for to-one nested updates
- Better error message if
@prisma/client/edge
can not find environment variable - 5.1: Alias for old name for
<Model>CountOutputTypeDefaultArgs
does not exist - Incorrect pagination for nested m2m chunked reads
Prisma Migrate
- RustPanic on
prisma generate
when Unsupported field defined in a Composite type - Use PostgreSQL System Information Functions instead of manually joining fields
- Duplicate expression index comment whenever db pull is run
Credits
Huge thanks to @skyzh, @alula, @michaelpoellath, @RobertCraigie, @darthmaim, @Gerschtli, @andyjy, @mejiaej, @iurylippo, @mrazauskas, @coder246, @RDIL for helping!
v5.1.1
Today, we are issuing the 5.1.1
patch release.
Fixes in Prisma Client
- Browser bundle: Unhandled Runtime Error when upgrading to 5.1.0 from 5.0.0
- Prisma Client:
disconnect: true
does not appear to delete the foreign key in the returned data - Prisma Client errors with "TypeError: Cannot create proxy with a non-object as target or handler" when using result client extension with no
needs
andcount
method
v5.1.0
Today, we are excited to share the 5.1.0
stable release
Highlights
After two big releases where we released Client extensions for production usage (4.16.0
) and made Prisma faster by default (5.0.0
), we have focused on some smaller issues to make the experience with these new features even better.
Community contributions
Our community has been on the roll! We appreciate everyone who helps us by opening a GitHub issue or proposing a fix via Merge Requests. In this release, we're excited to highlight multiple community contributions:
- Fix IPv6 not working for relational databases: https://github.com/prisma/prisma-engines/pull/4051 by @alula
- Middlewares: Add to
PrismaAction
type, missingfindUniqueOrThrow
andfindFirstOrThrow
https://github.com/prisma/prisma/pull/17471 by @mejiaej and missinggroupBy
https://github.com/prisma/prisma/pull/19985 by @iurylippo - Better error message in currently non-supported runtimes like Browser or Vercel Edge Runtime https://github.com/prisma/prisma/pull/20163 by @andyjy
- Remove error messages for valid NixOS setups https://github.com/prisma/prisma/pull/20138 by @Gerschtli
Better performance: Fewer SQL queries on PostgreSQL & CockroachDB
In our continued and ongoing work to make Prisma faster, we identified some Prisma Client queries that led to multiple SQL statements being executed — although in specific databases, that was not necessary.
Hence we optimized our internal SQL generation for PostgreSQL and CockroachDB to generate more efficient SQL queries:
create
query
Simple In a simple create
query, RETURNING
makes the second query and the transaction statements obsolete:
Prisma Client query
prisma.user.create({
data: { name: "Original name" }
})
Before v5.1.0
BEGIN
INSERT INTO "User" ("name") VALUES ($1) RETURNING "User"."id"
SELECT "User"."id", "User"."name" FROM "User" WHERE "User"."id" = $1;
COMMIT
5.1.0 and later
-- Sends 1 statement (instead of 2) and omits the transaction
INSERT INTO "User" ("name") VALUES ($1) RETURNING "User"."id", "User"."name"
update
query
Simple For a simple update
query, RETURNING
makes both additional queries and the transaction statements obsolete:
Prisma Client query
prisma.user.update({
where: { id: 1 },
data: { name: "updated" }
})
Before v5.1.0
BEGIN
SELECT id FROM "User" WHERE "User".id = 1;
UPDATE "User" SET name = 'updated' WHERE "User".id = 1;
SELECT id, name FROM "User" WHERE "User".id = 1;
COMMIT
5.1.0 and later
-- Sends 1 statement (instead of 3) and omits the transaction
UPDATE "User" SET name = 'updated' WHERE "User".id = 1 RETURNING "User".id, "User".name;
update
query, return with relation value
Simple One SELECT
query could easily be dropped in a simple update
query that should return a relation value as well:
Prisma Client query
prisma.user.update({
where: { id: 1 },
data: { name: "updated" },
includes: { posts: true }
})
Before v5.1.0
BEGIN
SELECT id FROM "User" WHERE "User".id = 1;
UPDATE "User" SET name = 'updated' WHERE "User".id = 1;
SELECT id, name FROM "User" WHERE "User".id = 1;
SELECT id, title FROM "Post" WHERE "Post"."userId" = 1;
COMMIT
5.1.0 and later
-- Sends 3 statements (instead of 4)
BEGIN
UPDATE "User" SET name = 'updated' WHERE "User".id = 1 RETURNING "User".id;
SELECT id, name FROM "User" WHERE "User".id = 1;
SELECT id, title FROM "Post" WHERE "Post"."userId" = 1;
COMMIT
update
query
Empty An empty update
query can be optimized to skip the transaction and the second identical query by creating specific handling for this edge case in our code:
Prisma Client query
prisma.user.update({
where: { id: 1 },
data: {},
})
Before v5.1.0
BEGIN
SELECT id, name FROM "User" WHERE "User".id = 1;
SELECT id, name FROM "User" WHERE "User".id = 1;
COMMIT
5.1.0 and later
-- Sends 1 statement (instead of 2) and omits the transaction
SELECT id, name FROM "User" WHERE "User".id = 1;
update
query (but do not return relation value)
Simple + relation An update of both the model and its relation, we could drop 2 SELECT
queries that we did before without ever using their return values:
Prisma Client query
prisma.user.update({
where: { id: 1 },
data: {
name: "updated",
posts: {
update: {
where: { id: 1 },
data: {
title: "updated"
}
}
}
}
})
Before v5.1.0
BEGIN
SELECT id, name FROM "User" WHERE "User".id = 1;
UPDATE "User" SET name = 'updated' WHERE "User".id = 1 RETURNING "User".id;
SELECT "id", "postId" FROM "Post" WHERE "Post".id = 1;
UPDATE "Post" SET title = 'updated' WHERE "Post"."userId" = 1 AND "Post".id = 1;
SELECT id, name FROM "User" WHERE "User".id = 1;
COMMIT
5.1.0 and later
-- Sends 3 statements (instead of 5)
BEGIN
UPDATE "User" SET name = 'updated' WHERE "User".id = 1 RETURNING "User".id, "User".name;
SELECT "id", "postId" FROM "Post" WHERE "Post".id = 1;
UPDATE "Post" SET title = 'updated' WHERE "Post"."userId" = 1 AND "Post".id = 1;
COMMIT
In the next releases, we will continue optimizing Prisma Client queries to only run the minimal amount of SQL queries necessary.
If you notice any Prisma Client queries that are affected right now, please check the issues under our performance/queries
label. If you didn’t find one for what you’re seeing, please create a new issue. This will be super useful for us to understand all (edge) cases. Thank you!
directUrl
Prisma Studio now supports Our CLI command prisma studio
that opens Prisma Studio now also can use the directUrl
property of the datasource
block so you can make it talk to a different database than defined in url
. This makes it easier to use Studio alongside the Prisma Data Proxy and Accelerate.
Prisma Client: No more type clashes
We fixed (almost) all cases where using a specific term as a model name in your Prisma Schema would lead to a type clash due to Prisma’s generated typings. As a result of a type clash, it was not possible to use that model in your code (this was e.g. the case if you named a model Model
or ModelUpdate
).
We also deprecated the <ModelName>Args
type as part of that fix. Going forward, <ModelName>DefaultArgs
should be used instead.
Fixes and improvements
Prisma Client
- Reduce the number of generated SQL statements for Updates/Inserts
- [v2.17.0] Missing client TS types Aggregate*Args
- Reduce transactions for writes
- Incorrect Include typings when having models called
X
andXUpdate
- Model named "Check" is incorrectly typed
- Models named Query cause an internal GraphQL Parse Error
- Naming an entity "Query" leads to an error
- Type name clash when
Model
andModelUpdate
is defined in the schema - Duplicate identifier 'CheckSelect'
@prisma/internals
(previously @prisma/sdk) uses deprecated dependenciesuuid@3.4.0
viatemp-write 4.0.0
- naming a model
Datasource
breaks generated return types - Certain
model
names cause clashes in generated types - Type error on query with select field (although query runs successfully)
$extends
TS error: "Inferred type of this node exceeds the maximum length the compiler will serialize" with"declaration": true
intsconfig
- Update operation includes multiple where statements for the same fields
- Type conflict when naming a table {something} and a second table {something}Result
Type '"findUniqueOrThrow"' is not assignable to type 'PrismaAction'
- Naming a model
Promise
breaks types forPrismaPromise
- Prisma can't connect with an IPv6 host (on e.g. Fly.io)
include
not working on models ending with...Update
with unique compound index- Prisma Client: fixing type name clashes from generated client
- Prisma Client: wrong type when using spread operator to set default values on query args
- The generated updateArgs have no update attribute
- 4.16.1 breaks type check
LogLevel
enum conflicts with built-in Prisma type- Using
Prisma.XyzFindManyArgs
breaksfindMany
typing in v4.16.0+ this.$on("beforeExit")
doesn't work anymore on 5.0.0- Wrong nullable types with fluent API in Prisma 5.0
Error: Unknown value type
on nested create- Prisma 5.0 Migration
findUnique
on@unique
columns that are enums <Tablename>UpsertArgs
select field does not match type fordb.<tablename>.upsert(item)
- TypeScript Error TS2322 when assigning JavaScript Date object to Prisma DateTime field
- npm install of Prisma CLI fails on preinstall with no logs when Node.js version is lower than minimum
- Types wrongly accept non-array parameter
by
ingroupBy
in 5.0.0 - CLI errors with
TypeError [ERR_INVALID_URL]: Invalid URL
whenHTTP(S)_MROXY
en var has is set to a URL without a protocol tsc --watch
fails withJavaScript heap out of memory
error- Hovering over types (intellisense) shows confusing
GetResult
- Internal query batching fails when the table name is 'stores'
- Client extensions result extensions should be applied after query extensions
Prisma Studio
Language tools (e.g. VS Code)
- The extension for VS Code ignores the modern telemetry flag
- Prisma VS Code extension with mongodb provider crashes when a relation field/type is not defined
- Editing schema.prisma results in wasm panics
Credits
Huge thanks to @skyzh, @alula, @michaelpoellath, @RobertCraigie, @Gerschtli, @andyjy, @mejiaej, @iurylippo, @mrazauskas for helping!
v5.0.0
We’re excited to share the 5.0.0
release today
Prisma 5.0.0
contains a lot of changes that improve Prisma’s performance, especially in serverless environments. If you want to learn more about the performance improvements, we wrote a blog post that sums up all the changes we made: Prisma 5: Faster by Default.
As this is a major release, it includes a few breaking changes that might affect a small group of our users. Before upgrading, we recommend that you check out our upgrade guide to understand the impact on your application.
Highlights
Here’s a summary of the changes:
- Preview features moved to General Availability
-
jsonProtocol
: improves communication between Prisma Client and the query engine, makes Prisma faster by default. -
fieldReference
: adds support for comparing columns of the same table. -
extendedWhereUnique
: adds support for non-unique columns insidewhere
clauses for queries that operate on unique records.
-
- General improvements and breaking changes
- Dependency version changes
- Minimum Node.js version change to 16.13.0
- Minimum TypeScript version change to 4.7
- Minimum PostgreSQL version change to 9.6
- Prisma Client embedded SQLite version upgrade to 3.41.2
- Main Changes
- Removal of
rejectOnNotFound
property - Removal of some array shortcuts
-
cockroachdb
provider is now required when connecting to a CockroachDB database - Removed
runtime/index.js
from the generated Prisma Client
- Removal of
- Other Changes
- Removal of deprecated flags in the Prisma CLI
- Removal of the
beforeExit
hook from the library engine - Removal of deprecated
prisma2
executable - Removal of deprecated
experimentalFeatures
generator property in the Prisma schema - Renamed
migration-engine
toschema-engine
- Dependency version changes
A JSON-based protocol that improves Prisma’s performance
We’re thrilled to announce that the jsonProtocol
Preview feature is now Generally Available. You can now remove the Preview feature flag from your schema after upgrading. We made the JSON-based wire protocol the default protocol used for communication between Prisma Client and the query engine.
We introduced this feature in version 4.11.0 to improve Prisma’s performance. Previously, Prisma used a GraphQL-like protocol to communicate between Prisma Client and the query engine. Applications with larger schemas had higher CPU and memory consumption compared to smaller schemas which created a performance bottleneck.
The JSON-based wire protocol improves efficiency when Prisma Client is communicating with the query engine.
Removal of array shortcuts
We took the opportunity to remove some array shortcuts to make our typings more consistent and logical. These shortcuts were a way to add a single element as a value to an array-based operator instead of wrapping a single element in an array. We will now require array values for the following:
-
OR
operator shortcuts -
in
andnotIn
operator shortcuts - PostgreSQL JSON
path
field shortcut - Scalar list shortcuts
- MongoDB Composite types list shortcuts
Here’s an example query using the OR
operator shortcut for a single element;
await prisma.user.findMany({
where: {
- OR: { email: 'alice@prisma.io' }
+ OR: [{ email: 'alice@prisma.io' }]
}
})
We recommend taking a look at the upgrade guide to learn how you can update your queries to work in Prisma 5.
Support for comparing multiple columns
We’re excited to announce that the fieldReference
Preview feature is now stable and Generally Available. This means you can use this feature without the Preview feature flag in your Prisma schema.
We first introduced this feature in 4.5.0 to add the ability to compare columns on the same table. For example, the following query returns records where the quantity
value is less than the warnQuantity
of a product:
await prisma.product.findMany({
where: {
quantity: { lte: prisma.product.fields.warnQuantity }
},
})
To learn more about this feature, refer to our documentation.
Support for filtering non-unique columns in queries for a unique record
We’re excited to announce the extendedWhereUnique
Preview feature is now Generally Available. This means you can use the feature without the Preview feature flag in the Prisma schema.
We first introduced this feature in version 4.5.0 to add support for non-unique columns inside where
clauses for queries that operate on unique records, such as findUnique
, update
, and delete
, which was previously not possible.
For example, consider the following model:
model Article {
id Int @​id @​default(autoincrement())
content String
version Int
}
You can filter on non-unique columns such as the version
field as follows:
await prisma.article.findUnique({
where: {
id: 5,
version: 1 // filter on the `version` field was not available before Prisma 4.5.0
},
});
To learn more about this feature, refer to our documentation.
Minimum Node.js version change to 16.13.0
The minimum version of Node.js Prisma supports is 16.13.0
. If you're using an earlier version of Node.js, you will need to upgrade your Node.js version.
Refer to our system requirements for the minimum versions Prisma requires.
Minimum TypeScript version change to 4.7
The minimum version of TypeScript Prisma supports is 4.7. If your project is using an earlier version of TypeScript, you will need to upgrade your TypeScript version.
Refer to our system requirements for the minimum versions Prisma requires.
Minimum PostgreSQL version change to 9.6
The minimum version of PostgreSQL Prisma supports is version 9.6. If you’re either using 9.4 or 9.5, you will need to update your PostgreSQL version to at least 9.6.
Refer to our system requirements for the minimum database versions Prisma requires.
Prisma Client embedded SQLite version upgrade
We upgraded the embedded version of SQLite from 3.35.4 to 3.41.2. We do not anticipate any breaking changes or changes needed in projects using SQLite. However, if you’re using SQLite, especially with raw queries that might go beyond Prisma's functionality, make sure to check the SQLite changelog.
rejectOnNotFound
property
Removal of In version 5.0.0, we removed the rejectOnNotFound
parameter from Prisma Client that was deprecated in version 4.0.0. We removed this feature to provide better type-safety using the findUniqueOrThrow
and findFirstOrThrow
methods as well have a consistent API.
If you are using the rejectOnNotFound
parameter we recommend either:
- Replacing your queries with the
findFirstOrThrow
orfindUniqueOrThrow
methods if enabled at a query-level - Using a Prisma Client extension to overload the
findFirstOrThrow
andfindUniqueOrThrow
model methods with your custom error handling if enabled at the client-level
We recommend taking a look at the upgrade guide for more information on how to adapt your application if you’re using rejectOnNotFound
.
cockroachdb
provider is now required when connecting to a CockroachDB database
Prior to adding explicit support for CockroachDB with the cockroachdb
provider in 3.9.0, it was possible to use the PostgreSQL provider when working with CockroachDB databases.
We’re now making it mandatory to use the CockroachDB connector when working with CockroachDB databases. CockroachDB and PostgreSQL have a few differences such as the available native types which impact the generated migrations.
If you were using the PostgreSQL connector to work with CockroachDB, take a look at the upgrade guide to learn how you can update your connector.
runtime/index.js
file from Prisma Client
Removal of the generated With Prisma 5, we removed the runtime/index.js
file from Prisma Client. If you were using APIs from runtime/index.js
, such as Decimal
, PrismaClientKnownRequestError
, NotFoundError
, PrismaClientUnknownRequestError
, we recommend updating your imports:
- import { Decimal } from '@​prisma/client/runtime'
+ import { Prisma } from '@​prisma/client'
// Usage update of Prisma Client's utilities
- Decimal
+ Prisma.Decimal
We recommend taking a look at the upgrade guide to learn how you can migrate to Prisma 5
beforeExit
hook from the library
query engine
Removal of the We removed the beforeExit
hook from the default library
Query Engine. We recommend using the built-in Node.js exit events.
-prisma.$on('beforeExit', () => { /* your code */ })
// Replacements
process.on('beforeExit', () => { /* your code */ })
process.on('exit', exitHandler)
process.on('SIGINT', exitHandler)
process.on('SIGTERM', exitHandler)
process.on('SIGUSR2', exitHandler)
We recommend taking a look at the upgrade guide to learn how you can migrate to Prisma 5.
prisma2
executable
Removal of deprecated When we released Prisma 2, the prisma2
executable was used to differentiate it from Prisma 1. In a later release, the prisma2
CLI took over the prisma
executable name.
The prisma2
executable has been deprecated for a while and will now be removed. If you’re using prisma2
in your scripts, replace it with prisma
.
Removal of deprecated flags in the Prisma CLI
We removed the following deprecated flags in the Prisma CLI:
-
--preview-feature
: used in theprisma db execute
,prisma db seed
, andprisma migrate diff
commands -
--experimental
and--early-access-feature
: used in theprisma migrate
commands such asprisma migrate dev
-
--force
: forprisma db push
. The--force
flag was replaced by--accept-data-loss
in version 2.17.0 -
--experimental-reintrospection
and--clean
: forprisma db pull
In the event you’re using one of these flags, we recommend removing the flags.
experimentalFeatures
generator property
Removal of deprecated In this release, we removed the experimentalFeatures
property that used to be in the generator property in the Prisma schema but has been renamed to previewFeatures
for a long time now. If you’re still using this property, you can either manually rename it to previewFeatures
or use the VS Code action to rename it if you’re using the latest version of the Prisma VS Code extension.
migration-engine
to schema-engine
Renamed In this release, we renamed the migration-engine
, responsible for running introspection and migration commands, to schema-engine
. For the majority of our users, no changes will be required. However, if you explicitly include or exclude the engine files you will need to update your code references. Refer to the upgrade guide for more information.
Fixes and improvements
Prisma Client
- Getting a string '(array)' in the generator config instead of the expected value when array is used
- Misleading error message from
create
call - Client extensions incorrect typings when defined both specific model and all models methods
- UncheckedUpdateManyInput types lead to conflicting names
<Model>RelationFilterInput
does not take nullability into account- Full text search query with
OR
broke after opting in tojsonProtocol
feature. - Prisma Client: remove list shorthands (for
jsonProtocol
) - Remove outdated preview feature aliases (transactionApi, aggregateApi)
- Prisma Client generator: remove creation of a package.json
- Prisma Client: make
jsonProtocol
GA - Only upload engines files to
binaries.prisma.sh/all_commits/
- Prisma Client: remove "beforeExit" hook from LibraryEngine/DataProxyEngine
- Prisma Client: remove
rejectOnNotFound
- Prisma Client: remove
runtime/index.js
bundle from client - Prisma CLI: remove non-existing
prisma dev
command - Prisma Client: remove legacy
photonResolver
andprovider=photonjs
handling - Prisma Client: make
fieldReference
GA - Prisma Client: make
extendedWhereUnique
GA - Remove backward compatibility for Prisma Client < 2.20 and Prisma CLI >= 2.20
- Prisma CLI: remove
prisma2
"executable" - Query in findMany in prisma extends returns a wrong type
- Can't specify $queryRawUnsafe return type after extending prisma client
- FindMany returns wrong type after extending prisma client
- 4.16.x cannot wrap
$extend
in factory function whencompilerOptions.composite
istrue
- 4.16: (MongoDB) Generated types for list composites are incorrect
- Prisma Client Extensions: $allModels: { $allOperations } sets
query
type tonever
- Prisma Schema Type inside a Type not generating a right Payload
- Field references are not available on extended clients
- Prisma Client fluent API does not work with extends anymore on 4.16.1
- Prisma not generating correct payload for types in models for MongoDB for 4.16.1
- Prisma requires to install bun when generating client library
- Getting wrong types with prisma client extensions
- Prisma Client: updating to 4.16.0 or 4.16.1 breaks Cloudflare worker, it errors with
The package "path" wasn't found on the file system but is built into node
- Result types are incorrectly inferred when
undefined
explicitly passed toselect
/include
- Migrating to release: 4.16.2 throws typescript error: "TS1005: '?' expected".
Prisma Migrate
- Make connecting to a cockroachdb database with
provider = "postgresql"
an error - Remove the deprecated
experimentalFeatures
generator property - Remove support for PostgreSQL 9.4 and 9.5
- Upgrade embedded SQLite version
- Drop support for Node.js v14
db pull
: Remove the version checker from introspection- Prisma CLI: remove undocumented
doctor
command - Rename migration-engine to schema-engine
- Prisma CLI: remove deprecated flags, arguments and "old migrate" logic
- Remove obsolete
experimentalFeatures
generator property - Remove usage / mention of
experimentalFeatures
Language tools (e.g. VS Code)
Credits
Huge thanks to @michaelpoellath, @RobertCraigie, @Coder246, @RDIL, @oohwooh, @rqres, @zhiyan114, @spudly, @hayes, @boennemann, @DongGunYoon for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, July 13 at 5 pm Berlin | 8 am San Francisco.
v4.16.2
Today, we are issuing the 4.16.2
patch release.
Fixes in Prisma Client
- 4.16: (MongoDB) Generated types for list composites are incorrect
- Getting wrong types with prisma client extensions
- Prisma Client fluent API does not work with extends anymore on 4.16.1
- Prisma Client Extensions:
$allModels: { $allOperations }
sets query type tonever
- Result types are incorrectly inferred when
undefined
explicitly passed toselect
/include
v4.16.1
Today, we are issuing the 4.16.1
patch release.
Fixes in Prisma Client
- Field references are not available on extended clients
- 4.16.x cannot wrap
$extend
in factory function whencompilerOptions.composite
istrue
- Prisma Schema Type inside a Type not generating a right Payload
- Query in findMany in prisma extends returns a wrong type
- 4.16.0 Count query is not returning the right type when in a transaction
- FindMany returns wrong type after extending prisma client
- Can't specify $queryRawUnsafe return type after extending prisma client
v4.16.0
Highlights
This release promotes the following Preview features to General Availability:
- Prisma Client extensions
- Ordering by nulls first and last
- Count by filtered relation
Prisma Client extensions are Generally Available
Today, we’re very excited to announce that Prisma Client extensions are Generally Available and production-ready! This means you can use the feature without the clientExtensions
Preview feature flag.
Prisma Client extensions are a powerful new feature for adding functionality on top of your Prisma Client in a type-safe manner. With this feature, you can create simple, but flexible solutions.
Prisma Client extensions have 4 different types of components that can be included in an extension:
- Result extensions components: add custom fields and methods to query result objects, for example, virtual/computed fields.
-
Model extensions components: enable you to add new methods to your models alongside existing model methods such as
findMany
. - Query extensions components: let you hook into the lifecycle of a query and perform side effects, modify query arguments, or modify the results in a type-safe way. These are an alternative to middleware that provide complete type safety and can be applied in an ad-hoc manner to different extensions.
- Client extensions components: allow you to add new top-level methods to Prisma Client. You can use this to extend Prisma Client with functionality that isn’t tied to specific models.
const prisma = new PrismaClient().$extends({
name: "extension-name",
result: { /* ... */ },
model: { /* ... */ },
query: { /* ... */ },
client: { /* ... */ },
});
You can also create and publish extensions for others to use. Learn more about how to share extensions in our documentation.
More features and changes made to Client Extensions
We also made the following improvements to Prisma Client extensions in preparation for General Availability:
-
Added a top-level
$allOperations
method forquery
component that captures all model operations as well as top-level raw queries. Refer to our documentation for more information.const prisma = new PrismaClient().$extends({ query: { $allOperations({ args, query, operation, model }) { /* your extension's logic here */ } } })
-
Prisma.validator
can now also be used for extended types:const prisma = new PrismaClient().$extends({/* ... */}) const data = Prisma.validator(prisma, 'user', 'findFirst', 'select')({ id: true, })
-
query
callbacks for$queryRaw
and$executeRaw
will always receiveSql
instance asargs
. This instance can be used to compose a new query usingPrisma.sql
:const prisma = new PrismaClient().$extends({ query: { $queryRaw({ args, query }) { return query(Prisma.sql`START TRANSACTION; ${args}; COMMIT;`) } } })
-
$on
cannot be called after extending Prisma Client. Therefore, if you want to use event handlers together with extensions, we recommend using the$on
method before$extends
.const prisma = new PrismaClient() .$on(/* ... */) .$extends({/* ... */})
-
We updated the import path for utilities used for authoring extension to
@prisma/client/extension
rather than@prisma/client
+ import { Prisma } from "@​prisma/client/extension" - import { Prisma } from "@​prisma/client"
Deprecating Middleware
We also took this opportunity to deprecate Prisma Client’s middleware. We recommend using to using Prisma Client query
extension components which can be used to achieve the same functionality and with better type safety.
🚧 Middleware will still be available in Prisma Client’s API. However, we recommend using Prisma Client extensions over middleware.
Ordering by nulls first and last is now Generally Available
Starting with this release, we’re excited to announce that orderByNulls
is now Generally Available! This means you can use the feature without the orderByNulls
Preview feature flag.
We introduced this feature in 4.1.0 to enable you to sort records with null fields to either appear at the beginning or end of the result.
The following example query sorts posts by updatedAt
, with records having a null value at the end of the list:
await prisma.post.findMany({
orderBy: {
updatedAt: { sort: 'asc', nulls: 'last' },
},
})
To learn more about this feature, refer to our documentation.
We’re excited to see what you will build! Feel free to share with us what you build on Twitter, Slack, or Discord.
Count by filtered relation is now Generally Available
This release moves the filteredRelationCount
Preview feature to General Availability! This means you can use the feature without the filteredRelationCount
Preview feature flag.
We first introduced this feature in 4.3.0 to add the ability to count by filtered relations.
The following query, for example, counts all posts with the title “Hello!”:
await prisma.user.findMany({
select: {
_count: {
select: {
posts: { where: { title: 'Hello!' } },
},
},
},
})
To learn more about this feature, refer to our documentation.
Introspection warnings for expression indexes
In the last two releases, 4.13.0 and 4.14.0, we added 9 introspection warnings. These warnings surface features in use in your database that cannot currently be represented in the Prisma schema.
In this release, we’re adding one more introspection warning to the list: expression indexes.
On database introspection, the Prisma CLI will surface the feature with a warning, and a comment in your Prisma schema for sections for each feature in use. The warnings will also contain instructions for workarounds on how to use the feature.
Fixes and improvements
Prisma Client
- Attach comments to enum values
- Extend Prisma Client
- Triple-slash Comments should attach to Composite Types
- Nested disconnect fails on MongoDB with extendedWhereUnique
- [ClientExtensions, TypeScript] Fields of custom type aren't available when using the ClientExtensions preview-feature, unless
select
'd explicitly. - Extensions incorrect typings generated (casing)
- Misleading error message of
prisma generate
when running it directly after installingprisma
- Prisma.validator: with clientExtensions enabled, Typescript can no longer compute types
- enum docstrings do not make it to the prisma client
- VScode behavior is very slow while using clientExtensions
- Client extensions in interactive transactions are bound to the base client
$runCommandRaw
is not passing the expected data to middleware or client extension- PCE: Improve runtime types in raw query extensions
- Sequential transactions run out of order when using client extensions and middleware
- Client Extension: Make
.prismaVersion.client
available on "@prisma/client/scripts/default-index" - Cannot create record with Prisma.DbNull when clientExtensions enabled
- Extended client raw queries fail when using the Prisma.sql helper
- jsonProtocol: array shortcut is missing for
distinct
field - Prisma Client Extension: support
Prisma.validator
- Prisma Client: make
clientExtensions
GA - PCE: Query extensions of
$queryRawUnsafe
also triggers$allModels.$allOperations
- PCE:
$on
applied to an extended client is also bound to the parent client - Type "never" returned from nested properties when using "select" after enabling data proxy + accelerate
$queryRaw*
is broken in interactive transactions together withclientExtensions
in4.16.0-dev.17
- Deploying to an offline environment fails because it tries to download a Prisma engine checksum file
- jsonProtocol: Wrong error message shown for validation error for checked/unchecked types
- Bug: FindXOrThrow don't get batched on the engine
Prisma Migrate
- Allow skipping sha checksum
- Documentation not available in DMMF for MongoDB
type
s prisma db pull
gets rid of@default(uuid())
on re-introspection
Language tools (e.g. VS Code)
Prisma Studio
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, June 22 at 5 pm Berlin | 8 am San Francisco.
v4.15.0
Highlights
For this release, we focused on fixing bugs and making smaller quality-of-life improvements.
prisma db seed
Support for custom arguments for This release adds support for defining and passing arbitrary arguments to prisma db seed
. This creates the opportunity for you to define your own arguments in your seed file that you could pass to the prisma db seed
command. A few example use-cases include, but are not limited to:
- Seeding different data in different environments
- Partially seeding data in some tables
Here is an example seed.ts
file that defines custom arguments for seeding different data in different environments:
// prisma/seed.ts
import { parseArgs } from "node:util";
const options = {
environment: { type: 'string', },
}
async function main() {
const { values: { environment } } = parseArgs({ options })
switch (environment) {
case "development":
/** do something for development */
break;
case "test":
/** do something for test environment */
break;
default:
break;
}
}
main()
You can then provide the environment
argument when executing the seed script as follows:
npx prisma db seed -- --environment development
Let us know what you think, share example usage of this feature, and create a bug report if you run into any issues.
Improved error messages when Query Engine file is not found
This release improves the error messages returned by Prisma Client when the Query Engine file is not found. A few reasons the Query Engine file might be missing from your application bundle include when:
- The downloaded Query Engine doesn’t match the runtime/ target platform your application is running on.
- The Query Engine is not copied to your final application bundle during the build step.
We hope these error messages are helpful while debugging your application.
Prisma VS Code extension improvements
In this release, we made a few improvements to our VS Code extension:
-
Updated the file system watcher that is responsible for restarting the TypeScript server when
prisma generate
is run to ensure the types are in syncNote:
- This new approach is currently only available on Windows and Linux. We plan on adding support for the new file system watcher on macOS soon.
- This requires both Prisma CLI & VS code extension version
4.15.0
or higher
-
Added Quick Fixes action for unique identifiers for MongoDB to add the
@map("_id")
attribute function when it’s missing on an identifier field -
Support for renaming symbols for composite types and views
Fixes and improvements
Prisma Client
- Prisma generate -
Error: write EPIPE
on WSL <-> Windows prisma generate
is blocked byquery-engine-rhel-openssl-1.0.x
opening in Notepad on Windows- Generated client output path hardcoded to build environment
- Issue with Yarn Workspace Monorepo: Query engine binary for current platform could not be found.
- Cloning a project with checked in
node_modules
(from another platform) leads to platform engine not being present - SvelteKit, Vite and Prisma "module not defined"
- Schema File Not Found in non monorepo with custom
output
- Deploying to Cloudflare Workers | "PrismaClient is unable to be run in the browser"
- Inline/bundle the contents of the prisma schema on generate
- Netlify:
Query engine library for current platform "rhel-openssl-1.0.x" could not be found. You incorrectly pinned it to rhel-openssl-1.0.x
- Query Engine Library Not Found
- No client schema when using PrismaClient during cached (standard) Netlify build
- Module "@prisma/client" has no exported member "PrismaClient"
- EPERM: operation not permitted
- prisma/client crashes when used with older versions of react-refresh
- Unable to run prisma cli in pnpm monorepo from workspace install
- Misleading error message when the query engine is not found
- When setting custom client output directory, generated package.json does not include "sideEffects: false"
- You already added the platform "debian-openssl-1.1.x" to the "generator" block in the "schema.prisma" file as described in https://pris.ly/d/client-generator, but something went wrong.
- Prisma seems to be looking in the wrong location for rhel-openssl-1.0.x
- Can't find prisma engine
Cannot find name '$PrismaModel'
due to featureextendedWhereUnique
with preview featurefieldReference
- Netlify build fails with PrismaClientInitializationError
- i'm getting the error while requesting the api
- Query engine library for current platform could not be found.
- Prisma unable to reconnect if initial connection fails
- GraphQL protocol encoder incorrectly turns empty array into empty object.
- GraphQL protocol: Invalid
Date
values silently turn intonulls
- @prisma/client/edge + Cloudflare Worker / wrangler = Could not resolve "os"
- Client is bricked from connecting to DB if first attempt fails.
- JSON protocol: incorrect recursive composites detection through multiple nesting levels
fieldReference
is not working with enums
Prisma Migrate
- Pass extra arguments to
prisma db seed
to the seed command - Typo in generating migration SQL to add enum.
Language tools (e.g. VS Code)
- MongoDB: Quick fix for missing
@map("_id")
annotation - Rename composite types
- Views: Support for rename
- TextDocument deprecation
- Lib name change vsce -> @vscode/vsce
Credits
Huge thanks to @RobertCraigie, @KhooHaoYit, @art049, @luxaritas, @mrazauskas, @maxmartynov, @haneenmahd for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, June 1 at 5 pm Berlin | 8 am San Francisco.
v4.14.1
Today, we are issuing the 4.14.1
patch release.
Fix in Prisma Client
v4.14.0
Request for feedback for Preview features
We would appreciate your feedback on a handful of Preview features to help us move them to General Availability soon. The Preview features include:
- PostgreSQL extensions
- Extended where unique
- Field reference support
- Order by Nulls
- Count by filtered relation
You can test them by enabling the Preview feature in your Prisma schema and giving them a try already in your Prisma schema, e.g., PostgreSQL extensions, or regenerating Prisma Client and trying them in your queries.
Highlights
Improved Prisma Client startup performance
For the last couple of months, we've been working hard to improve the performance of Prisma Client. We also published a blog post on how How We Sped Up Serverless Cold Starts with Prisma by 9x, which we recommend you give it a read.
This release continues with the same theme by making the size of the generated Prisma Client smaller. We have roughly halved the size of Prisma Client's dependencies.
More Introspection warnings for unsupported features
In 4.13.0, we introduced the first 6 introspection warnings that surface the existence of these features in your database and link to our documentation on how to manually work around the Prisma Schema with unsupported database features.
In this release, we added 3 more introspection warnings for the following features:
- Check Constraints (MySQL + PostgreSQL)
- Exclusion Constraints
- MongoDB $jsonSchema
On introspecting a database using any of these features, you will get a warning from the Prisma CLI and a comment in your Prisma schema where the feature is being used. The warning will also contain a link to instructions on how to manually use the feature.
Fixes and improvements
Prisma Client
- Generator output
client
leads toError: ENOENT: no such file or directory, open '.../node_modules/@​prisma/client/schema.prisma'
- DeprecationWarning: Implicit coercion to integer for exit code is deprecated
thread 'tokio-runtime-worker' panicked at 'internal error: entered unreachable code: No unsupported field should reach that path', query-engine\connectors\sql-query-connector\src\model_extensions\scalar_field.rs:70:44
- jsonProtocol:
in
argument of filter types does not accept scalars jsonProtocol
should report errors as nicely as before- Generated client with custom path containing string
client
:ENOENT: no such file or directory, open 'D:\<projectpath>\node_modules\.prisma\client\schema.prisma
- Can't find the schema when the project path contains the same name as the generated client folder
Prisma Migrate
- Build all glibc Linux binaries with CentOS 7
- Remove
Please create an issue ...
inMigrateEngine.ts
- Do not introspect exclusion constraints as Gist indexes
- Introspection warnings: move rendering from
DbPull.ts
to the engine - views: don't create local
views
folder on introspection if no views are found - RelationMode autocomplete uses incorrect casing
Language tools (e.g. VS Code)
Credits
Huge thanks to @RobertCraigie, @KhooHaoYit, @art049, @luxaritas, @mrazauskas for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, May 11 at 5 pm Berlin | 8 am San Francisco.
v4.13.0
Highlights
Introspection warnings for unsupported features
The Prisma Schema Language (PSL) currently doesn't support all database features and functionality of our target databases. The PSL is an abstraction over SQL and will keep evolving to address gaps in our database feature matrix.
Before this release, prisma db pull
did not pick up the unsupported features in a database. It was easy to lose them when running prisma migrate dev
based on an existing Prisma schema if not included in a migration file using custom migrations.
To avoid this, we added introspection warnings that surface the existence of these features in your database and link to our documentation on how to manually work around the Prisma Schema with unsupported database features.
In this release, we added introspection warnings for the following features:
- Partitioned tables
- PostgreSQL Row Level Security
- Index sort order,
NULLS FIRST
/NULLS LAST
- CockroachDB row-level TTL
- Comments
- PostgreSQL deferred constraints
Prisma CLI will output warnings on introspection (prisma db pull
) and add comments to your Prisma schema. In the coming releases, we will expand this to many more features labeled with topic: database-functionality
on GitHub.
Improved support for Netlify and Vercel build process
Netlify and Vercel cache project dependencies during the build process and reuse that cache until dependencies change. While this helps speed up the build process, any postinstall
scripts of these dependencies will not be executed.
Prisma uses a postinstall
script in its package to automatically trigger the customized generation of Prisma Client for your Prisma Schema. When a dependency cache is used, that generation process is not triggered, and an outdated Prisma Client may be used in your application.
When you update your Prisma Schema but not your dependencies, Prisma Client will not be generated for the new schema. For example, columns you added recently to one of your models will not be present in the Prisma Client API - causing errors.
This problem can be avoided by:
- Adding a custom
postinstall
script in yourpackage.json
file - Manually adding a
prisma generate
step to the “Build” scripts of Vercel and Netlify.
We now added detection of this scenario and will prevent a build without an additional prisma generate
. This will ensure you're aware of the problem early and get guidance on how to fix this problem. You can read more on how to do this in our docs — Vercel caching troubleshooting, Netlify caching troubleshooting.
Better support for pnpm as a package manager
Before this release, Prisma only used npm scripts which would lead to undesirable behavior for a project using a different package manager such as pnpm and yarn. This release improves the detection of the package managers in your project by using ni
. If you're still running into this problem, let us know by creating a GitHub issue.
Segmentation fault and TLS connection error fix
In this release, we've fixed a TLS connection error segmentation fault. This mostly affected users running on Node.js 17 or later with OpenSSL 1.1 when using TLS to connect to their database.
JSON protocol Preview feature feedback
We have fixed multiple bugs for the jsonProtocol
Preview feature and are close to making it Generally Available. We are still looking for feedback about its usage to ensure it is ready and works as expected for everyone.
We would appreciate it if you would try it out, help us polish the feature, and move it to General Availability. Testing it requires little effort. You can test it using the following steps:
- Enabling the
jsonProtocol
Preview feature in your Prisma schema - Re-generating Prisma Client
- Running your application or tests to make sure everything works
We encourage you to leave your feedback in this GitHub issue or create a bug report if your run into any issues.
Fixes and improvements
Prisma Client
prisma generate
fails when using pnpm workspaces because it tries to install prisma dependencies with npm or yarn- Netlify deploy does not pick up changes to schema file
- Vercel: Schema only change does not invalidate build cache
- Serverless deployments: Just making a schema level change to a repository does not invalidate
node_modules
cache that contains generated Client - pnpm: Can not
prisma generate
when@prisma/client
is not installed in project - Segmentation fault crash when using prisma client when using PostgreSQL
- Docker with
pnpm install
hangs on@prisma/client
postinstall - Automatic installation of missing dependencies isn't compatible with pnpm
- Prisma generate throws dependency error karma-chai
- Postinstall script fails with PNPM workspaces due to npm ERR! Cannot read properties of null (reading 'matches')
- Debian 11 Node 19.3.0 segmentation fault
- Prisma client segfault on Ubuntu 22.04
- Segmentation Fault in Postgres
- Using Prisma with pnpm results in inability to call database related commands
- Prisma Connect Causes NodeJS to Close With Exit Code 0
- 99056 segmentation fault (core dumped) node --require esbuild-register prisma/seed.ts
- JSON protocol: sibling composites of the same type are rejected
Prisma Migrate
- prisma db pull adds redundant comments: "This table is a partition table ..."
- Render warning code 30 in cli (PG RLS)
Language tools (e.g. VS Code)
Credits
Huge thanks to @KhooHaoYit, @rintaun, @maxmartynov, @haneenmahd for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, April 20 at 5 pm Berlin | 8 am San Francisco.
v4.12.0
Highlights
Introspection of Views SQL improvements (Preview)
The views
Preview feature significantly improved this release: prisma db pull
now reads the SQL query used to define a view and stores it in a .sql
file in a views
folder next to your Prisma schema.
Note: These
.sql
files are not yet used for creating or updating views during migrations yet. For now, we are only looking for feedback. Let us know if the introspected SQL files match the views picked up in your database and if the correct files were created in your filesystem.
We encourage you to leave feedback in this GitHub issue.
Improvements to JSON protocol (Early Preview)
In 4.11.0, we announced the jsonProtocol
Preview feature which had some rough edges. This release improves the Preview feature by providing polished and helpful error messages from Prisma Client when something goes wrong. Here is an example error message:
We would appreciate it if you would try it out to help us polish the feature and move it to General Availability. Testing it requires little effort. Please also leave any feedback in this issue, or open a new one if you want to report a bug.
Prisma Client startup performance
In this release, we've improved the startup performance of Prisma Client. We're keen on improving the performance of Prisma Client. If you experience any problems with the startup performance, be sure to report them so that we can look into them.
Open Telemetry tracing and logging for Prisma Client for Data Proxy
This release adds support for Open Telemetry tracing (via the tracing
Preview feature) and logging to Prisma Client for Data Proxy.
Fixes and improvements
Prisma Migrate
- Certain types of schema changes don't work with CockroachDB v22.2
- Completions: provided by engines break right at the start of a newline
db pull
fail with particular enum default value in column- Unable to reset CockroachDB for table with foreign key relationship on v22.2.
- Introspection of SQLite views
- Changing the Column Type to Enum on a model throws an error
- Introspection of the view definition statement
- MySQL multi-value index removes the primary key on introspection
Prisma Client
findUnique
used withPromise.all
returnsnull
- Missing
PrismaPromise
export after update from 4.9.0 to 4.11.0 - jsonProtocol doesn't query enum fields by default
- Prisma 4.11 breaks multilevel relation with compound primary keys (typings)
- 4.11.0:
Unique constraint failed on the fields
on query that worked in 4.10.1 jsonProtocol
Field/Enum is not included in the result of the findFirst/findMany function- Too many records are returned in 4.11.0 when using nested include and @unique field is null
- Objects with computed properties returned from an extended prisma client return true for any property name when calling hasOwn or hasOwnProperty on it
Language tools (e.g. VS Code)
Credits
Huge thanks to @KhooHaoYit, @rintaun, @ivan, @art049 for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, March 30 at 5 pm Berlin | 8 am San Francisco.
v4.11.0
Highlights
JSON protocol Early Preview
This release introduces an early Preview feature: JSON protocol.
During performance investigations and optimizations, we noticed that the existing implementation added a CPU and memory overhead that was especially noticeable for larger Prisma schemas. Therefore, we found an alternative way to express our queries without needing that overhead: JSON.
To try out the new protocol, enable the jsonProtocol
Preview feature in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["jsonProtocol"]
}
Regenerate Prisma Client to use the new JSON protocol.
For environments or situations where it is not viable to enable the Preview feature flag to your Prisma schema file, we also added an environment variable that you can use to force the use of the JSON Protocol Preview feature: MRISMA_ENGINE_MROTOCOL=json
.
Note: This is an early Preview feature with a significant limitation: Invalid input to Prisma Client will throw unpolished, internal errors that are less descriptive and user-friendly than our usual ones. We intend to improve these future releases. Using it with Data Proxy and Prisma Data Platform currently also leads to errors.
We expect using jsonProtocol
to improve Prisma Client's startup performance significantly. This will likely have a more significant impact on applications with larger Prisma schemas.
We would appreciate your feedback on this feature on the following particularly:
- Does using this preview feature introduce any regressions or problems in your application?
- If not, how does it influence the performance of your application? Can you share before and after measurements?
For feedback, please comment on the GitHub feedback issue.
Introspection support for MySQL, SQL Server, and CockroachDB views
You can now run prisma db pull
against your database to populate your Prisma schema with your views in MySQL, SQL Server, and CockroachDB.
To learn more, refer to our documentation on views introspection. Try it out and let us know your thoughts in this GitHub issue.
Prisma Client extensions improvements: raw query operations
This release adds support for extending top-level raw query operations.
const prisma = new PrismaClient().$extends({
query: {
// relational databases
$queryRaw({ args, query, operation }) {
// handle $queryRaw operation
return query(args)
},
$executeRaw({ args, query, operation }) {
// handle $executeRaw operation
return query(args)
},
$queryRawUnsafe({ args, query, operation }) {
// handle $queryRawUnsafe operation
return query(args)
},
$executeRawUnsafe({ args, query, operation }) {
// handle $executeRawUnsafe operation
return query(args)
},
// MongoDB
$runCommandRaw({ args, query, operation }) {
// handle $runCommandRaw operation
return query(args)
},
},
})
Webpack plugin for Next.js apps using Prisma in monorepo setups
If you've been using Prisma Client in a Next.js app in a monorepo setup, you might have seen this infamous error message:
Error: ENOENT: no such file or directory, open schema.prisma
We finally pinpointed the problem's source to the Next.js bundling step and opened an issue in the Next.js repository for Vercel to investigate and hopefully fix it.
In the meantime, we've created a workaround via a webpack plugin that makes sure your Prisma schema is copied to the correct location: @prisma/nextjs-monorepo-workaround-plugin
.
To use the plugin, first install it:
npm install -D @​prisma/nextjs-monorepo-workaround-plugin
Import the plugin into your next.config.js
file and use it in config.plugins
:
const { PrismaPlugin } = require('@​prisma/nextjs-monorepo-workaround-plugin')
module.exports = {
webpack: (config, { isServer }) => {
if (isServer) {
config.plugins = [...config.plugins, new PrismaPlugin()]
}
return config
},
}
For further information, refer to our documentation to learn how to use it and open an issue if it doesn't work as expected.
Fixes and improvements
Prisma Client
- Prisma hangs when javascript is minified
- Issue with prisma failing to locate schema file in monorepo
- NextJS try to open "schema.prisma" at wrong path.
- pnpm workspace + nextjs:
ENOENT: no such file or directory, open '...\.next\server\pages\api\schema.prisma'
- next.js ENOENT trying to open schema.prisma
- Error with custom output in NPM monorepo:
Error: ENOENT: no such file or directory, open 'schema.prisma'
- Error with custom output in Turborepo using Blitz.js: Error: ENOENT: no such file or directory, open '<...>/schema.prisma'
- Upsert fails on Postgres with list column.
- Error received when connecting items in an existing one-to-many relationship on MySQL
ENOENT
with custom output and ESM module in NPM monorepo (including Nextjs):no such file or directory, open /.../schema.prisma...
- Setting
ignoreEnvVarErrors: true
Node API QE causesdatasourceOverrides
to be ignored - PCE: Support query extensions for raw queries
Prisma Migrate
- sslaccept=accept_invalid_certs not working with mysql server 8.0.30
- Error 08S01 (1043) -> Bad Handshake. MySQL Connection with SSL certs
- Introspection of MySQL views
- Introspection of SQL Server views
- Introspection of CockroachDB views
db pull
: add new codes for introspection warnings for views in the CLI- Figure out where getDMMF is used for validation
- Error when
directUrl
isprisma://
connection string - 4.10.0, unexpected:
errorCode: 'P1012' PrismaClientInitializationError: error: Environment variable not found: DATABASE_URL.
- Validation output is now always colored, also in CI
- Prisma Client falsely validates
directUrl
env var value, leading to validation error (Affects PDP/Data Proxy and normal Engine) - Fix Postgres introspection of partition tables false positives on inherited tables
- Support openSUSE Tumbleweed
- Change
validate
to returnResult<(), JsError>
inWasm
module - (internal): add unit tests for path-specific libssl version parsing
Credits
Huge thanks to @KhooHaoYit, @rintaun, @ivan, @Mini256, @Lioness100, @yukukotani, @sandrewTx08, @fubhy, @zachtil, @unflxw, @Mosaab-Emam for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, March 2 at 5 pm Berlin | 8 am San Francisco.
v4.10.1
Today, we are issuing the 4.10.1
patch release.
Fixes in Prisma Client
- Prisma Client falsely validates directUrl env var value, leading to validation error (Affects PDP/Data Proxy and normal Engine)
- 4.10.0, unexpected: errorCode: 'P1012' PrismaClientInitializationError: error: Environment variable not found: DATABASE_URL.
v4.10.0
Highlights
Improved CLI support for connection poolers
When working with connection poolers such as the Prisma Data Proxy, Accelerate or pgBouncer, it is necessary to use a different URL to connect to the database when using Prisma Client and Prisma Migrate.
We're introducing a new datasource property directUrl
to improve this. When the directUrl
property is present, the Prisma CLI will use it to connect to the database for tasks such as introspection and migrations.
### .env
### Connection to Prisma Data Proxy. Used by Prisma Client.
DATABASE_URL="prisma://__HOST__/?api_key=__KEY__"
### Connection to the database. Used for migrations and introspection.
DIRECT_URL="postgresql://__USER__:__PASSWORD__@​__HOST__:__PORT__/__DATABASE__"
// ./prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
To learn more, refer to our documentation.
Introspection support for PostgreSQL views
We introduced initial support for database views in 4.9.0 with the addition of the view
keyword. This release introduces introspection support for PostgreSQL views. You can run prisma db pull
against your database to populate your Prisma schema with your views.
To learn more, refer to our documentation on views introspection. Try it out and let us know your thoughts in this GitHub issue.
Improved introspection for unsupported database functionality & partitioned tables
Currently, the Prisma Schema Language(PSL) does not cover the full feature sets of different database providers. For the unsupported database functionality, Prisma provides offers escape hatches like raw queries or manual editing of the migration files.
While we work on adding support for missing database functionality, e.g. database views, some of it is not fully-supported and the escape hatches fail. Objects that use unsupported properties might not be caught during introspection and raw queries might not work. Re-introspection may sometimes remove the information from the schema file and the generated migrations may be invalid or re-generate the same SQL repeatedly.
We're therefore fixing the defects and supporting the unsupported database functionalities Prisma currently doesn't support. We created a list of these features in this GitHub issue we would like to improve.
This release improves introspection support for partitioned tables in PostgreSQL and MySQL. Previously, Prisma would pick up the partitions as model
s and miss the actual main table. Prisma will now pick up the main table as a model
, not the partitions.
If you're already using partitioned tables in your database, you can use prisma db pull
to update your Prisma schema. If you're already using Prisma and want to partition a table in your database, you can:
- Create a draft migration using
prisma migrate dev --create-only
- Update the draft migration with the SQL to partition the tables
- Re-run
prisma migrate dev
to apply the draft migration to your database
Try it out and let us know what you think. If you run into an issue, feel free to create a bug report.
Smaller engine size used in Prisma CLI
In 4.8.0, we decreased the size of the engines by ~50%, which significantly impacted Prisma Client, especially in serverless environments.
In this release, we've reduced the size of Prisma CLI by removing the Introspection and Formatter engines. The introspection functionality is now served by the Migration Engine. A cross-platform Wasm module has entirely replaced the Formatter Engine. This reduces the overall installation size for Prisma CLI.
Fixes and improvements
Prisma Client
- Precompiled engine files for
aarch64-unknown-linux-musl
target (Alpine Linux on ARM, e.g. M1) - Specify the generator to use for sharing schema files in different environments
- Implement
getDmmf
as Wasm module that could be used in Prisma CLI - Client in interactive transaction is not extended
- Deeply nested objects aren't typed when clientExtensions is enabled
- Typescript issue on nested queries with clientExtensions feature
Prisma
- Introspection can't get composite primary key for partitioned table
- db pull adds redundant comment about ignored table
- Remove
prisma-fmt
formatter binary - Diagnostics currently need to be manually written for Code Action tests
- OpenSSL on Node Alpine still not working after Prisma 4.8.0 on an ARM machine
- Improved error messages on system library detection
- Remove
introspection-engine
binary from CLI - [Stopgap] Introspect partitioned tables better: Only introspect main table in a valid way, ignore partitions
- Regression:
get-platform
error for non-amd64
Alpine introduced inprisma@4.9.0
prevents using custom Prisma engines - Introspection of PostgreSQL views
- internal: use original distro and distro family in warning messages
- Failed to detect linux distro +
Error: Unknown binaryTarget debian-openssl-0.0.x and no custom engine files were provided
after upgrading from 4.8.1 to 4.9.0
Language tools (e.g. VS Code)
- Add VS Code quick fix / code action to phase out
referentialIntegrity
in favor ofrelationMode
- Auto completion of
directUrl
Credits
Huge thanks to @rintaun, @ivan, @Mini256, @yukukotani, @sandrewTx08 for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, February 9 at 5 pm Berlin | 8 am San Francisco.
v4.9.0
Highlights
Initial support for database views (Preview)
This release introduces a new keyword, view
, behind the views
Preview feature flag. You can manually add a view
to your Prisma schema, which is ignored when running migrations. This is a small step forward but should already be helpful to many of you depending on workarounds and shell scripts to work with views and Migrate.
Here is an example usage of views
:
generator client {
provider = "prisma-client-js"
previewFeatures = ["views"]
}
view UserInfo {
id Int @​id
// from the User model
email String
name String
// from the Profile model
bio String
}
model User {
id Int @​id @​default(autoincrement())
email String @​unique
name String?
profile Profile?
}
model Profile {
id Int @​id @​default(autoincrement())
bio String
user User @​relation(fields: [userId], references: [id])
userId Int @​unique
}
To learn more, head to our documentation. Try it out and let us know your thoughts on this GitHub issue.
Multi-schema support for SQL Server (Preview)
We're thrilled to share that this release adds Preview support for multi-schema for SQL Server.
This release adds support for:
- Introspecting databases that organize objects in multiple database schemas
- Managing multi-schema database setups directly from Prisma schema
- Generating migrations that are database schema-aware with Prisma Migrate
- Querying across multiple database schemas with Prisma Client
If you already have a SQL Server database using multiple schemas, you can quickly get up and running and set up multiple schemas by:
- Enabling the Preview feature in the Prisma schema
- Defining the schemas in the
schemas
property in thedatasource
block - Introspecting your database using
prisma db pull
You can further evolve your database schema using the multi-schema Preview feature by using prisma migrate dev
.
For further details, refer to our documentation and let us know what you think in this GitHub issue.
Prisma Client Extensions improvements
In this release, we've made a number of improvements to the Prisma Client Extensions Preview feature:
-
Retrieving the current model name at runtime You can now get the name of the current model at runtime using
Prisma.getExtensionContext(this).name
. You might use this to write out the model name to a log, to send the name to another service, or to branch your code based on the model. You can learn more about this in our docs. -
Improved type safety when defining custom model methods Prisma Client now provides a set of type utilities that tap into input and output types. They are fully dynamic, which means they adapt to any given model and schema. You can use them to improve your custom model methods' auto-completion. This is especially useful in shared extensions. Learn more about this in our docs.
Let us know what you think in this GitHub issue and in case you run into any issues, please create a bug report.
Introspection and Migration engine improvements
In this release, we moved the Introspection Engine (responsible for prisma db pull
) which the Migration Engine will now serve. Previously, the Introspection Engine was stand-alone.
Let us know what you think in this GitHub issue and in case you run into any issues, please create a bug report.
WriteConflict
bug fix
MongoDB This version also comes with a notable bug fix: In our MongoDB provider, any queries that are returned with a WriteConflict
error Prisma now will retry the query, similar to how other MongoDB drivers and clients do.
Prisma plugin for JetBrains IDEs
If you are using a JetBrains IDE the team over at JetBrains recently released an official Prisma plugin in their Plugin Marketplace.
Thank you, @JetBrains, for working on this! Next to our VS Code extension for Prisma and our general language server, which works in many editors, most relevant editors should now be covered.
Accelerate (Early Access)
We’re thrilled to announce Early Access to Accelerate.
Accelerate is a global database cache. It is available in 280 locations and has built-in connection pooling for serverless apps. You can make your queries up to 1000 times faster on any Prisma-supported database, reducing your query response times.
Join the waiting list for Accelerate here.
Fixes and improvements
Prisma
- Feature Request: Jetbrains (IntelliJ IDEA, Webstorm) Plugin
- Misleading 'We need to reset the PostgreSQL database' when using PostgreSQL schemas
- Solve "P1012 Introspection failed" errors on Windows CI
- support NanoID
- Create CI worker without a proper
openssl
orlibc
installation to improve snapshot testing suite - db pull --url with an invalid url produces a misleading error message
- (re)-Introspection errors have a misleading error message
- multi-schema + introspection: rename models and enums to avoid name collisions
- multiSchema + introspection: add
--schemas
param to thedb pull
command - Cross schema reference with foreign key not working in 4.7.0+
- Handle missing
schemas
property different when cross schema references are detected (whenmultiSchema
preview feature is enabled) db pull
withmultiSchema
enabled andschemas
defined, outputspublic
in CLI message anyway- Remove DML dependency from MongoDB introspection
- I want short unique id. UUID, CUID are too long
- Completions: for
schemas
property indatasource
- Completions
@@​schema
attribute - OS Support: improve SSL detection on
debian
distros multiSchema
: addschemas
property togetConfig
output- multiSchema:
migrate reset
with sqlserver does not delete second schema - Prisma 4.9.x (dev version) broke
openssl
detection for Linux distros besides Alpine and Debian-based distros, like RHEL - Wrong db pull warning with multiSchema preview feature, it says that
These enums were enriched with
@@mapinformation taken from the previous Prisma schema.
but the schema file datamodel is actually empty. - PSL: Recognize the
view
keyword - previewFeatures = ["multiSchema"] Error when doing db pull
- #17126 broke the
platform-serverless-vercel/vercel-cli
ecosystem tests - When
distro
is undefined, the output ofldconfig
is ignored because of thesed: -e expression #​1, char 7: unknown option to
s'` silent error
Prisma Client
- Detect absense of openssl and inform the user about it
- prisma@4.7.1 - "RangeError: Maximum call stack size exceeded" when clientExtensions enabled
- Prisma 4.8 produces conflicting typescript types for custom many to many relations
- Using findUnique on 4.8.0 with nested
where
andinclude
produces an object that doesn't include entities you specify ininclude
- Error: Maximum call stack size exceeded is thrown after I used clientExtensions as preview feature.
- MongoDB: Using
delete
on a one-to-one relation while updating removes other relations - Promise types are not unwrapped properly when using async/await in WebStorm
- Deeply nested objects aren't typed when clientExtensions is enabled
Prisma Migrate
Language tools (e.g. VS Code)
- Improve local development workflow and update documentation
- Integer.MAX_VALUE is not portable across clients
- Quick Fix: add
@@​schema
attribute to model / enum - Completions: from the list of available schema namespaces
- Recognizing the
view
keyword
Prisma Engines
- update napi dependencies from
2.9.1
to2.10.1
- me/ie rewiring: add
introspect
tests tomigration-engine
Credits
Huge thanks @rintaun, @ivan, @Mini256, @fubhy, @unflxw, @Mosaab-Emam for helping!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, January 26 at 5 pm Berlin | 8 am San Francisco.
v4.8.1
Today, we are issuing the 4.8.1
patch release.
Fix in Prisma Client
v4.8.0
Highlights
Improved serverless experience — smaller engines size
In this release, we have decreased the size of our engine files by an average of 50%. The size of the Query Engine used on Debian, with OpenSSL 3.0.x, for example, went from 39MB to 14MB. We will also remove some smaller engines to decrease the total size in future versions.
Additionally, we have started optimizing how the Prisma schema is loaded in Prisma Client. You should notice a considerable improvement when executing the first query if you're working with a bigger schema with many models and relations.
We will continue investing in this direction in the next releases and further improve the experience with Prisma and serverless environments.
Multi-schema support for CockroachDB (Preview)
We're pleased to share that this release adds Preview support for multi-schema for CockroachDB.
This release adds support for:
- Introspecting databases that organize objects in multiple database schemas
- Managing multi-schema database setups directly from Prisma schema
- Generating migrations that are database schema-aware with Prisma Migrate
- Querying across multiple database schemas with Prisma Client
If you already have a CockroachDB database using multiple schemas, you can quickly get up and running set up multiple schemas by:
- Enabling the Preview feature in the Prisma schema
- Defining the schemas in the
schemas
property in thedatasource
block - Introspecting your database using
prisma db pull
You can further evolve your database schema using the multi-schema Preview feature by using prisma migrate dev
.
For further details, refer to our documentation and let us know what you think in this GitHub issue.
Improved OpenSSL 3.x support
Prisma now supports OpenSSL 3 builds for Linux Alpine on x86_64
architectures. This particularly impacts users running Prisma on node:alpine
and node:lts-alpine
Docker images. The images are based on an Alpine version that ships with OpenSSL 3.0.x, which isn’t compatible with OpenSSL 1.1.x (already supported by Prisma). You can read more details about it in this GitHub comment.
We also have rewritten our OpenSSL version detection logic, making it future-proof. We now expect Prisma to support systems running with any OpenSSL 3 minor versions out of the box.
Fixes and improvements
Prisma
- Migrate: @dbgenerated with @db.Time(0) keeps generating new migrations
- Error parsing attribute "@@index": The Gin index field type
Uuid
has no default operator class. - UTF-8 Error: index is not a char boundary
- Error in migration engine. Reason: entered unreachable code
- Regression in enum default value handling in 4.7.0
- Regression in relation field name deduplication
- multiSchema:
migrate reset
only resets first schema - Cross schema reference with foreign key not working in 4.7.0.
- Support SQL Server in
multiSchema
introspection migrate dev
does not detect drift between database schema and migration history formultiSchema
- Bad credentials when downloading using @prisma/fetch-engines
- multiSchema: migrate dev fails to apply cleanly to shadow database after custom migration renames table in secondary schema
Prisma Migrate
- Prisma db migration always altering my table contains mysql TIME data type inside of it
- Prisma migration fails with postgres
- Migrate Dev CMD Issue when using
multiSchema
preview feature with MySQL
Prisma Client
- Prisma 4.3.1 distribution is bundling a libquery_engine
- enum fields are missing in select's type when
clientExtensions
preview feature is used $extends
TS error: "Inferred type of this node exceeds the maximum length the compiler will serialize" with"declaration": true
intsconfig
- Regression bug: batched findUniqueOrThrow queries throw 'Field does not exist on enclosing type.'
- Prisma Client Extensions:
args
isundefined
- Support OpenSSL 3.0 for Alpine Linux
console.log
outputs incorrect value whenresult
extensions are used- 4.6.0 and newer does not let me spy using vitest.
- Investigate memory issues on Windows
- prisma@4.7.1 - "RangeError: Maximum call stack size exceeded" when clientExtensions enabled
- Unique constraint error when connecting an item in a 1-1 relation that is already connected
- Error when using "multiSchema" with custom database schema and implicit Many To Many relation
- binaries.prisma.sh not accessible via IPv6
- Nested disconnect fails with
extendedWhereUnique
on SQL
Language tools (e.g. VS Code)
- Auto completion suggests
@map
although already present - Update message for detecting both Stable and Insiders in workspace
- Update to use correct form of criteri(a/on)
- Extra
'
in optional arguments context
Prisma Engines
- Use correct forms of "criterion" (singular) and "criteria" (plural)
- Only use buildjet action runner where needed
- Bug:
@@​schema
attribute should always be required whenschemas
is defined in the datasource
Credits
Huge thanks to @ivan, @Mini256, @cmd-johnson for helping!
Prisma Help Center (New)
We recently just launched our Help Center that you can use to find resources and get help from our support team for both the Prisma ORM and the Prisma Data Platform.
Check it out, and let us know what you think.
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, December 22 at 5 pm Berlin | 8 am San Francisco.
v4.7.1
Today, we are issuing the 4.7.1
patch release.
Fixes in Prisma Client
- Enum fields are missing in select's type when
clientExtensions
preview feature is used console.log
outputs incorrect value whenresult
extensions are used- "Field does not exist on enclosing type" error is thrown in
findUniqueOrThrow
- Prisma Client Extensions:
args
isundefined
v4.7.0
Highlights
Interactive transactions are now Generally Available
After an extensive Preview phase and lots of great feedback from our community, we're excited to announce that interactiveTransactions
is now Generally Available and production ready!
Interactive transactions allow you to pass an async function into a $transaction
, and execute any code you like between the individual Prisma Client queries. Once the application reaches the end of the function, the transaction is committed to the database. If your application encounters an error as the transaction is being executed, the function will throw an exception and automatically rollback the transaction.
Here are some of the feature highlights we've built:
- Support for defining transaction isolation levels — from
4.2.0
- Support for the Prisma Data Proxy — from
4.6.0
Here's an example of an interactive transaction with a Serializable
isolation level:
await prisma.$transaction(
async (prisma) => {
// Your transaction...
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
maxWait: 5000,
timeout: 10000,
}
)
You can now remove the interactiveTransactions
Preview feature in your schema.
Relation mode is Generally Available
This release marks relationMode="prisma"
as stable for our users working with databases that don't rely on foreign keys to manage relations.
Prisma’s relation mode started as a way to support PlanetScale which does not allow you to create foreign keys for better online migration support. We transformed that into our Referential Integrity Emulation in 3.1.1
when we realised that more users could benefit from it, and then integrated it as the default mode for MongoDB, which generally does not have foreign keys. Prisma needed to use emulation to give the same guarantees.
We then realized the feature was more than just referential integrity and affected how relations work. To reflect this, we renamed the feature to relation mode and the datasource
property to relationMode
in 4.5.0
relationMode = "prisma"
Index warnings for In this release, we've added a warning to our Prisma schema validation that informs you that the lack of foreign keys might result in slower performance — and that you should add an @@​index
manually to your schema to counter that. This ensures your queries are equally fast in relation mode prisma
as they are with foreign keys.
With
relationMode = "prisma"
, no foreign keys are used, so relation fields will not benefit from the index usually created by the relational database under the hood. This can lead to slower performance when querying these fields. We recommend manually adding an index.
We also added a fix to our VS Code extension to help adding the suggested index with minimal effort:
If you are currently using the Preview feature flag to enable relation mode, you can now remove referentialIntegrity
from the previewFeatures
in your generator client
block in your Prisma schema.
For more information, check out our updated relation mode documentation.
Prisma Client Extensions (Preview)
This release adds Preview support for Prisma Client Extensions. This feature introduces new capabilities to customize and extend Prisma Client. Today we are opening up four areas for extending Prisma Client:
-
model
: add custom methods or fields to your models -
client
: add client-level methods to Prisma Client -
result
: add custom fields to your query results -
query
: create custom Prisma Client queries
Prisma Client Extensions are self-contained scripts that can tweak the behavior of models, queries, results, and the client (Prisma Client) as a whole. You can associate a single or multiple extensions with an extended client to mix and match Prisma to your needs.
Prisma Client Extensions enables many use cases such as defining virtual fields, custom validation, and custom queries.
It also enables you to share your client extensions with others and import client extensions developed by others into your project.
For example, given the following schema:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["clientExtensions"]
}
model User {
id Int @​id @​default(autoincrement())
email String @​unique
firstName String?
lastName String
}
You can create a computed field called fullName
as follows:
import { PrismaClient } from "@​prisma/client"
const prisma = new PrismaClient()
.$extends({
result: {
user: {
fullName: {
// the dependencies
needs: { firstName: true, lastName: true },
compute(user) {
// the computation logic
return `${user.firstName} ${user.lastName}`
},
},
},
},
})
We're excited to see what you build with them! For more information, check out our docs and let us know what you think in this GitHub issue.
Multi-schema support for PostgreSQL (Preview)
We're pleased to announce that this release adds support for multi-schema support for PostgreSQL. The ability to query and manage multiple database schemas has been a long-standing feature request from our community.
This release adds support for the following:
- Introspecting databases that organize objects in multiple database schemas
- Managing multi-schema database setups directly from Prisma schema
- Generating migrations that are database schema-aware with Prisma Migrate
- Querying across multiple database schemas with Prisma Client
If you already have a PostgreSQL database using multiple schemas, you can quickly get up and running using prisma db pull
— on enabling the Preview feature and specifying the schemas in the datasource
block similar to the example below.
You can get started with defining multiple schemas in your Prisma schema as follows:
generator client {
provider = "prisma-client-js"
previewFeatures = ["multiSchema"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
schemas = ["base", "transactional"]
}
model User {
id Int @​id
orders Order[]
@​@​schema("base")
}
model Order {
id Int @​id
user User @​relation(fields: [id], references: [id])
user_id Int
@​@​schema("transactional")
}
Then generate and apply the changes to your database with prisma migrate dev
.
We want to thank all our users for helping us design the feature since the early proposal on GitHub up to our current Preview release.
For further details, refer to our documentation and let us know what you think in this GitHub issue.
Request for feedback
Our Product team is currently running a survey for designing Database Views support for Prisma and we would appreciate your feedback.
Fixes and improvements
Prisma Client
RangeError: Invalid count value
duringnpx prisma generate
withDEBUG=*
on integration build- When rejectOnNotFound is used, chaining deeper into a related table still throws if it doesn't find anything
- Stabilize
referentialIntegrity
- Some errors are obfuscated by interactive transactions when using
binary
engine - Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired' P2028
- The error is incorrectly pointed out when using the $transaction method
- Client: using update + connect throws an error on an idempotent operation
- findFirstOrThrow / findUniqueOrThrow errors are not reported via
error
event - wrong error message/header on multiple table upsert using transaction
- Args are out of sync with the action type for count when creating prisma middeware
- “Transaction API error: Transaction not found”
- Add
Prisma.TransactionClient
todefault-index.d.ts
- RangeError: Invalid count value during prisma generate
- Prisma Client regression bug after upgrading to 4.6.0:
findMany
errors withPANIC: index out of bounds: the len is 0 but the index is 0
upsert()
with nested selection errors withcalled
Option::unwrap()on a
Nonevalue
in 4.6.0- Bug(qe): errors don't get logged
- Downloading binaries of 4.6.1 fails with wrong sha256 checksum
- Calling
findUnique
concurrently with different key order causes one of them to return null - No way to catch error in
findUniqueOrThrow
via middleware - Test implicit m:n in relation mode
prisma
/ Reproduction test for prisma#16390
Prisma
- [Multi Schema] Same model map different schema
- Schema: add deprecation warning for datasource property
referentialIntegrity
(renamed torelationMode
) - Error in migration engine. Reason: [migration-engine/connectors/sql-migration-connector/src/sql_renderer/postgres_renderer.rs:944:22] We should only be setting a changed default if there was one on the previous schema and in the next with the same enum.
db pull
withmultiSchema
error on schema with 2 models with the same table name but in a different schema- Prisma 4.6.0 drops and recreates enum field when running db push even if the field has not changed
- @@map not working on postgress enums starting version 4.6.0
relationMode
: make feature GA- Add
SetDefault
validation error with warnings whenprovider = "mysql"
andrelationMode = "foreignKeys" | default
- Polish
relationMode
validation warning messages - Add linting/validation warnings for
prisma validate
&prisma format
Prisma Migrate
- What happen with
prisma migrate dev
- Prisma complains when enum types are not declared in alphabetical order
Language tools (e.g. VS Code)
- Dim models that are
@@​ignore
d and fields that are@ignore
d - Recommend adding indices to foreign keys when
referentialIntegrity = "prisma"
- PostgreSQL only: Add autocompletion in the datasource block for
extensions
whenpostgresqlExtensions
preview feature is set - language-tools:
relationMode
GA - remove preview feature condition - feat: for
relationMode="prisma"
, for@relation
: add a warning if there is no index on the field(s) - feat: Quick Fix -
relationMode
: missing foreign keys' indexes
Prisma Engines
Credits
Huge thanks to @cmd-johnson, @jsoref, @miguelgargallo for helping!
Prisma Data Platform
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the following:
- Data Browser for navigating, editing, and querying data
- Data Proxy for your database's persistent, reliable, and scalable connection pooling.
- Query Console for experimenting with queries
Try it out. Let us know what you think!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, December 1 at 5 pm Berlin | 8 am San Francisco.
v4.6.1
Today, we are issuing the 4.6.1
patch release.
Fixes in Prisma Client
- Prisma Client regression bug after upgrading to 4.6.0:
findMany
errors withPANIC: index out of bounds: the len is 0 but the index is 0
upsert()
with nested selection errors withcalled
Option::unwrap()on a
Nonevalue
in 4.6.0
Fix in Prisma Migrate
v4.6.0
Highlights
Interactive Transactions for Prisma Data Proxy (Preview)
In 3.8.0, we disabled the interactiveTransactions
Preview feature when using the Prisma Data Proxy. This was because the API was not yet supported.
In this release, we're removing the limitation. You can now try the Preview version of interactive transactions with the Prisma Data Proxy. Re-generate Prisma Client using prisma generate --data-proxy
after enabling the Preview feature.
Note: The interactiveTransactions
Preview feature flag is still needed. We will remove this in a future version when the feature is stable.
Try it out and let us know your thoughts in our interactive transactions feedback GitHub issue.
Native database level upserts for PostgreSQL, SQLite, and CockroachDB
Prisma’s upsert is one of its most powerful and most convenient APIs. In this release, Prisma will now default to the native database upsert for PostgreSQL, SQLite, and CockroachDB whenever possible.
Prisma will use the native database upsert if:
- There are no nested queries in the
upsert
'screate
andupdate
options - The query modifies only one model
- There is only one unique field in the
upsert
'swhere
option - The unique field in the
where
option and the unique field in thecreate
option have the same value
Prisma Client's upsert
operation was implemented on a Prisma-level and did not use the native database implementations like, e.g., INSERT .. ON CONFLICT .. UPDATE SET
. This allowed Prisma to also upsert nested queries.
The Prisma-implementation came at a cost. In some scenarios, it was more likely for a transaction to roll back because of a conflict when multiple upsert
operations were being executed in parallel, and the multiple queries often took longer than the native database query would have taken.
Try it out and let us know what you think. If you run into any issues, don't hesitate to create a GitHub issue.
Relation Mode improvements (Preview)
In 4.5.0, we renamed the "Referential Integrity" Preview feature to "Relation Mode". We also changed the datasource
property name of the feature to relationMode
.
In this release, we fixed all remaining known bugs of relationMode = "prisma"
and cleaned up our documentation. You can now read about Relation mode on its own documentation page which is up to date with the implementation.
If you encounter any problems please comment on our feedback issue. We plan to make this Generally Available soon.
extendedWhereUnique
improvements (Preview)
In 4.5.0, we introduced the extendedWhereUnique
Preview feature to allow filtering for non-unique properties in unique where queries. In this release, we're adding new rules to decide when concurrent findUnique
queries get batched into a findMany
query.
Unfortunately, we forgot to adapt our findUnique
query batch optimization, which turns multiple concurrent findUnique
queries into a single findMany
query when possible — GitHub issue.
Therefore, findUnique
queries will get batched into a findMany
query if:
- All criteria of the filter must be on scalar fields (unique or non-unique) of the same model you're querying
- All criteria must use the equal's filter, whether that's via the shorthand or explicit syntax (
where: { field: <val>, field1: { equals: <val> } }
)
Conversely, suppose the filter object contains any boolean operators, relation filters, or scalar filters that are not using equals
. Prisma will fall back to executing the findUnique
queries independently.
Let us know your thoughts and share your feedback on the Preview feature in this GitHub issue.
Fixes and improvements
Prisma Client
- upsert across HTTP requests has a race condition
- Client tests for Vitess, with
relationMode=prisma
- Concurrent relation upserts conflict
upsert()
should do ON CONFLICT DO UPDATE/NOTHING in postgresql- Cannot insert Floats (≥9.223372037e18 and <1e21) or (>-1e21 and ≤-9.223372037e18)
- Always serialize float fields in exponent notation
- Postgres integer column silently overflows to bad value
- Add duration to mongo logging
- upsert(): Unique constraint on DateTime sqlite
- "Unique constraint failed on the fields" when using upsert
- using connect in interactive transaction fails
- MongoDB does not log queries with
binary
Engine - [MongoDb] Query logger produces incorrect output
- Float values around 2^63 get interpreted as invalid intergers and throw a graphql error
- referentialIntegrity/relationMode preview feature (
referentialIntegrity = "prisma"
): MakeNoAction
a synonym/alias ofRestrict
for the emulation, for all databases except PostgreSQL & SQLite. - Client: In 1:1,1:n, m:n relations using
OnDelete: SetNull
withreferentialIntegrity = "prisma"
user.delete()
should fail, but succeeds. - calling findUnique concurrently on a model with a compound unique constraint causes it to return null
- Support interactive transactions in the Data Proxy
Prisma
- Re-Introspection:
referentialIntegrity = prisma
not respected when using@@​map()
- Validation fails to detect invalid
SetNull
referential action referencing non-optional fields - Schema: add validation for datasource property referentialIntegrity & relationMode, so only one can be set.
- Create TypeScript tests for #15655
referentialIntegrity
policy is lost during re-introspection- Relation fields are removed after npx prisma db pull
- Re-introspection should not remove relations when relationMode="prisma"
Language tools (e.g. VS Code)
Design Partner Program
Are you building data-intensive applications in serverless environments using Prisma? If so, you should join our Design Partner Program to help us build the tools that best fit your workflows!
The Design Partner Program aims to help development teams solve operational, data-related challenges in serverless environments. Specifically, we’re looking to build tools that help with the following problems:
- Solutions to listen and react to database changes in real time are either brittle or too complex to build and operate.
- Coordinating workflows executed via a set of isolated functions or services spreads that coordination logic across these services instead of keeping it centralized and maintainable. This adds unnecessary overhead and clutter to your business logic.
- Optimizing the data access layer for scaling performance often involves projecting data into denormalized views, or caching. These methods come with complex logic to figure out strategies for cache invalidation or preventing to use stale data.
- Building web applications on modern Serverless platforms such as Vercel or Netlify often breaks down as soon as you need to execute on any of the topics listed above. This pushes to re-platform on a traditional infrastructure, delaying projects, and losing productivity benefits offered by Vercel or Netlify.
Submit an application through our application form to join the Prisma Design Partner Program to take advantage of new features that you won't have to build or maintain yourselves.
Prisma Data Platform
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the following:
- Data Browser for navigating, editing, and querying data
- Data Proxy for your database's persistent, reliable, and scalable connection pooling.
- Query Console for experimenting with queries
Try it out. Let us know what you think!
📺 Join us for another "What's new in Prisma" live stream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" live stream.
The stream takes place on YouTube on Thursday, November 10 at 5 pm Berlin | 8 am San Francisco.
Credits
Huge thanks to @cmd-johnson for helping!
v4.5.0
Major improvements
Filter for non-unique properties in unique where queries (Preview)
In this release, we are adding support for non-unique properties inside the where
statement for queries that operate on a unique record (e.g.: findUnique
, update
, delete
, etc.). This was not possible in the past, as we only allowed unique fields as filters inside the where
statement for the queries in question.
There are use cases where a query that operates on a unique record requires further filtering by non-unique properties. For example, for the following model:
model Article {
id Int @​id @​default(autoincrement())
content String
version Int
}
Let’s say that you would like to update the Article
with an id
of “5”, but only if the version
equals "1":
await prisma.article.update({
where: { id: 5, version: 1 }, // `version` field was not available before Prisma 4.5.0
data: {
content: "Incredible new story",
version: { increment: 1 },
},
});
With 4.5.0
, we are adding support to specify any number of non-unique fields in your where
statement, as long as you have at least one unique field.
To use it, enable the Preview feature flag:
generator js {
provider = "prisma-client-js"
previewFeatures = ["extendedWhereUnique"]
}
To learn more about this feature and about use cases where it can be useful, please check out our documentation. For feedback, please leave a comment on the GitHub issue.
PostgreSQL extension management (Preview)
We are excited to add support for declaring PostgreSQL extensions in the Prisma schema. The feature comes with support for introspection and migrations. This will allow you to adopt, evolve and manage which PostgreSQL database extensions are installed directly from within your Prisma schema.
💡 This feature adds support to manage PostgreSQL extensions in Prisma schema. It does not provide additional query capabilities and datatypes in Prisma Client.
To try this feature, enable the Preview feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["postgresqlExtensions"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
Now you will be able to use the new extensions
property in the datasource
block of your Prisma schema.
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
extensions = [hstore(schema: "myHstoreSchema"), pg_tgrm, postgis(version: "2.1")]
}
⚠ ️ To avoid noise from introspection, we currently only introspect the following allow-list:citext
,pgcrypto
,uuid-ossp
, andpostgis
. But you can add and configure any extension to your Prisma schema manually.
Please visit our documentation to learn more about this feature or leave a comment with feedback on the GitHub issue.
datasource
block renamed to relationMode
(Preview)
Change to Referential Integrity — property in To prepare Prisma Client’s emulation of relations for general availability, we are releasing several improvements to the referentialIntegrity
Preview feature.
We decided to rename the feature to Relation Mode. We think this closer reflects what this feature does and distinguishes it from integrity management on the database level. The related property in the datasource
block of the Prisma schema has also been changed from referentialIntegrity
to relationMode
.
⚠ ️ The Preview feature flag inside thegenerator
block of the Prisma schema is still calledreferentialIntegrity
.
To use it, keep using the old referentialIntegrity
Preview feature flag:
generator js {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity"]
}
But use the new property name in the datasource
:
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}
We also removed the referential action NoAction
for PostgreSQL and SQLite when using relationMode = "prisma"
as we are not planning to support the details of the database behavior.
To learn more about relationMode
, please check out the documentation or leave a comment on the GitHub issue.
Deno for Prisma Client for Data Proxy (Preview)
Deno is an alternative JavaScript runtime that can replace Node.js to run JS and TS apps. It aligns itself closely with web technologies, claims to be secure by default, and supports TypeScript out of the box.
Today we are releasing initial support for Prisma with Deno via an integration for our Prisma Client for Data Proxy. This feature was developed together with the amazing team at Deno 🦕.
To use Prisma Client in a Deno project, add the deno
Preview feature flag to your Prisma schema and define a folder as output
(this is required for Deno):
generator client {
provider = "prisma-client-js"
previewFeatures = ["deno"]
output = "../generated/client"
}
Now you can generate Prisma Client with the Data Proxy using the command npx prisma generate --data-proxy
. Then use Prisma Client in your Deno script with the following import:
import { PrismaClient } from './generated/client/deno/edge.ts'
const prisma = new PrismaClient()
async function main() {
const users = await prisma.user.findMany()
console.log({ users })
}
main()
You can also deploy an app built and configured like this on Deno Deploy, Deno’s deployment platform. Read this guide in our documentation for a full example and individual steps.
For feedback, please comment on this GitHub issue.
Fixed “Invalid string length” error in Prisma Studio and Prisma Data Platform Data Browser
Many people were having issues with an "Invalid string length" error both in Prisma Studio and Prisma Data Platform Data Browser. This issue can be resolved through this workaround. With this release, the root cause of this issue has been fixed and it should not occur again.
Updated proposal for Client Extensions: request for comments
In 4.3.0
, we shared a proposal for Prisma Client Extensions on Github. We received a lot of great feedback, which we have incorporated into a new proposal.
If you’re interested, please head over to the new proposal in GitHub and tell us what you think. Thank you!
Fixes and improvements
Prisma
- Optimistic Concurrency Control
- MySQL does not support
onDelete: setDefault
- Reformat unreachable code: Encountered impossible declaration during formatting
- Switching between
referentialIntegrity
modes makes migration history obsolete - Rename the feature to “Prisma relation mode” → relationMode
- [multiSchema] check PSL validations for enum and composite type database name clashes
- Support PostgreSQL Extensions in the Prisma Schema Language
- Support PostgreSQL Extensions in the PostgreSQL Introspection
- Support PostgreSQL Extensions in the Migration Engine
- Add TS test for datasource property
referentialIntegrity
andrelationMode
- relationMode: Change test naming
Prisma Client
- Be able to update or retrieve a single record including non-unique fields in the "where" conditions.
- Remove WhereUnique constraint from single object lookups
- Expand tests around referential actions and referential integrity
- Feature: Allow non-unique fields to be used with update
- QueryRaw: Error serializing parameter
- PrismaClientUnknownRequestError on create statement default optional value
- Problems with SQL Server deadlocks
Prisma Migrate
Language tools (e.g. VS Code)
- Custom icon for .prisma files
- Add autocompletion for property of
relationMode
(previouslyreferentialIntegrity
) in the datasource block
Credits
Huge thanks to @kt3k, @abenhamdine, @jsoref for helping!
v4.4.0
Major improvements
General improvements
In the last sprint, we focused our efforts on squashing as many bugs as we could. You can find the full list of improvements and bug fixes in the Fixes and improvements section below.
Some of the improvements we made include but are not limited to:
- Improved optimistic concurrency control (GitHub issue)
- Improved decimal precision
- Improved handling of big amounts of prepared statement placeholders:
Databases impose limits when they hit a specific number, and when a query (either generated by Prisma Client or provided by the user directly as a raw query) hits it some users ran into a misleading
Can't reach database server
error message (GitHub issue). The error message will now be more useful (P2035
error code), and Prisma Client should not cause these errors anymore.
If you notice any regression, please make sure to create a GitHub issue. We touched a lot of code in this sprint, and even though we are confident in our tests, something might have slipped through the cracks. We'd like to fix the regressions as soon as possible.
isolationLevel
for sequential transaction operations
In version 4.2.0
, we added support for setting transaction isolation levels for interactive transactions (Preview). You can now define isolation levels for sequential transaction operations: prisma.$transaction([])
.
Isolation levels describe different types of trade-offs between isolation and performance that databases can make when processing transactions. Isolation levels determine what types of data leaking can occur between transactions or what data anomalies can occur.
To set the transaction isolation level, use the isolationLevel
option in the second parameter of the API. For example:
await prisma.$transaction(
[
// sequential operations
prisma.user.create({ data: {/** args */ } }),
prisma.post.create({ data: {/** args */ } })
],
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable
}
)
Prisma Client supports the following isolation levels if they're available in your database provider:
ReadCommitted
ReadUncommitted
RepeatableRead
Serializable
Snapshot
Learn more about it in our documentation.
P2034
error code for transaction conflicts or deadlocks
New When using certain isolation levels, it is expected that a transaction can fail due to a write conflict or a deadlock, throwing an error. One way to solve these cases is by retrying the transaction.
To make this easier, we're introducing a new PrismaClientKnownRequestError
with the error code P2034
: "Transaction failed due to a write conflict or a deadlock. Please retry your transaction". You can programmatically catch the error and retry the transaction. Here's an example showing how you can retry a transaction:
import { Prisma, PrismaClient } from '@​prisma/client'
const prisma = new PrismaClient()
async function main() {
const MAX_RETRIES = 5
let retries = 0;
let result;
while (retries < MAX_RETRIES) {
try {
result = await prisma.$transaction(
[
prisma.user.deleteMany({ where: { /** args */ } }),
prisma.post.createMany({ data: { /** args */ } })
],
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable
}
)
} catch (error) {
if (error.code === 'P2034') {
retries++
continue
}
throw error
}
}
}
Fixes and improvements
Prisma Client
- Wrong types for fluent API when used along with
rejectOnNotFound
- Precision issue when persisting Decimal.js objects
- Decimals lose precision (postgres)
- Weird behavior with "in:" clause on a findMany() with orderBy + take
- decimal lose precision digits to postgres
updateMany()
causes lost-updates- Error: P1001: Can't reach database server when including large table
- Client shows contains filter on uuid data type despite not being a valid operation
- A model with relation to another model via non-null foreign key has nullable type
- Validation error when inserting data of type
List<String | DateTime>
into field of typeList<String>
- Can't reach database server when doing a large findMany query
- Maximum call stack size exceeded when creating huge amount of related rows
- Unique constraint failed during
$transaction([deleteMany, createMany])
- update will break atomicity
- Nested self referential orderby not working
- MySQL: Optimistic Concurrency Control doesn't work with UpdateMany
- Wrong type when retrieving multiple related records using fluent API
- Fluent API produces runtime error
- Column 'orderby_.....' in on clause is ambiguous
- [PostgreSQL] Cannot create or update row with large Decimal value within
numeric
range - Failed transactions trigger multipleResolves
The provided database string is invalid. Unable to parse URL. in database URL.
on invalid (?) connection string- relation query fails when thousands of records
- Unable to query records with certain values
- orderBy using self-referential relation in a nested relation fails with "table name "TableName" specified more than once"
- @updatedAt does not work with @default
- Prisma silently misses nested elements on MariaDB when it triggers a huge IN clause
createdAt @​default(now())
andupdatedAt @​updatedAt
get different times on row creation- Interactive Transactions: fatal when throwing string instead of Error() since 3.10.0
- Prisma MongoDB can not search for field with value
$foo
- groupBy crashes when using enums
- MySQL DECIMAL(X, 5) returns incorrect precision.
- "Join" performance: (Not so) huge data set throws an error
Error: The provided database string is invalid. Unable to parse URL. in database URL.
- [mongoDB]
findRaw
does not work within aninteractiveTransaction
- Filters max size is exceeded
- Prisma fails on Postgres query with findMany
- Update Restrict failed on prisma referentialIntegrity
- invalid character in $let in $lookup pipeline when using cursor and order by query
- Find many returns empty array or null
- Once instance has previously been poisoned
- Sanitize error snapshots in new test setup
- The findMany query fails silently when the array length passed through IN parameter exceeds 999
- mongodb cannot use $runCommand Raw in transaction
parent result: Some(ManyRecords { records: [Record { values: [Int(3), Int(1), DateTime(2022-08-08T12:27:55.310+00:00)], parent_id: None }], field_names: ["id", "userId", "createdAt"] }), relation: Relation { name: "post", model_a_name: "Comment", model_b_name: "Post", model_a: OnceCell((Weak)), model_b: OnceCell((Weak)), field_a: OnceCell((Weak)), field_b: OnceCell((Weak)), manifestation: Inline(InlineRelation { in_table_of_model_name: "Comment" }), internal_data_model: "#InternalDataModelWeakRef#" }
- Given exponent overflowing the maximum accepted scale (255).: TryFromIntError(())
- Once instance has previously been poisoned
- sqlite:cuid():called
Result::unwrap()
on anErr
value: FingerprintError("Could not retrieve hostname") - Calling
findUnique
concurrently with aDateTime
column causes it to returnnull
- Maximum Call Stack Size Exceeded When Inserting large Array Object
- Prisma Client is incompatible with TypeScript 4.8
- This is a non-recoverable error: When creating Item with nested query
- Given exponent overflowing the maximum accepted scale (255).: TryFromIntError(())
- Prisma 4.3.0 takes 100x more time to generate types
- Tracing:
prisma:engine
spans always get sampled when using probability based samplers - Datasource providers in
prisma init
is listing wrong values - Disconnect with large queries
N/A
error and message with large raw queries- only one @updatedAt is filled by the QE although multiple are accepted in the schema
- Insert fails if a table has a space in the name of the primary key
- Bug with throwing formatted errors
- called
Option::unwrap()
on aNone
value - Upsert error on MySQL:
Query ... is required to return data, but found no record(s)
- Add tests for mongodb's
findRaw
,aggregateRaw
andrunCommandRaw
in sequential transactions
Prisma
- sqlite: show better error when a permission denied error occurs
- Prisma v4 breaks support for empty
dbgenerated()
- invalid migration created with no schema change - Binary engine:
$disconnect
never returns if engine failed to start
Prisma Migrate
Prisma Studio
Credits
Huge thanks to @abenhamdine, @miguelgargallo, @Clansty, @panoplied, @MEnnabah, @drzamich, @AndrewSouthpaw, @kt3k for helping!
💼 We're hiring!
If you're interested in joining our growing team to help empower developers to build data-intensive applications, Prisma is the place for you.
We're looking for a Developer Advocate (Frontend / Fullstack) and Back-end Engineer: Prisma Data Platform.
Feel free to read the job descriptions and apply using the links provided.
Prisma Data Platform
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:
- Data Browser for navigating, editing, and querying data
- Data Proxy for your database's persistent, reliable, and scalable connection pooling.
- Query Console for experimenting with queries
Try it out and let us know what you think!
📺 Join us for another "What's new in Prisma" livestream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" livestream.
The stream takes place on YouTube on Thursday, September 29 at 5 pm Berlin | 8 am San Francisco.
v4.3.1
Today, we are issuing the 4.3.1
patch release.
Fixes in Prisma Client
Fixes in Prisma CLI
v4.3.0
Major improvements
Field reference support on query filters (Preview)
We're excited to announce Preview support for field references. You can enable it with the fieldReference
Preview feature flag.
Field references will allow you to compare columns against other columns. For example, given the following schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
model Invoice {
id Int @​id @​default(autoincrement)
paid Int
due Int
}
You can now compare one column with another after running prisma generate
, for example:
// Filter all invoices that haven't been paid yet
await prisma.invoice.findMany({
where: {
paid: {
lt: prisma.invoice.fields.due // paid < due
}
}
})
Learn more about field references in our documentation. Try it out and let us know what you think in this GitHub issue.
Count by filtered relation (Preview)
In this release, we're adding support for the ability to count by a filtered relation. You can enable this feature by adding the filteredRelationCount
Preview feature flag.
Given the following Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["filteredRelationCount"]
}
model User {
id Int @​id @​default(autoincrement())
email String @​unique
name String?
posts Post[]
}
model Post {
id Int @​id @​default(autoincrement())
title String
content String?
published Boolean @​default(false)
author User? @​relation(fields: [authorId], references: [id])
authorId Int?
}
You can now express the following query with the Preview feature after re-generating Prisma Client:
// Count all user posts with the title "Hello!"
await prisma.user.findMany({
select: {
_count: {
select: {
posts: { where: { title: 'Hello!' } },
},
},
},
})
Learn more in our documentation and let us know what you think in this issue
Multi-schema support (Preview)
In this release, we're adding very early Preview support of multi-schema support for PostgreSQL and SQL Server behind the multiSchema
Preview feature flag. With it, you can write a Prisma schema that accesses models across multiple schemas.
Read further in this GitHub issue. Try it out and let us know what you think in this GitHub issue.
Prisma CLI exit code fixes
We've made several improvements to the Prisma CLI:
-
prisma migrate dev
previously returned a successful exit code (0) whenprisma db seed
was triggered but failed due to an error. We've fixed this andprisma migrate dev
will now exit with an unsuccessful exit code (1) when seeding fails. -
prisma migrate status
previously returned a successful exit code (0) in unexpected cases. The command will now exit with an unsuccessful exit code (1) if:- An error occurs
- There's a failed or unapplied migration
- The migration history diverges from the local migration history (
/prisma/migrations
folder) - Prisma Migrate does not manage the database' migration history
-
The previous behavior when canceling a prompt by pressing Ctrl + C was returning a successful exit code (0). It now returns a non-successful,
SIGINT
, exit code (130). -
In the rare event of a Rust panic from the Prisma engine, the CLI now asks you to submit an error report and exit the process with a non-successful exit code (1). Prisma previously ended the process with a successful exit code (0).
tracing
Preview feature
Improved precision for the Before this release, you may have occasionally seen some traces that took 0μs working with the tracing
Preview feature. In this release, we've increased the precision to ensure you get accurate traces.
Let us know if you run into any issues in this GitHub issue.
prisma format
now uses a Wasm module
Initially, the prisma format
command relied on logic from the Prisma engines in form of a native binary. In an ongoing effort to make prisma
more portable and easier to maintain, we decided to shift to a Wasm module.
prisma format
now uses the same Wasm module as the one the Prisma language server uses, i.e. @prisma/prisma-fmt-wasm
, which is now visible in prisma version
command's output.
Let us know what you think. In case you run into any issues, let us know by creating a GitHub issue.
MongoDB query fixes
⚠ ️ This may affect your query results if you relied on this buggy behavior in your application.
While implementing field reference support, we noticed a few correctness bugs in our MongoDB connector that we fixed along the way:
-
mode: insensitive
alphanumeric comparisons (e.g. “a” > “Z”) didn’t work (GitHub issue) -
mode: insensitive
didn’t exclude undefined (GitHub issue) -
isEmpty: false
on lists types (e.g. String[]) returned true when a list is empty (GitHub issue) -
hasEvery
on list types wasn’t aligned with the SQL implementations (GitHub issue)
JSON filter query fixes
⚠ ️ This may affect your query results if you relied on this buggy behavior in your application. We also noticed a few correctness bugs in when filtering JSON values when used in combination with theNOT
condition. For example:
await prisma.log.findMany({
where: {
NOT: {
meta: {
string_contains: "GET"
}
}
}
})
Prisma schema
model Log {
id Int @​id @​default(autoincrement())
level Level
message String
meta Json
}
enum Level {
Info
Warn
Error
}
If you used NOT
with any of the following queries on a Json
field, double-check your queries to ensure they're returning the correct data:
string_contains
string_starts_with
string_ends_with
array_contains
array_starts_with
array_ends_with
-
gt
/gte
/lt
/lte
Prisma extension for VS Code improvements
The Prisma language server now provides Symbols in VS Code. This means you can now:
-
See the different blocks (
datasource
,generator
,model
,enum
, andtype
) of your Prisma schema in the Outline view. This makes it easier to navigate to a block in 1 click A few things to note about the improvement are that:- CMD + hover on a field whose type is an enum will show the block in a popup
- CMD + left click on a field whose type is a model or enum will take you to its definition.
-
Enable Editor sticky scroll from version
1.70
of VS Code. This means you can have sticky blocks in your Prisma schema, improving your experience when working with big schema files
Make sure to update your VS Code application to 1.70, and the Prisma extension to 4.3.0
.
We'd also like to give a big Thank you to @yume-chan for your contribution!
Prisma Studio improvements
We've made several improvements to the filter panel which includes:
-
Refined filter panel
- Reducing the contrast of the panel in dark mode
- Ability to toggle filters in the panel
-
Refined error handling for MongoDB m-n relations Prisma Studio prevents fatal errors when interacting with m-n relations by explicitly disabling creating, deleting, or editing records for m-n relations
-
Multi-row copying You can select multiple rows and copy them to your clipboard as JSON objects using CMD + C on MacOS or Ctrl + C on Windows/ Linux
Prisma Client Extensions: request for comments
For the last couple of months, we've been working on a specification for an upcoming feature — Prisma Client extensions. We're now ready to share our proposed design and we would appreciate your feedback.
Prisma Client Extensions aims to provide a type-safe way to extend your existing Prisma Client instance. With Prisma Client Extensions you can:
- Define computed fields
- Define methods for your models
- Extend your queries
- Exclude fields from a model ... and much more!
Here’s a glimpse at how that will look:
const prisma = new PrismaClient().$extend({
$result: {
User: {
fullName: (user) => {
return `${user.firstName} ${user.lastName}`
},
},
},
$model: {
User: {
signup: async ({ firstName, lastName, email, password }) => {
// validate and create the user here
return prisma.user.create({
data: { firstName, lastName, email, password }
})
},
},
},
})
const user = await prisma.user.signup({
firstName: "Alice",
lastName: "Lemon",
email: "alice@prisma.io",
password: "pri$mar0ckz"
})
console.log(user.fullName) // Alice Lemon
For further details, refer to this GitHub issue. Have a read and let us know what you think!
Fixes and improvements
Prisma Client
- Allow WHERE conditions to compare columns in same table
- Dates serialized without quotation marks in query event parameters property
- Ability to filter count in "Count Relation Feature"
- Some traces show 0μs
- [MongoDB] Alphanumeric insensitive filters don't work
- [MongoDB] Insensitive filters don't exclude undefineds
- Schema size affects runtime speed
- Prisma Client always receive engine spans even when not tracing
- Environment variables not available when using Wrangler 2
Prisma
- Undo "skip flaky referentialActions sql server test"
- Add
@prisma/prisma-fmt-wasm
to CLI and output dependency version in-v
, use instead of Formatter Engine binary - Add jest snapshots for improved
db push
output in MongoDB - OpenSSL error message appearing while using query-engine has false positives
- Calling
dmmf
raises "Schema parsing - Error while interacting with query-engine-node-api library" misleading error message when there is a schema validation error. - Unique composite indexes do not clash with a matching name on schema validation (composite types)
- CLI:
migrate status
should return a non-successful exit code (1) when a failed migration is found or an error occurs - CLI:
migrate dev
should return a non-successful exit code (1) when there is an error during seeding
Prisma Migrate
Language tools (e.g. VS Code)
Credits
Huge thanks to @abenhamdine, @drzamich, @AndrewSouthpaw, @kt3k, @lodi-g, @Gnucki, @apriil15, @givensuman for helping!
Prisma Data Platform
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:
- Data Browser for navigating, editing, and querying data
- Data Proxy for your database's persistent, reliable, and scalable connection pooling.
- Query Console for experimenting with queries
Try it out and let us know what you think!
💼 We're hiring!
If you're interested in joining our growing team to help empower developers to build data-intensive applications, Prisma is the place for you.
We're looking for a Developer Advocate (Frontend / Fullstack) and Back-end Engineer: Prisma Data Platform.
Feel free to read the job descriptions and apply using the links provided.
📺 Join us for another "What's new in Prisma" livestream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" livestream.
The stream takes place on YouTube on Thursday, September 1 at 5 pm Berlin | 8 am San Francisco.
v4.2.1
Today, we are issuing the 4.2.1
patch release.
Fix in Prisma Client
v4.2.0
Major improvements
Prisma Client tracing support (Preview)
We're excited to announce Preview support for tracing in Prisma Client!
Tracing allows you to track requests as they flow through your application. This is especially useful for debugging distributed systems where each request can span multiple services.
With tracing, you can now see how long Prisma takes and what queries are issued in each operation. You can visualize these traces as waterfall diagrams using tools such as Jaeger, Honeycomb, or DataDog.
Read more about tracing in our announcement post and learn more in our documentation on how to start working with tracing.
Try it out and let us know what you think.
Isolation levels for interactive transactions
We are improving the interactiveTransactions
Preview feature with the support for defining the isolation level of an interactive transaction.
Isolation levels describe different types of trade-offs between isolation and performance that databases can make when processing transactions. Isolation levels determine what types of data leaking can occur between transactions or what data anomalies can occur.
To set the transaction isolation level, use the isolationLevel
option in the second parameter of the API. For example:
await prisma.$transaction(
async (prisma) => {
// Your transaction...
},
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
maxWait: 5000,
timeout: 10000,
}
)
Prisma Client supports the following isolation levels if they're available in your database provider:
ReadCommitted
ReadUncommitted
RepeatableRead
Serializable
Snapshot
Learn more about in our documentation. Try it out, and let us know what you think in this GitHub issue.
Renaming of Prisma Client Metrics
In this release, we've renamed the metrics — counters, gauges, and histograms — returned from prisma.$metrics()
to make it a little easier to understand at a glance.
Previous | Updated |
---|---|
query_total_operations |
prisma_client_queries_total |
query_total_queries |
prisma_datasource_queries_total |
query_active_transactions |
prisma_client_queries_active |
query_total_elapsed_time_ms |
prisma_client_queries_duration_histogram_ms |
pool_wait_duration_ms |
prisma_client_queries_wait_histogram_ms |
pool_active_connections |
prisma_pool_connections_open |
pool_idle_connections |
prisma_pool_connections_idle |
pool_wait_count |
prisma_client_queries_wait |
Give Prisma Client metrics
a shot and let us know what you think in this GitHub issue
To learn more, check out our documentation.
Syntax highlighting for raw queries in Prisma Client
This release adds syntax highlighting support for raw SQL queries when using $queryRaw``
and $executeRaw``
. This is made possible using Prisma's VS Code extension.
Note: Syntax highlighting currently doesn't work with when using parentheses, ()
, $queryRaw()
, $executeRaw()
, $queryRawUnsafe()
, and $executeRawUnsafe()
.
If you are interested in having this supported, let us know in this GitHub issue.
Experimental Cloudflare Module Worker Support
We fixed a bug in this release that prevented the Prisma Edge Client from working with Cloudflare Module Workers.
We now provide experimental support with a workaround for environment variables.
Try it out and let us know how what you think! In case you run into any errors, feel free to create a bug report.
Upgrade to Prisma 4
In case you missed it, we held a livestream a few weeks ago and walked through issues you may run into while upgrading to Prisma 4 and how to fix them!
Request for feedback
Our Product teams are currently running two surveys to help close the feature gaps and improve Prisma.
If you have a use-case for geographical data (GIS) or full-text search/ indexes (FTS), we would appreciate your feedback on your needs:
- Prisma GIS User Research Survey
- Prisma Full-Text Search User Research Survey
Many thanks!
Fixes and improvements
Prisma Client
- Allow
dataproxy
to have datasource overrides - Warning during build: equals-negative-zero
- getGraphQLType throws error if object has no prototype
- Prisma Client: Log Data Proxy usage explicitly
- Cannot read property 'name' of undefined attempting to create row
- Edge client crashes when enabling debug logs in constructor
- TypeError: Cannot read properties of undefined (reading '_hasPreviewFlag')
- Large package.json log output in prisma:client:dataproxyEngine
Prisma
- Error: [libs/datamodel/connectors/dml/src/model.rs:338:29] Crash probably due to cyrillic table names
- Prisma doesn't validate composite attributes correctly
- Not letting me add Int as a type?
- Introspection crash,
libs\datamodel\connectors\dml\src\model.rs:494:29
(missing PK?) - SQL Server introspection panic
- Hi Prisma Team! Prisma Migrate just crashed.
- Primary key in model using a missing column
- Migrate just crashed sqlserver
- Prisma is trying to find column that doesn't exists
prisma db pull
onSQL Server
- Issue that occurred during
prisma db pull
Language tools (e.g. VS Code)
Prisma Studio
Credits
Huge thanks to @shian15810, @zifeo, @lodi-g, @Gnucki, @apriil15, @givensuman, @peter-gy for helping!
Prisma Data Platform
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:
- Data Browser for navigating, editing, and querying data
- Data Proxy for persistent, reliable, and scalable connection pooling for your database.
- Query Console for experimenting with queries
Try it out and let us know what you think!
💼 We're hiring!
If you're interested in joining our growing team to help empower developers to build data-intensive applications, Prisma is the place for you.
We're looking for a Developer Advocate (Frontend / Fullstack) and Back-end Engineer: Prisma Data Platform.
Feel free to read the job descriptions and apply using the links provided.
📺 Join us for another "What's new in Prisma" livestream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" livestream.
The stream takes place on YouTube on Thursday, August 11 at 5 pm Berlin | 8 am San Francisco.
v4.1.1
Today, we are issuing the 4.1.1
patch release.
Fix in Prisma Studio
v4.1.0
Upgrading to Prisma 4
In case you missed it, we held a livestream last week and walked through issues you may run into while upgrading to Prisma 4 and how to fix them!
Major improvements
Ordering by nulls first and last support (Preview)
In this release, we're adding support for choosing how to sort null values in a query.
To get started, enable the orderByNulls
Preview feature flag in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["orderByNulls"]
}
Next, run prisma generate
to re-generate Prisma Client. You will now have new fields you can now use to order null values:
await prisma.post.findMany({
orderBy: {
updatedAt: {
sort: 'asc',
nulls: 'last'
},
},
})
Learn more in our documentation and don't hesitate to share your feedback in this issue.
Fixed memory leaks and CPU usage in Prisma Client
In this release, we've fixed the following issues experienced when setting up and tearing down Prisma Client while running tests:
- Prisma Client now correctly releases memory on Prisma Client instances that are no longer being used. Learn more in this GitHub issue
- Reduced CPU usage spikes when disconnecting Prisma Client instances while using Prisma Client. You can learn more in this GitHub issue
These fixes will allow you to run your tests a little faster!
Prisma Studio improvements
We're refining the experience when working with Prisma studio with the following changes:
- An always visible filter panel and functionality to clear all filters at once
- Improved relationship model view with more visible buttons
Let us know what you think, and in the event, you run into any issues, please create a GitHub issue
Fixes and improvements
Prisma
- Formatter doesn't allow comments on consecutive indices
- Internal: reformatter is not idempotent
prisma format
strips comments on block level attributes- Reformatter crash in relation code
- Formatter crashes on arbitrary blocks
prisma --version
crashes ifopenssl
isn't properly installed- Rename 'getVersion' to 'getEngineVersion' in
@prisma/internals
- BigInt with a default value cause duplicates in all migrations
- Formatter: thread 'main' panicked at 'not yet implemented'
- Mongodb introspection fails with "called
Option::unwrap()
on aNone
value" - PSL should support inline
//
comments in the generator and datasource blocks - Unable to use native database types with Prisma and CockroachDB
Prisma Client
- High permanent CPU usage after calling $disconnect on a client that executed an interactive transaction before (v3.9.0+)
- Slow Tests
prisma generate
: Non-functional debounce mechanism for watch mode- Unknown error in SQLite Connector migrating from Prisma 3.x to 4.0.0 on ARM/M1 machines
- macOS 12 sometimes kills Node.js process when loading the QE library
Prisma Migrate
- migrate-cli: do not override RUST_LOG from the environment
- Incorrect migration creates on sql server when index deleted
- Float cause duplicate alter table in all migrations
- db error: ERROR: cannot drop view geography_columns because extension postgis requires it
Language tools (e.g. VS Code)
- Check when
@id
is suggested and fix - Implement a code action adding a unique constraint to a relation
- Potential pipeline
🔥 of language-tools with versioning change of@prisma/engines
- Cannot add comments to my @@unique constraints
@prisma/engines npm package
Credits
Huge thanks to @shian15810, @zifeo, @lodi-g, @Gnucki, @apriil15 for helping!
💼 We're hiring!
If you're interested in joining our growing team to help empower developers to build data-intensive applications, Prisma is the place for you.
We're looking for a Technical Support Engineer and Back-end Engineer: Prisma Data Platform.
Feel free to read the job descriptions and apply using the links provided.
📺 Join us for another "What's new in Prisma" livestream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" livestream.
The stream takes place on YouTube on Thursday, July 19 at 5 pm Berlin | 8 am San Francisco.
v4.0.0
We're excited to share the 4.0.0
stable release today.
Prisma 4.0.0
features a variety of improvements across Prisma Migrate, Prisma schema, and Prisma Client. These changes will impact most Prisma users, particularly those who used some of our most popular Preview features around advanced index management, raw SQL queries, and filtering rows by properties of JSON.
As this is a major release, we included many breaking bug fixes and other enhancements, but we believe upgrading is worthwhile. You can learn about upgrading in our Prisma 4 Upgrade guide and the Prisma 4 Upgrade video.
Major improvements
Here's a TL;DR:
-
Preview features moved to General Availability
extendedIndexes
filterJson
improvedQueryRaw
-
Improvements to the Prisma Schema
- Defaults values for scalar lists (arrays)
- Improved default support for embedded documents in MongoDB
- Explicit unique constraints for 1:1 relations
- Removed support for usage of
references
on implicit m:n relations - Enforcing uniqueness of referenced fields in the
references
argument in 1:1 and 1:m relations for MySQL - Removal of undocumented support for the
type
alias - Removal of the
sqlite
protocol for SQLite URLs - Better grammar for string literals
-
New Prisma Client APIs
findUniqueOrThrow
findFirstOrThrow
-
General improvements
- Deprecating
rejectOnNotFound
- Fix rounding errors on big numbers in SQLite
-
DbNull
,JsonNull
, andAnyNull
are now objects - Prisma Studio updates
- Dropped support for Node 12
- New default sizes for statement cache
- Renaming of
@prisma/sdk
npm package to@prisma/internals
- Removal of the internal
schema
property from the generated Prisma Client
- Deprecating
extendedIndexes
is now Generally Available
Starting with this release, we're excited to announce that extendedIndexes
is now Generally Available!
generator client {
provider = "prisma-client-js"
- previewFeatures = ["extendedIndexes"]
}
We introduced extendedIndexes
in 3.5.0
and have constantly been shipping improvements in the subsequent releases to the configuration of indexes.
You can now configure indexes in your Prisma schema with the @@​index
attribute to define the kind of index that should be created in your database. You can configure the following indexes in your Prisma Schema:
Sort, sort order, and length
The length
argument is available on MySQL on the @id
, @@​id
, @unique
, @@​unique
, and @​@​index
fields. It allows Prisma to support indexes and constraints on String
with a TEXT
native type and Bytes
types.
The sort
argument is available for all databases on the @unique
, @@​unique
, and @@​index
fields. SQL Server also allows it on @id
and @@​id
.
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Post {
title String @​db.VarChar(300)
abstract String @​db.VarChar(3000)
slug String @​unique(sort: Desc, length: 42) @​db.VarChar(3000)
author String
created_at DateTime
@​@​id([title(length: 100), abstract(length: 10)])
@​@​index([author, created_at(sort: Desc)])
}
Hash indexes for PostgreSQL
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model A {
id Int @​id
value Int
@​@​index([value], type: Hash)
}
GIN
, GiST
, SP-GiST
and BRIN
indexes for PostgreSQL
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @​id
title String
content String?
tags Json?
@​@​index([tags], type: Gin)
}
SQL Server index clustering
datasource db {
provider = "sqlserver"
url = env("DATABASE_URL")
}
model Post {
id Int @​default(autoincrement()) @​id(clustered: false)
title String
content String?
}
Refer to our docs to learn how you can configure indexes in your Prisma schema and the supported indexes for the different databases.
filterJson
is now Generally Available
This release moves the filterJson
Preview feature into General Availability! 🪄
generator client {
provider = "prisma-client-js"
- previewFeatures = ["filterJson"]
}
JSON filtering allows you to filter rows by the data inside a Json
type. For example:
const getUsers = await prisma.user.findMany({
where: {
petMeta: {
path: ['cats', 'fostering'],
array_contains: ['Fido'],
},
},
})
The filterJson
Preview feature has been around since May 2021, and we're excited to mark it ready for production use! Learn more in our documentation.
improvedQueryRaw
is now Generally Available
Prisma 4 now marks the improvedQueryRaw
Preview feature as Generally Available! 🤩
generator client {
provider = "prisma-client-js"
- previewFeatures = ["improvedQueryRaw"]
}
This change introduces two major improvements (both breaking, refer to the upgrade guide for a smooth upgrade) when working with raw queries with Prisma:
1. Scalar values are de-serialized as their correct JavaScript types
Raw queries now deserialize scalar values to their corresponding JavaScript types.
Note: Types are inferred from the values and not from the Prisma Schema types.
Here's an example query and response:
const res = await prisma.$queryRaw`SELECT bigint, bytes, decimal, date FROM "Table";`
console.log(res)
// [{ bigint: BigInt("123"), bytes: Buffer.from([1, 2]), decimal: new Prisma.Decimal("12.34"), date: Date("<some_date>") }]
Below is a table that recaps the serialization type-mapping for raw results:
Database Type | JavaScript Type |
---|---|
Text | String |
Int32 | Number |
Int64 | BigInt |
Float | Number |
Double | Number |
Numeric | Decimal |
Bytes | Buffer |
Json | Object |
DateTime | Date |
Date | Date |
Time | Date |
Uuid | String |
Xml | String |
2. PostgreSQL type-casts
Previously, PostgreSQL type-casts were broken. Here's an example query that used to fail:
await prisma.$queryRaw`SELECT ${1.5}::int as int`;
// Before: db error: ERROR: incorrect binary data format in bind parameter 1
// After: [{ int: 2 }]
You can now perform some type-casts in your queries as follows:
await prisma.$queryRaw`SELECT ${2020}::float4, (NOW() - ${"1 day"}::interval), ${"2022-01-01 00:00:00"}::timestamptz;`
A consequence of this fix is that some subtle implicit casts are now handled more strictly and would fail. Here's an example that used to work but won't work anymore:
await prisma.$queryRaw`SELECT LENGTH(${42});`
// ERROR: function length(integer) does not exist
// HINT: No function matches the given name and argument types. You might need to add explicit type casts.
The LENGTH
PostgreSQL function only accept text
as input. Prisma used to silently coerce 42
to text
but won’t anymore. As suggested by the hint, cast 42
to text
as follows:
await prisma.$queryRaw`SELECT LENGTH(${42}::text);`
Refer to our docs to learn more on raw query type mappings in Prisma.
4.0.0
, refer to our upgrade guide: Raw query type mapping: scalar values are now deserialized as their correct JavaScript types and Raw query mapping: PostgreSQL type-casts.
Defaults values for scalar lists (arrays)
Prisma 4 now introduces support for defining default values for scalar lists (arrays) in the Prisma schema.
You can define default scalar lists as follows:
model User {
id Int @​id @​default(autoincrement())
posts Post[]
favoriteColors String[] @​default(["red", "blue", "green"])
}
To learn more about default values for scalar lists, refer to our docs.
Improved default support for embedded documents in MongoDB
From version 4.0.0
, you can now set default values on embedded documents using the @default
attribute. Prisma will provide the specified default value on reads if a field is not defined in the database.
You can define default values for embedded documents in your Prisma schema as follows:
model Product {
id String @​id @​default(auto()) @​map("_id") @​db.ObjectId
name String @​unique
photos Photo[]
}
type Photo {
height Int @​default(200)
width Int @​default(100)
url String
}
Refer to our docs to learn more on default values for required fields on composite types.
4.0.0
.
Explicit unique constraints for 1:1 relations
From version 4.0.0
, 1:1 relations are now required to be marked with the @unique
attribute on the side of the relationship that contains the foreign key.
Previously, the relation fields were implicitly treated as unique under the hood. The field was also added explicitly when npx prisma format
was run.
model User {
id Int @​id @​default(autoincrement())
profile Profile? @​relation(fields: [profileId], references: [id])
profileId Int? @​unique // <-- include this explicitly
}
model Profile {
id Int @​id @​default(autoincrement())
user User?
}
references
on implicit m:n relations
Removed support for usage of This release removes the usage of the references
argument, which was previously optional when using m:n relations.
model Post {
id Int @​id @​default(autoincrement())
- categories Category[] @​relation("my-relation", references: [id])
+ categories Category[] @​relation("my-relation")
}
model Category {
id Int @​id @​default(autoincrement())
- posts Post[] @​relation("my-relation", references: [id])
+ posts Post[] @​relation("my-relation")
}
This is because the only valid value for references
was id
, so removing this argument clarifies what can and cannot be changed.
Refer to our docs to learn more about implicit m:n relations.
references
argument in 1:1 and 1:m relations for MySQL
Enforcing uniqueness of referenced fields in the From version 4.0.0
, Prisma will now enforce that the field on the references
side of a @relation
is unique when working with MySQL.
To fix this, add the @unique
or @id
attributes to foreign key fields in your Prisma schema.
4.0.0
, refer to our upgrade guide.
type
alias
Removal of undocumented support for the With 4.0.0
, we're deprecating the type
keyword for string aliasing. The type
keyword will now be exclusively used for defining embedded documents in MongoDB.
We encourage you to remove any usage of the type
keyword from your Prisma schema for type aliasing.
sqlite
protocol for SQLite URLs
Removal of the Starting from 4.0.0
, we are dropping support of the sqlite://
URL prefix for SQLite. We encourage you to use the file://
prefix when working with SQLite.
Better grammar for string literals
String literals in the Prisma schema now need to follow the same rules as strings in JSON. That changes mostly the escaping of some special characters.
You can find more details on the specification here:
To fix this, resolve the validation errors in your Prisma schema or run npx prisma db pull
to get the current values from the database.
findUniqueOrThrow
and findFirstOrThrow
New Prisma Client APIs: In this release, we're introducing two new APIs to Prisma Client:
-
findUniqueOrThrow
– retrieves a single record asfindUnique
but throws aRecordNotFound
exception when no record is not found -
findFirstOrThrow
– retrieves the first record in a list asfindFirst
but throws aRecordNotFound
exception when no record is found
Here's an example of usage of the APIs:
const user = await prisma.user.findUniqueOrThrow({
where: {
email: "alice@prisma.io",
},
})
user.email // You don't need to check if the user is null
The APIs will be convenient for scripts API routes where you're already handling exceptions and want to fail fast.
Note: Please use the APIs with care. If you use these APIs, add the proper guardrails to your application.
Refer to the API reference in our docs to learn how findUniqueOrThrow
and findFirstOrThrow
differ from findUnique
and findFirst
respectively.
rejectOnNotFound
Deprecating We're deprecating the rejectOnNotFound
parameter in favor of the new findUniqueOrThrow
and findFirstOrThrow
Prisma Client APIs.
We expect the new APIs to be easier to understand and more type-safe.
Refer to the findUniqueOrThrow
and findFirstOrThrow
docs to learn how you can upgrade.
Fix rounding errors on big numbers in SQLite
SQLite is a loosely-typed database. While Prisma will prevent you from inserting values larger than integers, nothing prevents SQLite from accepting big numbers. These manually inserted big numbers cause rounding errors when queried.
Prisma will now check numbers in the query's response to verify they fit within the boundaries of an integer. If a number does not fit, Prisma will throw a P2023
error:
Inconsistent column data: Conversion failed:
Value 9223372036854775807 does not fit in an INT column,
try migrating the 'int' column type to BIGINT
To learn more on rounding errors with big numbers on SQLite, refer to our docs.
DbNull
, JsonNull
, and AnyNull
are now objects
Previously, Prisma.DbNull
, Prisma.JsonNull
, and Prisma.AnyNull
used to be implemented using string constants. This meant their types overlapped with regular string data that could be stored in JSON fields.
We've now made them special objects instead that don't overlap with string types.
Before 4.0.0
DbNull
was checked as a string so you could accidentally check for a null as follows:
import { PrismaClient, Prisma } from '@​prisma/client'
const prisma = new PrismaClient()
const dbNull = "DbNull" // this string could come from anywhere!
await prisma.log.findMany({
data: {
meta: dbNull,
},
})
Expand to view the underlying Prisma schema
model Log {
id Int @​id
meta Json
}
Prisma 4 resolves this using constants guaranteed to be unique to prevent this kind of inconsistent queries.
You can now read, write, and filter JSON fields as follows:
import { PrismaClient, Prisma } from '@​prisma/client'
const prisma = new PrismaClient()
await prisma.log.create({
data: {
meta: Prisma.DbNull,
},
})
We recommend you double-check queries that use Json
after upgrading to Prisma 4. Ensure that you use the Prisma.DbNull
, Prisma.JsonNull
, and Prisma.AnyNull
constants from Prisma Client, not string literals.
Refer to the Prisma 4 upgrade guide in case you run into any type errors.
Prisma Studio updates
We've refined the experience when working with Prisma Studio with the following changes:
- Including a confirmation dialog before deleting records
- Adding a shortcut copy action on a cell – CMD + C on MacOS or Ctrl + C on Windows/ Linux
Dropped support for Node 12
The minimum version of Node.js Prisma will support is 14.17.x
. If you're using an earlier version of Node.js, you will need to update your Node.js version.
Refer to our system requirements for the minimum versions Prisma requires
New default sizes for statement cache
We had inconsistent and large default values (500 for PostgreSQL and 1000 for MySQL) for the statement_cache_size
. The new shared default value is 100.
If the new default doesn't work for you, please create an issue and use the statement_cache_size=x
parameter in your connection string to override the default value.
@prisma/sdk
npm package to @prisma/internals
Renaming of The internal package @prisma/sdk
is now available under the new, more explicit name @prisma/internals
.
We do not provide any API guarantees for @prisma/internals
as it might need to introduce breaking changes from time to time, and it does not follow semantic versioning.
This is technically not a breaking change as usage of the @prisma/sdk
package is neither documented nor supported.
If you're using @prisma/sdk
(now @prisma/internals
), it would be helpful if you could help us understand where, how, and why you are using it by giving us feedback in this GitHub discussion. Your feedback will be valuable to us in defining a better API.
schema
property from the generated Prisma Client
Removal of the internal We've removed the internal Prisma.dmmf.schema
to reduce the size of Prisma Client generated and improve boot times.
To access the schema
property, you can use the getDmmf()
method from @prisma/internals
.
Fixes and improvements
Prisma
- PSL: define the grammar of string literals
- MySQL: Update default
statement_cache_size
- You cannot define an index on fields with Native type Text of MySQL.
- Removal of undocumented support for
type
alias with Prisma 4.0.0 @unique
is added during Re-Introspection- [PSL] Do not allow
references
arg on Many2Many relations on SQL - prisma migrate dev will not allow for db level default on scalar list
- Postgres Single Quote Escaping Breaking Migrations
- [Epic]
extendedIndexes
GA - Remove preview feature
extendedIndexes
- Epic: Scalar List Defaults
- Implement scalar lists defaults proposal in PSL
- Implement scalar list defaults proposal in introspection
- Implement scalar list defaults proposal in migrations
- PANIC: called
Option::unwrap()
on aNone
value in query-engine/core/src/interpreter/query_interpreters/nested_read.rs:232:50 - Invalid
db pull
/db push
flow - Improve CLI output when using
db push
with MongoDB - DB Pull Error
- MongoDB composite index crashes
- Error: Error in migration engine. Reason: [migration-engine/core/src/commands/diff.rs:127:22] internal error: entered unreachable code: no provider, no shadow database url for migrations target
- Regression: Prisma 3.15.0 with macOS / Azure SQL Server errors at database connection
- Migrate internal duration/performance logging
- Fix CI support in prisma forks
- Allow setting the
length
prefix onUnsupported
fields on MySQL - CRDB: Handle unicode escaping in enum and string defaults in migrate/introspection
- Poor grammar and confusing language in Prisma CLI
- Datetime defaults: make sure we consume the whole expression
- @prisma/engine-core uses vulnerable
undici 5.1.1
package - getConfig/getDmmf: Clarify error messages on Rust panics
Prisma Client
- PANIC in libs/prisma-models/src/record.rs:161:30Invalid coercion encountered: ConversionFailure("Float(BigDecimal("519.05"))", "Decimal")
- Set array default
- Allow setting scalar list default values
- test(client): happy blog-env test has no assertion
- Avoid using magic string values for JsonNull/DbNull
PrismaClientInitializationError
is missing expected error code- Make the implicit unique constraints on 1:1 relations explicit
- PANIC: called
Result::unwrap()
on anErr
value: FieldNotFound { name: "upsert", model: "CcStructureUnit" } in query-engine/core/src/query_graph_builder/write/write_args_parser.rs:24:62 - Consider renaming the
@prisma/sdk
package to reduce confusion - PANIC: JSON target types only accept strings or numbers, found: {"bytes":"05010000000473436170"} in query-engine/connectors/sql-query-connector/src/filter_conversion.rs:542:22
- Cannot pass Prisma.empty to $executeRaw function
- Numerics in Postgres bigger than 2<<128 crash Prisma/Quaint
- Remove
sqlite:
for defining a sqlite url - PANIC: called
Option::unwrap()
on aNone
value in query-engine/core/src/interpreter/query_interpreters/nested_read.rs:232:50 - findMany broken with many relations to same entity
- PANIC: called
Option::unwrap()
on aNone
value in query-engine\core\src\interpreter\query_interpreters\nested_read.rs:232:50 - Large decimals cause panick
- Misleading Error for non-unique relation names
thread 'tokio-runtime-worker' panicked at 'called
Option::unwrap()on a
Nonevalue', /Users/runner/.cargo/git/checkouts/quaint-9f01e008b9a89c14/479e08a/src/connector/postgres/conversion/decimal.rs:81:39
- Implement scalar list defaults proposal in query engine and client
default(now())
on the same table sometimes yield different times
Language tools (e.g. VS Code)
Prisma Engines
Credits
Huge thanks to @shian15810, @zifeo, @ever0de, @givensuman, @peter-gy, @rushabhhere, @flatplate, @njmaeff, @tnzk, @DePasqualeOrg, @roboncode, @jacobhq for helping!
📺 Join us for another "What's new in Prisma" livestream
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma" livestream.
The stream takes place on YouTube on Thursday, June 30 at 5 pm Berlin | 8 am San Francisco.
📺 Learn how to upgrade in our webinar on July 12th
We're going to host a dedicated webinar with Prisma engineers to talk about the upgrade process. If you're unsure whether the breaking changes of this release affect you, be sure to not miss this livestream.
The stream takes place on YouTube on Tuesday, July 12 at 5 pm Berlin | 8 am San Francisco.
Configuration
-
If you want to rebase/retry this MR, check this box
This MR has been generated by Renovate Bot.