Mahmoud
07/13/2021, 3:02 PMschema.prisma
file, you’ll need to set the database provider to mongodb
. You’ll also need to add mongoDb
to the previewFeatures
property in the generator
block:
// Set the database provider to "mongodb"
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
// We want to generate a Prisma Client
// Since mongodb is a preview feature, we need to enable it.
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongoDb"]
}
// Create our Post model which will be mapped to a collection in the database.
// The id attributes tell Prisma it's a primary key and to generate
// object ids by default when inserting posts.
model Post {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
slug String @unique
title String
body String
}
You’ll also need to add a database connection string to your .env
file. We recommend using MongoDB Atlas to spin up a MongoDB database for free.
Learn more in our Getting Started Guide
We would love to know your feedback! If you have any comments or run into any problems we’re available in this issue. You can also browse existing issues that have the MongoDB label.
⚡️ Prisma native support for M1 Macs
This one’s for our Mac users. Prisma now runs natively on the new M1 chips. Best of all, there’s nothing to configure, it just works. Enjoy the speed bump!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
@ryan and @Daniel Norman will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.Mahmoud
07/27/2021, 10:57 AMMahmoud
08/10/2021, 5:12 PMinteractiveTransactions
preview feature in your Prisma Schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["interactiveTransactions"]
}
Note that the interactive transactions API does not support controlling isolation levels or locking for now.
You can find out more about implementing use cases with transactions in the docs, and share your feedback.
🎉 namedConstraints
are now in Preview
So far the Prisma schema could only represent the underlying database names for @@unique
and @@index
.
Names for primary keys and foreign keys could not be represented even when the database supported these. This could lead to problems with the names of constraints in different environments getting out of sync and generated migrations therefore failing.
You can opt-in to namedConstraints
by setting the namedConstraints
preview feature in your Prisma Schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["namedConstraints"]
}
When using prisma db pull
these names will now automatically be pulled into your Prisma schema unless they match our default naming convention (which follows the Postgres convention).
Please check our upgrade guide before enabling the preview flag and running migrate operations for the first time.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
@Daniel Norman and I will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.Mahmoud
08/24/2021, 4:54 PMfullTextSearch
preview flag:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["fullTextSearch"]
}
After you regenerate your client, you’ll see a new search
field on your String
fields that you can query on. Here’s an example:
// returns all posts that contain the words cat *or* dog.
const result = await prisma.post.findMany({
where: {
body: {
search: 'cat | dog',
},
},
})
You can learn more about how the query format works in our documentation. We would love to know your feedback! If you have any comments or run into any problems we’re available in this in this Github issue.
ℹ️ Validation errors for referential action cycles on Microsoft SQL Server
Prisma now checks for referential cycle actions when it validates your schema file and shows you the exact location of the cycle in your schema when using Microsoft SQL Server.
👋🏻 prisma introspect
is being deprecated in favor of prisma db pull
The prisma introspect
command is an alias for prisma db pull
, which allows you to pull the schema from the database into your local schema.prisma
file. Starting with this release, you will get a warning that encourages you to use prisma db pull
instead of prisma introspect
.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
@Mahmoud will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.Daniel Norman
09/07/2021, 5:39 PMprisma db seed
has been revamped
😛risma-red: Node-API
😛risma-darkblue: Order by Aggregate in Group By
😛risma: Order by Relation
😛risma-red: Select Relation Count
🤓 To read more about the GA release of the M*icrosoft SQL Server* and Azure SQL Connector, check out the blog post
📚 We recommend that you carefully read through the breaking changes in the release notes and make sure that you’ve correctly upgraded your application.📚
😛risma-rainbow: Help us spread the word about Prisma 😛risma-rainbow:
To help spread the word about Prisma, we’d appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter 🙌
🎥 **, where @User and I will discuss the latest release and other news from the Prisma ecosystem in a livestream on YouTube on Thursday at 5pm Berlin | 8am San Francisco.
📺 If you haven’t already, be sure to subscribe to our YouTube channel, so you get notified about new videos and livestreams!Daniel Norman
09/21/2021, 4:15 PMDaniel Norman
09/21/2021, 4:15 PMUser:Post
, you can configure the deletion of a user to cascade to posts so that no posts are left pointing to a User that doesn’t exist. In Prisma, these constraints are defined in the Prisma schema with the @relation()
attribute.
However, databases like PlanetScale do not support defining foreign keys. To work around this limitation so that you can use Prisma with PlanetScale, we’re introducing a new referentialIntegrity
setting in Preview.
This was initially introduced in version 2.24.0
of Prisma with the planetScaleMode
Preview feature and setting. Starting with this release both have been renamed to referentialIntegrity
.
The setting lets you control whether referential integrity is enforced by the database with foreign keys (default), or by Prisma, by setting referentialIntegrity = "prisma"
.
Setting Referential Integrity to prisma
has the following implications:
• Prisma Migrate will generate SQL migrations without any foreign key constraints.
• Prisma Client will emulate foreign key constraints and referential actions on a best-effort basis.
You can give it a try in version 3.1.1 by enabling the referentialIntegrity
preview flag:
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
referentialIntegrity = "prisma"
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity"]
}
⚠️ Note that Referential Integrity is set to prisma
by default when using MongoDB.
📚Learn more about Referential Integrity in our documentation.
😛risma-red: Full-Text Search for the Go Client
In an earlier release, we added Full-Text Search (for PostgreSQL) to the Typescript Client. This was released as a Preview feature.
In this release, we’ve added that Preview feature to the Go Client. Enable it in your Go project by adding the fullTextSearch
preview feature.
Here’s an example:
// Fetch all drafts with a title that contains the words fox or dog
posts, _ := client.Post.FindMany(
db.Post.Title.Search("fox | dog"),
db.Post.Status.Equals("Draft"),
).Exec(context.Background())
// Loop over the posts and print the title
for _, post := range posts {
fmt.Println(post.Title)
}
nikolasburk
10/05/2021, 3:31 PMprisma db pull
against a MongoDB database with existing data will sample the data and create a Prisma data model based on the stored documents.
This comes with a few caveats:
• The preview feature mongoDb
must be enabled on the datasource
block in the Prisma schema.
• The MongoDB instance must have at least one collection with at least one document.
• To introspect indices, there must be at least one document in the collection with the indexed fields.
• If any fields have conflicting types, the most common type is chosen and the other types are written to a comment above the field in the Prisma schema.
• Relations must be added manually after introspection.
• Running prisma db pull
multiple times will overwrite any added text in the data model for now.
We're constantly iterating on this feature, so please provide feedback for introspecting MongoDB databases!
🔢 Get the count of a relation in MongoDB
This release, we're giving MongoDB developers the ability to query the count of a relation. In the example below, we're getting the number of posts each user wrote:
const userWithPostsCount = await prisma.user.findMany({
include: {
_count: {
select: { posts: true },
},
},
})
// => [
// {
// email: "<mailto:alice@prisma.io|alice@prisma.io>",
// _count: { posts: 3 }
// }
// ]
This feature was previously available for SQL databases and now it's also available in MongoDB. Learn more in our documentation.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we'd very much appreciate if you would star the repo 🌟 And if you're excited about the features in this week's release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the "What's new in Prisma" livestream
This week, my colleague @Daniel Norman and I will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.nikolasburk
10/19/2021, 3:10 PM3.3.0
, we're releasing Early Access support for Prisma Client connection pooling using the Prisma Data Proxy. The Data Proxy feature of the Prisma Data Platform is now accessible to all users of the Prisma Data Platform (no need to request access). For detailed documentation and instructions about the Data Proxy, check out pris.ly/data-proxy.
Using this new feature in Prisma Client and leveraging the Data Proxy, developers can now also deploy Prisma applications on Cloudflare Workers. Here's what it looks like to use Prisma Client inside of this environment:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request: Request): Promise<Response> {
await prisma.log.create({
data: {
level: 'Info',
message: `${request.method} ${request.url}`,
},
})
return new Response(`request method: ${request.method}!`)
}
Follow this deployment guide to learn how to use Prisma Client with your own Cloudflare Workers.
🔀 Support for ordering by relation fields in MongoDB
In 2.16.0
, we first introduced ordering by a relation for relational databases. As of today's release, you can now order by a relation field in MongoDB as well:
ts
// Return a list of posts ordered by the author's email address
// in ascending order.
await prisma.post.findMany({
orderBy: {
author: {
email: "asc",
},
},
})
5️⃣ MongoDB 5 is now supported
Prisma now supports connecting to MongoDB 5 databases. Take advantage of the latest and greatest from the fine folks at MongoDB HQ and share your feedback in the #mongodb channel here on Slack!
🦦 Prisma Client Go now supports scalar list operations
With 3.3.0
, you can now filter and atomically update scalar lists with Prisma Client Go.
Given the following Prisma schema:
model User {
id Int @id @default(autoincrement())
name String
pets String[]
}
You can filter pets with the following code:
user, err := client.User.FindFirst(
db.User.Pets.HasSome([]string{"Fido", "Scooby"}),
).Exec(ctx)
And when you add a new furry addition to your family, you can update your list with `Push`:
user, err := client.User.FindUnique(
db.User.Name.Equals(1),
).Update(
db.User.Items.Push([]string{"Charlemagne"}),
).Exec(ctx)
Learn more about how to use this new feature in our documentation and share your feedback in the #prisma-client-go channel here on Slack!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we'd very much appreciate if you would star the repo 🌟 And if you're excited about the features in this week's release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the "What's new in Prisma" livestream
This week, my colleague @Daniel Norman and I will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.nikolasburk
11/02/2021, 5:08 PM3.4.0
provides support for PostgreSQL 14. For a full list of our supported databases and their versions, see our documentation.
🔀 Support for ordering by aggregate group in MongoDB
In Prisma version 3.4.0
, we add support on MongoDB databases for using the ORDER BY
clause in an aggregate function. This was previously available for relational databases.
For example, if the data about your application’s users includes their city of residence, you can determine which cities have the largest user groups. The following query sorts each city
group by the number of users in that group, and returns the results in descending order (largest group first):
const groupBy = await prisma.user.groupBy({
by: ['city'],
_count: {
city: true,
},
orderBy: {
_count: {
city: 'desc',
},
},
})
For more information refer to our documentation about ordering by groups.
✨ Initial support for MongoDB in prisma db push
The prisma db push
command is used to sync your Prisma schema and your database schema in development. Because MongoDB has a unique approach to database schema management, this initial release only syncs @unique
, @@unique
and @@index
annotations in your schema.
Check out the release notes for a practical example of using prisma db push
with MongoDB.
🔎 Introspection of embedded documents in MongoDB
For those interested in helping us getting introspection of embedded documents right, we packaged a first iteration into the CLI. More info in the Github issue.
🚀 Prisma Client Go now supports the Data Proxy
Connection limit issues got you down? By using Prisma’s Data Proxy, you can pool your connections to avoid overloading your database. With this release, Prisma Client Go can now read and write to the Data Proxy.
Check out the release notes for more info about this!
🦦 JSON filtering support in Prisma Client Go
We’ve had JSON filtering support in the TypeScript Client since . In today’s release, we’re bringing support to the Go Client. Here’s an example snippet of the API:
logs, _ := client.Log.FindMany(
db.Log.Meta.Path([]string{"service"}),
db.Log.Meta.Equals(db.JSON("\"api\"")),
).Exec(ctx)
Learn more about how to use this new feature in our documentation and share your feedback in the #prisma-client-go channel here on Slack!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
🌐 The Prisma Serverless Data Conference is happening on November 18
Make sure to claim your ticket for our free Prisma Serverless Data Conference about all things databases and serverless with fantastic speakers from companies like PlanetScale, MongoDB, Vercel, Netlify, Cloudflare and CockroachDB.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, my colleague @Alex Ruheni and I will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5pm Berlin | 8am San Francisco.nikolasburk
11/16/2021, 3:28 PM3.5.0
, we’ve added support for ordering full text search results by relevance. Ordering by relevance gives you a way to order search results by the best match.
While this feature is useful standalone, it’s most commonly used in combination with the full text search
field in the where
clause:
const query = "node.js developer"
const developers = await prisma.people.findMany({
where: {
bio: {
// Only select people whose bio's contain "node.js developer"
search: query,
},
},
orderBy: {
// Order that selection by query relevance.
_relevance: {
fields: ["bio"],
search: query,
sort: "desc",
},
},
})
Learn more in our documentation and if you run into any issues or have feedback for us, you can reach us in this issue.
⚙️ More configuration options for indexes and constraints in the Prisma schema (Preview)
We are extending the syntax in the Prisma schema to add support for configuration of length and sort order for:
• indexes
• unique constraints
• primary key constraints
The following example demonstrates the use of the sort
and length
arguments:
model Post {
title String @db.VarChar(300)
abstract String @db.VarChar(3000)
slug String @db.VarChar(3000) @unique(sort: Desc, length: 42)
author String
created_at DateTime
@@id([title(length: 100, sort: Desc), abstract(length: 10)])
@@index([author, created_at(sort: Desc)])
}
⚠️ Warning: This might be a breaking change for some users. To learn how to mitigate that, please read the documentation linked below.
Learn more in the documentation on index configuration.
🦦 Case insensitive filtering for Prisma Client Go
We’ve had this feature in the Prisma Client JS for a while, but in this release, we’ve added case-insensitive query support to the Go Client as well. Now you can worry a bit less about what kind of data the user is going to send your way.
users, err := client.User.FindMany(
User.Email.Equals("prisMa"),
User.Email.Mode(QueryModeInsensitive), // sets case insensitivity
).Exec(ctx)
Learn more in our documentation and share your feedback in the #prisma-client-go channel here on Slack!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
🌐 The Prisma Serverless Data Conference is happening on Thursday (Nov 18)
Make sure to claim your ticket for our free Prisma Serverless Data Conference about all things databases and serverless with fantastic speakers from companies like PlanetScale, MongoDB, Vercel, Netlify, Cloudflare and CockroachDB.
📰 Join us on Wednesday(!!!) for the “What’s new in Prisma” livestream
This week, my colleague @Daniel Norman and I will discuss the latest release and other news from the Prisma ecosystem in a on Wednesday at 5pm Berlin | 8am San Francisco.Alex Ruheni
11/30/2021, 3:23 PMdb pull+
, db push
and migrate
commands for MySQL and MongoDB databases as a Preview feature. For now, we do not enable the full-text search commands in the Prisma Client. They will be implemented separately. You can follow the progress in the MongoDB and MySQL issues.
Add the Preview feature fullTextIndex
to the Prisma schema, after which the @@fulltext
attribute is allowed in the Prisma schema:
generator js {
provider = "prisma-client-js"
previewFeatures = ["fullTextIndex"]
}
model A {
id Int @id
title String @db.VarChar(255)
content String @db.Text
@@fulltext([title, content])
}
Note: It is mandatory to do db pull
with the Preview feature enabled before using Prisma Migrate on existing MySQL databases, so the index types can be converted and will not get overwritten in the next migration.
For more details checkout our documentation.
💥 Hash index support for PostgreSQL (Preview)
With the extendedIndexes
Preview feature, it is now possible to use Hash
instead of the default BTree
as the index algorithm on PostgreSQL databases. A hash index can be much faster for inserts, but it only supports equals operation in the database. Here’s an example of using a hash index:
generator js {
provider = "prisma-client-js"
previewFeatures = ["extendedIndexes"]
}
model A {
id Int @id
value Int
@@index([value], type: Hash)
}
For more details checkout our documentation.
🚀 VS Code extension now uses a Wasm module
Starting with 3.6.0
, the language server and the VS Code extension use logic compiled to WebAssembly and distributed through npm. If you have any feedback, please leave an issue in the `prisma/language-tools` repository.
✨ Bytes
can now be filtered with in
and notIn
You can now use in
and notIn
operations on the Bytes
type:
const audioTracks = raws.map(raw => {
return Buffer.from(raw)
})
const result = await prisma.audio.find({
where: {
track:
in: audioTracks
}
}
})
👀 Json
fields now accept read-only types
You can now pass immutable values into Json
fields. In the following example, audit
is a Json
field that accepts a read-only array:
const trail = [
{ event: "signup" },
{ event: "subscribe" },
{ event: "invite friend" }
] as const
await prisma.user.create({
data: {
audit: trail
}
})
Learn more in this issue.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Daniel Norman will discuss the latest release and other news from the Prisma ecosystem in a on Wednesday at 5 pm Berlin | 8 am San FranciscoAlex Ruheni
12/21/2021, 3:44 PM3.7.0
😛risma-rainbow:
🧪 Referential actions support for MongoDB
In 3.7.0
, we’ve added MongoDB support for onDelete
and onUpdate
to specify how you want to handle changes to relationships. MongoDB does not support referential actions out of the box, but we can emulate this feature inside the Prisma Query Engine. Given the following schema:
model User {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
posts Post[]
name String
}
model Post {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
author User @relation(fields: [userId], references: [id], *onDelete: Cascade*)
title String
userId String @db.ObjectId
}
By specifying onDelete: Cascade
, Prisma will also delete posts whenever the author of the posts is deleted. There’s a lot more to referential actions than cascading deletes. Head over to our documentation to learn more. Prisma exposes features and workflows that database vendors don’t offer.
🔁 Prevent referential cycles on MongoDB
As part of getting onDelete
and onUpdate
ready for MongoDB, we’ve tightened up our validation rules to prevent a potential stack overflow if you create a loop with referential actions.
This change may cause some existing schemas using the mongodb
preview feature to become invalid, where your schema now errors out with the following message:
Error parsing attribute "@relation": Reference causes a cycle.
If you run into this, you can learn how to resolve it with this documentation. If you’re still stuck, feel free to open a discussion, and we’ll lend a hand!
⚠️ Deprecating undocumented usage of type
in Prisma Schema
With Prisma 3.7.0
release, the VS Code extension (and other IDEs using our language server implementation) will start to show a warning when detecting unsupported usage of the type
keyword. We plan to remove that functionality entirely with the next major release of Prisma. If you depend on similar functionality for type aliasing, please comment on the issue. Here’s an example of a string alias:
type MyId = String @id @default(dbgenerated(new_uuid()))
model A {
id MyId
}
🔒 Prisma Studio improvements
• Due to how Prisma Studio executes Prisma Client queries, it was possible to execute arbitrary code on Studio’s local server. This has since been patched.
• Issues with viewing and updating models with BigInt
fields are also resolved.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us today for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Alex Ruheni R. will discuss the latest release and other news from the Prisma ecosystem in a livestream on YouTube today at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
01/11/2022, 3:28 PM3.8.0
😛risma-rainbow:
🔍 Full-text search support for MySQL is now in Preview
Prisma now supports full-text search in MySQL. You can enable full-text support by adding the fullTextIndex
and fullTextSearch
Preview flags in your Prisma schema and defining @@fulltext()
index on fields you’d like to use full-text search on.
generator client {
provider = "prisma-client-js"
previewFeatures = ["fullTextIndex", "fullTextSearch"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Post {
id Int @id @default(autoincrement())
title String @unique
@@fulltext([title])
}
Run prisma db push
or prisma migrate dev
to update your database schema. Prisma Client will also be re-generated, enabling you to use full-text search in your application.
// search for titles that contain cat, but not fox
await prisma.post.findMany({
where: {
title: {
search: "+cat -fox",
},
},
})
Learn more in our documentation.
🚧 dataProxy
and interactiveTransactions
are now mutually exclusive
Before Prisma 3.8.0
, Prisma queries would fail whenever the Data Proxy and interactive transactions Preview features were used together. The interactiveTransactions and dataProxy Preview flags cannot be used together in this release. Generating the Prisma Client when both Preview features are enabled will throw an error.
🔧 Fixed support for push
when adding an element to an array in MongoDB
Prisma 3.8.0
fixed push
support for `ObjectId`s on MongoDB. Given the following schema:
model Course {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
title String
students String[] @db.Array(ObjectId)
}
You can now run the following query:
// Add a new student to the course
await prisma.course.update({
where: {
id: 1
},
data: {
students: {
push: new ObjectID("...")
}
}
})
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, I will discuss the latest release and other news from the Prisma ecosystem in a on Thursday at 5 pm Berlin | 8 am San FranciscoAlex Ruheni
02/01/2022, 3:42 PM3.9.0
😛risma-rainbow:
🛠️ Prisma Migrate improvements to troubleshoot migrations
Last year, we released Prisma Migrate for General Availability. Since then, we’ve gotten feedback from you to understand the challenges you experience building, testing, and deploying migrations. We’re thrilled to announce that we’re introducing new CLI commands to improve the experience troubleshooting migrations: prisma migrate diff
and prisma db execute
.
The prisma migrate diff
command creates a diff of your database schema, Prisma schema file, or the migration history. As a companion to the prisma migrate diff
, we also built prisma db execute
to execute SQL scripts against a database. This creates the possibility of building many new workflows such as forward and backward migrations with automation tooling. We’re looking forward to learning how they work for you and how we could make them better. You can learn about them here and give us feedback on the issue.
🦦 Preview support for CockroachDB
We are excited to announce Preview support for CockroachDB. CockroachDB support in Prisma is the product of collaboration with the Cockroach Labs team, and with this release, you can use Prisma in existing CockroachDB projects with introspection. To learn more, check out the release blog post and try it out with the getting started guide.
🌟 Raw query support for MongoDB
Prisma version 3.9.0
introduces raw queries to the MongoDB (Preview) connector. Raw queries help writing queries that Prisma doesn’t support yet, such as:
// To find zero or more documents matching a filter
const result = await prisma.user.findRaw({
filter: { age: { $gt: 25 } },
options: { projection: { _id: false } },
})
// To perform aggregation operations on a collection
await prisma.user.aggregateRaw({
pipeline: [
{ $match: { status: 'registered' } },
{ $group: { _id: '$country', total: { $sum: 1 } } },
],
})
// To run a command against the database
await prisma.$runCommandRaw({
aggregate: 'User',
pipeline: [
{ $match: { name: 'Bob' } },
{ $project: { email: true, _id: false } },
],
explain: false,
})
Learn more about Prisma’s new raw query API and how you can use it in our documentation.
➿ Concurrency issues with Interactive Transactions
Prisma version 3.9.0
resolved issues experienced around timeouts and rollbacks when there were concurrent reads and writes. If you experienced timeouts or your interactive transactions weren’t working quite as expected, now’s the time to make the upgrade and give it another go.
Learn more about Interactive Transactions in our documentation.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma. 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Daniel Norman will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
02/22/2022, 6:49 PM3.10.0
😛risma-rainbow:
We are working towards a stable release of MongoDB and are shipping lots of improvements. All the major features and breaking changes in this release therefore only apply to the MongoDB connector. Take a closer look if you are using the Preview of MongoDB as some of the changes are breaking.
📄 Embedded documents support is now in preview
We’re super excited to announce that Prisma version 3.10.0
supports reading and modifying embedded documents. Embedded documents will provide access to a new type
keyword in your Prisma schema that you can use to define composite types.
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongoDb"]
}
model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
photos Photo[]
}
type Photo {
height Int
width Int
url String
}
Given the schema above, you can now read and write to the embedded photos
array:
// Create a new product with an embedded list of photos
const product = await prisma.product.create({
data: {
name: "Forest Runners",
price: 59.99,
// Create an embedded list of photos in the product
photos: [
{ height: 100, width: 200, url: "1.jpg" },
{ height: 300, width: 400, url: "2.jpg" },
],
},
})
You can read further in our documentation. Feel free to open an issue if you run into anything, and we’ll give you a hand!
🔍 Introspection of embedded documents is now enabled by default
We added Preview support for embedded documents in version 3.4.0
and are now activating it for all users. Running prisma db pull
against your MongoDB database will generate type
definitions within your Prisma schema. When introspecting your database, you can switch off the depth with -composite-type-depth=0
, or limit it with, for example, --composite-type-depth=2
.
Feel free to drop your feedback on the feature on GitHub.
🚨 @default(dbgenerated())
is now replaced with @default(auto())
The original purpose of dbgenerated
is to support SQL expressions Prisma doesn’t understand yet. However, MongoDB doesn’t have a concept of default value expressions like SQL does. We took this opportunity to simplify handling the default values in MongoDB.
🚨 Many-to-Many relations now require a references
argument
Prisma version 3.10.0
now enforces all arguments in a MongoDB many-to-many relation. This means a @relation
attribute must define fields
and references
arguments on both sides. The fields
argument must point to a scalar field in the same model, and this scalar field must be an array. The references
arguments must point to a scalar field in the opposite model, and it must be a singular type of the same base type as the referencing array on the other side.
model Post {
id String @id @map("_id") @default(auto()) @db.ObjectId
category_ids String[] @db.ObjectId
categories Category[] @relation(fields: [category_ids], references: [id])
}
model Category {
id String @id @map("_id") @default(auto()) @db.ObjectId
post_ids String[] @db.ObjectId
posts Post[] @relation(fields: [post_ids], references: [id])
}
🚨 db.Array(ObjectId)
is now updated to @db.ObjectId
The original purpose of dbgenerated
is to support SQL expressions Prisma doesn’t understand yet. However, MongoDB doesn’t have a concept of default value expressions like SQL does. We took this opportunity to simplify how we handle the default values in MongoDB.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @Austin and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
03/15/2022, 8:21 PM3.11.0
😛risma-rainbow:
📦 Experimental support for embedded document filters (MongoDB)
In the previous release, we added embedded document support for creates, updates, and deletes. In version 3.11.0
, we’re adding experimental support for filtering embedded documents. Given the following schema:
model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
photos Photo[]
}
model Order {
id String @id @default(auto()) @map("_id") @db.ObjectId
shippingAddress Address
billingAddress Address? /// optionally embedded document
}
type Photo {
height Int
width Int
url String
}
type Address {
street String
city String
zip String
}
You can now add filters within an embedded document:
// find all orders with the same shipping address
const orders = await prisma.order.findMany({
where: {
shipping: {
equals: {
street: "555 Candy Cane Lane",
city: "Wonderland",
zip: "52337",
},
},
},
})
You can also add a filter on a “contains many” relationship:
// find all products that don't have photos
const product = prisma.product.findMany({
where: {
photos: {
isEmpty: true
}
},
})
This scratches the surface of what’s possible. For a complete list of available operations, have a look at our documentation. Please share your feedback in this issue.
🗃️ Ordering by embedded documents is in Preview (MongoDB)
In addition to filtering, version 3.11.0
now supports sorting by by an embedded document. Using the example schema above, you can sort orders by their zip code:
// sort orders by zip code in ascending order
const orders = await prisma.order.findMany({
orderBy: {
shippingAddress: {
zip: "asc",
},
},
})
Learn more about this feature in our documentation, and don’t hesitate to reach out in this issue.
:wood: MongoDB query logging support
In this release, we’ve added the ability to log MongoDB queries. You can enable query logging in the PrismaClient
constructor:
const prisma = new PrismaClient({
log: [
{
emit: 'event',
level: 'query',
},
]
})
prisma.$on('query', (e) => console.log(e.query))
The logs output by Prisma have the same format as the mongosh
console, so you can pipe the queries from your logs directly into your shell.
🔒 MongoDB introspection update
We’ve updated the type inference behavior for MongoDB on introspection. On introspection, Prisma samples the data of a field to find an appropriate type.
In the past, Prisma picked the type used most often for fields with data with multiple types. However, this could cause problems when retrieving mixed data during runtime and throwing exceptions, such as Prisma Studio or in Prisma Client queries.
From 3.11.0
, Prisma defaults to the Json
type to all fields with mixed data types. Additionally, Prisma still shows a warning on the console and adds a comment to the introspected Prisma schema so it is clear where such cases occur and that you can do something to fix them.
🚀 Prisma Client logger revamp
In 3.11.0
, we’ve rewritten our internal logger to reduce lock contention and enable future features like tracing. If you’re running into query performance issues, please open an issue.
🦦 CockroachDB now supports migrations (Preview)
We’re excited to announce Preview support for migrations for CockroachDB. Give it a try and let us know what you think in this issue.
🔍 Detecting state of a diff with migrate diff
using exit code
Prisma version 3.11.0
includes a new --exit-code
flag to the migrate diff
to detect the state of a diff. Please read about it in the reference documentation.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma. 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @Austin and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 9 am San Francisco.Matt Mueller (Prisma Client PM)
03/24/2022, 8:39 PM3.11.1
patch release. It's a big one for our MongoDB community 🌿 😛risma-rainbow:
📌 All of the changes below are specific to the MongoDB Preview. This will be our last release before we announce MongoDB support as production-ready. Please, please, please give these changes a try and tell us know what you think in this issue or jump on a quick call with us. 🍻
❗ Breaking: Filters no longer return undefined
fields by default
In preparation for MongoDB General Availability, we've changed what data is returned when filtering MongoDB documents on undefined
fields. The new rule is that undefined
fields are excluded by default unless explicitly filtered for. This allows you to query for undefined and null values separately.
Let's take a look at a concrete example. Given the following Prisma schema:
model Address {
id Int @id @map("_id")
city String
street String? // Note that street is optional
}
For Mongo, optional fields can either be null
or undefined
(absent). The following documents are all valid for the schema above:
{ "_id": 1, "city": "San Fransisco", "street": "Market st." }
{ "_id": 2, "city": "Seattle", "street": null }
{ "_id": 3, "city": "Chicago" }
Prior to 3.11.1
, if you queried for where: { street: null }
, you'd get _id: 2
and _id: 3
. In 3.11.1
, you'll only get _id: 2
. The ability to also query for the missing fields has also been added. For details, refer to the new isSet
below to learn more.
🪑 New isSet
filter operation
To compensate for missing fields on documents no longer being returned by the filters above, we’ve added a new isSet: bool
filter. This filter can be used to include fields that are undefined
on documents.
Using the example above, to include the undefined
fields, you can use an `OR`:
await prisma.address.findMany({
where: {
OR: [
{ street: { isSet: false } },
{ street: null }
]
}
})
The isSet
operation has been added to all scalar and embedded fields that are optional.
🚯 New unset
operation
In 3.11.1
, you can also remove a field with the unset
operation. Using the example above, let's write a query to remove the street field:
await prisma.address.update({
where: {
id: 10,
},
data: {
street: {
unset: true,
},
},
})
This effectively sets the street
field to undefined
in the database.
🐙 New updateMany
embedded operation
We now support updating embedded documents that match specific criteria.
For example, given the following schema:
model Product {
id Int @id @map("_id")
name String @unique
photos Photo[]
}
type Photo {
height Int @default(200)
width Int @default(100)
url String
}
Let's update the photo with a url
of 1.jpg
to `2.png`:
const product = prisma.product.update({
where: {
id: 10,
},
data: {
photos: {
updateMany: {
where: {
url: '1.jpg',
},
data: {
url: '2.png',
},
},
},
},
})
⛔ New deleteMany
embedded operation
Similar to updateMany
, you can also remove embeds that match specific criteria. Using the Prisma Schema above, let's delete all photos with a height
of 100:
const product = prisma.product.update({
where: {
id: 10,
},
data: {
photos: {
deleteMany: {
where: {
height: 100,
},
},
},
},
})
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.Alex Ruheni
04/05/2022, 3:28 PM3.12.0
😛risma-rainbow:
:mongodb:*MongoDB is now Generally Available*
Today we’re proud to announce that MongoDB is now stable and production-ready. After upgrading to 3.12.0
, you can remove the MongoDB preview flag in your schema:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
- previewFeatures = ["mongoDb"]
}
Here are some of the feature highlights we developed over this period:
• Expressive and type-safe operations for querying MongoDB embedded documents
• Increased likelihood of referential integrity in your database
• Thorough introspection support for using Prisma with existing MongoDB databases
• Declarative index management right from your Prisma Schema with db push
• Powerful raw query APIs to help you incrementally migrate to Prisma
You can learn about these features in the release blog post and more in our freshly brewed MongoDB Guide. For newcomers to Prisma with MongoDB, we recommend checking out our Getting Started Guide.
To celebrate this milestone, we invite you to join Prisma’s MongoDB Launch Week starting on April 25th. Enjoy a jam-packed week of exclusive workshops with plenty of opportunities to win free MongoDB Atlas credits and swag. It’s free to sign-up and available anywhere you have an internet connection.
🚨 Please be aware that we made a few breaking changes to tie up loose ends before General Availability:
• `@db.Array` replaced with `@db.ObjectId`
• Removed Decimal support
We made some changes in the `3.11.1` patch release, in case you missed it.
🗄️ Index support on composite type fields
We also added support for adding indexes on embedded document fields in MongoDB. You can now define a normal, unique, or full-text index in your schema.
type Address {
street String
number Int
}
model User {
id Int @id
email String
address Address
@@index([email, address.number]) /// normal index
@@unique([email, address.street]) /// unique index
@@fulltext([email, address.street]) /// full-text index
}
Note: Prisma Client does not yet fully support this feature and will be rolled out in a future release🔌 Improved connection pooling resiliency In
3.12.0
, we busted a ghost that has been bugging teams since the early days of the Prisma ORM. Under certain amounts of load, some people reported that the connection pool would sometimes drop connections or deadlock and not recover.
After many sightings and much head-scratching, we could finally reproduce the issue. This allowed us to narrow down the problem to one of our dependencies and fix the problem.
To read the nitty-gritty details of the problem and our solution, check out this issue.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma. 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo, 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk, @Sabin Adams, and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
04/26/2022, 4:49 PM3.13.0
😛risma-rainbow:
🔍 migrate diff
and db execute
are now Generally Available!
We’re proud to announce that the commands are now Generally Available and can now be used without the --preview-feature
flag. 🎉
The prisma migrate diff
and prisma db execute
commands make it possible to build many new workflows such as forward and down migrations with some automation tooling. Take a look at our documentation to learn some of the popular workflows these commands unlock:
• Fixing failed migrations
• Squashing migrations
• Generating down migrations
Let us know what tools, automation, and scripts you build using these commands.
🔮 SQL Server index clustering(Preview)
In version 3.5.0
, we introduced the extendedIndexes
Preview feature which we have constantly been adding new configuration options for indexes. In this release, we added support for enabling or disabling index/constraint clustering in SQL Server.
By default, indexes will be clustered by default. You can update this in your schema as follows to disable index clustering:
datasource db {
provider = "sqlserver"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["extendedIndexes"]
}
model Post {
id Int @default(autoincrement()) @id(clustered: false)
title String
content String?
}
The following SQL will be generated in your migration when you run prisma migrate dev
CREATE TABLE [Post] (
id INT NOT NULL,
[title] VARCHAR(255) NOT NULL,
[content] NVARCHAR(1000),
CONSTRAINT [Post_pkey] PRIMARY KEY NONCLUSTERED (id)
)
If you’ve enabled the extendedIndexes
Preview feature, this is potentially a breaking change. Refer to our documentation to learn how you can upgrade from a previous version.
🦦 Updated native types for CockroachDB (Preview)
We have revamped the native types available in the CockroachDB connector. We initially re-used the PostgreSQL native types because they were close enough, but we have now adapted our list of the supported native types to match what CockroachDB supports.
If you are already using CockroachDB in your project, you can run prisma db pull
to update all the native types in your Prisma schema. Refer to our documentation for the complete list of all CockroachDB native types.
OpenSSL 3.0 support
We’re excited to announce that version 3.13.0
now supports OpenSSL 3.0.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk, @Sabin Adams, and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
05/10/2022, 2:57 PM3.14.0
😛risma-rainbow:
🦦 CockroachDB connector is now Generally Available!
We are proud to announce that the CockroachDB connector is now stable and Generally Available.
If you’re upgrading from Prisma version `3.9.0`+ or the PostgreSQL connector, you can now run npx prisma db pull
and review the changes to your schema. To learn more about CockroachDB-specific native types we support, refer to our docs.
To learn more about the connector and how it differs from PostgreSQL, head to our documentation.
⚡*️ PostgreSQL GIN
, GiST
, SP-GiST
, and BRIN
indexes support (Preview)*
This release has expanded index type support with the GIN, GiST, SP-GiST, and BRIN indexes.
To make use of an index type, you can update your Prisma schema by providing the type
argument to the @@index
attribute:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["extendedIndexes"]
}
model Post {
id Int @id
title String
content String?
tags Json?
@@index([tags], type: Gin)
}
The following SQL will be generated in your migration when you run `prisma migrate dev`:
CREATE TABLE "Post" (
"id" INTEGER NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT,
"tags" JSONB,
CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "Post_tags_idx" ON "Post" USING GIN ("tags");
To learn more about configuring index types in your schema, refer to our documentation.
:magic_wand: Improved queryRaw
API
In this release, we made improvements to the SQL raw API. Some improvements are breaking and will be available behind the new improvedQueryRaw
Preview feature flag.
generator client {
provider = "prisma-client-js"
previewFeatures = ["improvedQueryRaw"]
}
The improvedQueryRaw
Preview feature solves most of the issues faced when working with the raw API. We would encourage you to turn on the Preview feature flag, try out the new API, and let us know how we can make it even better. Here are some of the improvements we made to `queryRaw`:
1. Raw scalar values are deserialized as their correct JavaScript types
Prisma Client queries such as findMany
deserialize database scalar values to their corresponding JavaScript types. For example, a DateTime
value is deserialized as a JavaScript Date,
and a Bytes
would be deserialized as a JavaScript Buffer
.
Raw queries now implement the same behavior when the improvedQueryRaw
Preview feature flag is enabled. The types of values from the database will be used instead of the types in the Prisma schema.
2. PostgreSQL type-casts
We’ve also fixed a lot of PostgreSQL type-casts that were broken by enabling the improvedQueryRaw
Preview feature flag. A consequence of this fix is that some subtle implicit casts are now handled more strictly and would fail.
3. Query parameters are correctly sent to the database
Before this release, query parameters of type BigInt
, Bytes
, and Decimal
were incorrectly sent to the database leading to instances of unexpected inserts. Passing the types as query parameters now works:
await prisma.$executeRaw`INSERT INTO "Table" ("bigint", "bytes", "decimal") VALUES (${BigInt("123")}, ${Buffer.from([1, 2, 3])}, ${Decimal("12.23")});`
This improvement is available without the📚 Learn more in the release notes For more info and links to documentation, you can read the release notes. 🌟 Help us spread the word about Prisma 🌟 To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter. 📰 Join us on Thursday for the “What’s new in Prisma” livestream This week, @nikolasburk and @Sabin Adams will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Preview feature flag.improvedQueryRaw
Alex Ruheni
06/07/2022, 5:21 PM3.15.0
😛risma-rainbow:
🔮 Improvements to Prisma Client for Data Proxy
The Prisma Data Proxy provides connection management and pooling for database connections for efficiently scaling database connections in serverless environments. The Prisma Client for Data Proxy includes support for connecting to the Prisma Data Proxy using HTTP.
One of the changes in this release is improving the Prisma Client for the Data Proxy generation step. You can now generate Prisma Client for the Data Proxy it using the --data-proxy
flag:
npx prisma generate --data-proxy
We also updated how you can run Prisma Client using the Data Proxy in Cloudflare Workers and Edge environments. You can now use @prisma/client/edge
instead of @prisma/client
in your application.
import { PrismaClient } from '@prisma/client/edge'
To learn more, check out our documentation.
📊 Prisma Client Metrics is now in Preview
Metrics is a new Preview feature that allows you to monitor how Prisma Client interacts with your database. Metrics expose a set of counters, gauges, and histograms that can be labeled and piped into an external monitoring system like Prometheus or StatsD.
You can use metrics in your project to help diagnose how your application’s number of idle and active connections changes with counters, gauges, and histograms. To get started using metrics in your project, enable the Preview feature flag in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["metrics"]
}
You can then get started using metrics in your project:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const metrics = await prisma.$metrics.json()
console.log(metrics)
To learn more, check out the metrics documentation. Give it a try and let us know what you think.
🔧 migrate reset
now returns with a non-0 exit code if the seed script returns with a non-0 exit code
This will help user scripts know more about the success of the command but might break existing scripts.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma. 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo, And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @Tasin Ishmam and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Michelle Greer
06/28/2022, 3:10 PMAlex Ruheni
06/28/2022, 3:14 PM4.0.0
😛risma-rainbow:
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 find a detailed guide in the Prisma 4 Upgrade guide.
Here’s a summary of the changes:
🦦 Preview features moved to General Availability:
• extendedIndexes
• filterJson
• improvedQueryRaw
🗃️ Default values for scalar lists
Prisma 4 now introduces support for defining default values for scalar lists (arrays) in the Prisma schema. You can define default scalar lists in your schema as follows:
model User {
id Int @id @default(autoincrement())
posts Post[]
favoriteColors String[] @default(["red", "blue", "green"])
}
Refer to our docs to learn more about this feature.
:mongodb: Improved default support for embedded documents
From version 4.0.0
, you can now define 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.
Refer to our upgrade guide for a detailed explanation and steps when working with default fields on composite types in MongoDB.
:magic_wand: New Prisma Client APIs – findUniqueOrThrow
& findFirstOrThrow
We’re introducing two new APIs to Prisma Client:
• findUniqueOrThrow
– retrieves a single record as findUnique
but returns RecordNotFound
exception when no record is not found
• findFirstOrThrow
– retrieves the first record in a list as findFirst
but returns a RecordNotFound
exception when no record is found
The APIs will be convenient for scripts API routes where you’re already handling exceptions and want to fail fast.
🚀 Improvements and breaking changes
Here’s a list of more breaking changes and improvements we shipped:
• Deprecating rejectOnNotFound
• Fix rounding errors on big numbers in SQLite
• DbNull
, JsonNull
, and AnyNull
are now objects
• Prisma Studio updates
• Dropped support for Node 12
• New default sizes for statement cache
• Removal of undocumented support for the type
alias
• Removal of the sqlite
protocol for SQLite URLs
• Better grammar for string literals
• Explicit unique constraints for 1:1 relations
• Removed support for the usage of references
on implicit m:n relations
• Enforcing the uniqueness of referenced fields in the references
argument in 1:1 and 1:m relations for MySQL
• Renaming of @prisma/sdk
npm package to @prisma/internals
• Removal of the internal schema
property from the generated Prisma Client
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Sabin Adams will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
07/19/2022, 1:46 PM4.1.0
😛risma-rainbow:
In case you missed it, we held a last week and walked through issues you may run into while upgrading to Prisma 4 and how to fix them!
🧩 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 on 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:
1. Prisma Client now correctly releases memory on Prisma Client instances that are no longer being used. Learn more in this GitHub issue
2. 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:
1. An always visible filter panel and functionality to clear all filters at once
2. Improved relationship model view with more visible buttons
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @Tasin Ishmam and @Sabin Adams will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
08/09/2022, 12:29 PM4.2.0
😛risma-rainbow:
📈 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.
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 have improved the interactiveTransactions
Preview feature with the support for defining the isolation level of an interactive transaction. 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,
}
)
Learn more about it 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. 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.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate it if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @Tasin Ishmam and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Alex Ruheni
08/30/2022, 5:25 PM4.3.0
😛risma-rainbow:
🦦 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.
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 columns against each other. 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 your thoughts on this GitHub issue.
🧩 Count by filtered relation (Preview)
This release adds support for the ability to count by a filtered relation. You can enable this feature by adding the filteredRelationCount
Preview feature flag. You can now express the following query:
// Count all published user posts
await prisma.user.findMany({
select: {
_count: {
posts: { where: { published: true } },
},
},
})
Learn more in our documentation and let us know what you think in this issue
🤹🏾 Multi-schema support (Experimental)
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 your thoughts on this GitHub issue.
🚀 Prisma CLI exit code fixes
We’ve made several improvements to the Prisma CLI to ensure it returns the correct exit code in the event of a failure. Read more about the improvements in the release notes.
🔍 Improved precision for the tracing
Preview feature
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.
:magic_wand: 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
, and type
) of your Prisma schema in the Outline view. This makes it easier to navigate to a block in 1 click.
• 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.
🔌 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 ready to share our proposed design and 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!
For further details, refer to this GitHub issue. Please have a read, and let us know what you think!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Sabin Adams will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.janpio
09/27/2022, 7:30 PM4.4.0
😛risma-rainbow:
🧹 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 of the release notes.
Some of the notable 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
🎚️ 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([ ])
. For example:
await prisma.$transaction(
[
// sequential operations
prisma.user.create({ data: {/** args */ } }),
prisma.post.create({ data: {/** args */ } })
],
{
isolationLevel: Prisma.TransactionIsolationLevel.Serializable
}
)
Learn more about it in our documentation.
🔏 New P2034
error code for transaction conflicts or deadlocks
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.
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, @nikolasburk and @Alex Ruheni. will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5pm Berlin | 8 am San Francisco.Tasin Ishmam
10/18/2022, 6:03 PM4.5.0
😛risma-rainbow:
🔍 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.
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.
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")]
}
Please visit our documentation to learn more about this feature or leave a comment with feedback on the GitHub issue.
🔗 Change to Referential Integrity — property in datasource
block renamed to relationMode
(Preview)
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
.
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)
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.
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
Many people were having issues with an "Invalid string length" error both in Prisma Studio and Data Browser. This issue can be resolved through this workaround. With this release, the root cause of this issue has been fixed.
📃 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!
📚 Learn more in the release notes
For more info and links to documentation, you can read the release notes.
🌟 Help us spread the word about Prisma 🌟
To help spread the word about Prisma, we’d very much appreciate if you would star the repo 🌟 And if you’re excited about the features in this week’s release, then help us and share your excitement on Twitter.
📰 Join us on Thursday for the “What’s new in Prisma” livestream
This week, Niko and I will discuss the latest release and other news from the Prisma ecosystem in a this Thursday at 5 pm Berlin | 8 am San Francisco.Tasin Ishmam
10/20/2022, 2:30 PM