Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
APACHE-2.0 License
Bot releases are visible (Hide)
Published by ruheni about 2 years ago
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
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.
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.
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.
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.
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.
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!
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:
Many thanks! 🙌🏽
dataproxy
to have datasource overrideslibs\datamodel\connectors\dml\src\model.rs:494:29
(missing PK?)prisma db pull
on SQL Server
prisma db pull
Huge thanks to @shian15810, @zifeo, @lodi-g, @Gnucki, @apriil15, @givensuman, @peter-gy for helping!
We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:
Try it out and let us know what you think!
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.
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.
Published by Jolg42 about 2 years ago
Today, we are issuing the 4.1.1
patch release.
Published by ruheni over 2 years ago
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
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!
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.
In this release, we've fixed the following issues experienced when setting up and tearing down Prisma Client while running tests:
These fixes will allow you to run your tests a little faster!
We're refining the experience when working with Prisma studio with the following changes:
Let us know what you think, and in the event, you run into any issues, please create a GitHub issue
prisma format
strips comments on block level attributesprisma --version
crashes if openssl
isn't properly installed@prisma/internals
Option::unwrap()
on a None
value"//
comments in the generator and datasource blocksprisma generate
: Non-functional debounce mechanism for watch mode@id
is suggested and fix@prisma/engines
Huge thanks to @shian15810, @zifeo, @lodi-g, @Gnucki, @apriil15 for helping!
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.
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.
Published by ruheni over 2 years ago
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.
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
Here's a TL;DR:
extendedIndexes
filterJson
improvedQueryRaw
references
on implicit m:n relationsreferences
argument in 1:1 and 1:m relations for MySQLtype
aliassqlite
protocol for SQLite URLsfindUniqueOrThrow
findFirstOrThrow
rejectOnNotFound
DbNull
, JsonNull
, and AnyNull
are now objects@prisma/sdk
npm package to @prisma/internals
schema
property from the generated Prisma ClientextendedIndexes
is now Generally AvailableStarting 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:
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)])
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model A {
id Int @id
value Int
@@index([value], type: Hash)
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @id
title String
content String?
tags Json?
@@index([tags], type: Gin)
}
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.
⚠️ Breaking change: If you previously configured the index properties at the database level, refer to the upgrade guide for a detailed explanation and steps to follow.
filterJson
is now Generally AvailableThis 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 AvailablePrisma 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:
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 |
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.
⚠️ Breaking change: To learn how you can smoothly upgrade to version 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.
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.
⚠️ Breaking change: Refer to the upgrade guide for a detailed explanation and steps to follow.
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.
⚠️ Breaking change: Refer to our upgrade guide for detailed explanation and steps when working with default fields on composite types in MongoDB from version 4.0.0
.
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?
}
⚠️ Breaking change: Refer to our upgrade path for a detailed explanation and steps to follow.
references
on implicit m:n relationsThis 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.
⚠️ Breaking change: Refer to the upgrade guide for a detailed explanation and steps to follow.
references
argument in 1:1 and 1:m relations for MySQLFrom 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.
⚠️ Breaking change: To learn how to upgrade to version 4.0.0
, refer to our upgrade guide.
type
aliasWith 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 URLsStarting 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.
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.
⚠️ Breaking change: To learn how to update your existing schema, refer to the upgrade guide.
findUniqueOrThrow
and findFirstOrThrow
In this release, we're introducing two new APIs to Prisma Client:
findUniqueOrThrow
– retrieves a single record as findUnique
but throws a RecordNotFound
exception when no record is not foundfindFirstOrThrow
– retrieves the first record in a list as findFirst
but throws a RecordNotFound
exception when no record is foundHere's an example of usage of the APIs:
const user = await prisma.user.findUniqueOrThrow({
where: {
email: "[email protected]",
},
})
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
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.
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 objectsPreviously, 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,
},
})
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.
We've refined the experience when working with Prisma Studio with the following changes:
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
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
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 ClientWe'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
.
statement_cache_size
type
alias with Prisma 4.0.0@unique
is added during Re-Introspectionreferences
arg on Many2Many relations on SQLextendedIndexes
GAextendedIndexes
Option::unwrap()
on a None
value in query-engine/core/src/interpreter/query_interpreters/nested_read.rs:232:50db pull
/ db push
flowdb push
with MongoDBlength
prefix on Unsupported
fields on MySQLundici 5.1.1
packagePrismaClientInitializationError
is missing expected error codeResult::unwrap()
on an Err
value: FieldNotFound { name: "upsert", model: "CcStructureUnit" } in query-engine/core/src/query_graph_builder/write/write_args_parser.rs:24:62@prisma/sdk
package to reduce confusionsqlite:
for defining a sqlite urlOption::unwrap()
on a None
value in query-engine/core/src/interpreter/query_interpreters/nested_read.rs:232:50Option::unwrap()
on a None
value in query-engine\core\src\interpreter\query_interpreters\nested_read.rs:232:50thread 'tokio-runtime-worker' panicked at 'called
Option::unwrap()on a
None value', /Users/runner/.cargo/git/checkouts/quaint-9f01e008b9a89c14/479e08a/src/connector/postgres/conversion/decimal.rs:81:39
default(now())
on the same table sometimes yield different timesHuge thanks to @shian15810, @zifeo, @ever0de, @givensuman, @peter-gy, @rushabhhere, @flatplate, @njmaeff, @tnzk, @DePasqualeOrg, @roboncode, @jacobhq for helping!
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.
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.
Published by millsp over 2 years ago
Today, we are issuing the 3.15.2
patch release.
In order to use the Prisma Data Proxy via Prisma Client, you need to generate it with prisma generate --data-proxy
as described in our documentation. We are introducing PRISMA_GENERATE_DATAPROXY="true"
as an additional way to do the same thing, but via an environment variable.
This is necessary, for example, to reliably deploy a Prisma Client for Data Proxy on Vercel Serverless Functions, where it can be hard to update the build command to run prisma generate --data-proxy
. Starting with this version you can just set PRISMA_GENERATE_DATAPROXY="true"
as an environment variable the Vercel project settings.
If you are unfamiliar with the Data Proxy, read how to get started.
Published by Jolg42 over 2 years ago
Today, we are issuing the 3.15.1
patch release.
Published by ruheni over 2 years ago
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
In this release, we're shipping a couple of 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 provides support for connecting to the Prisma Data Proxy using HTTP.
We introduced this feature in version 3.3.0
and constantly shipped features, fixes, and improvements.
One of the changes in this release is improving the Prisma Client for the Data Proxy generation step.
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
- previewFeatures = ["dataProxy"]
}
You can generate Prisma Client for the Data Proxy it by 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.
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.
This release includes a known regression when connecting to Azure SQL from MacOS only and will be resolved soon. Follow this issue for updates and resolution.
migrate reset
returns with a non-0 exit code if the seed script returns with a non-0 exit codeThis will help user scripts know more about the success of the command, but might break existing scripts.
introspect --url
throws error if existing schema file only contains generator
prisma migrate reset
always exits with 0
, needs to exit with 1
on errorsWould you like to create a Github issue? » Yes
does nothing in terminal on Windows患者ID
AirbyteRawYuriPagesAirbyteDataProperties推荐点RichText
db
and migrate
commandsOption::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87upsert
causes: "PANIC: called Option::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87".env
filesOption::unwrap()
on a None
value in query-engine\core\src\query_document\parser.rs:250:87prisma generate
errors with Error: Error: ENOENT: no such file or directory, open '/[...]/prisma/schema.prisma'
when using a custom name for the Prisma schema fileOption::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87Option::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87TypeError: at normalizeAndValidateHeaderValue
with data proxy in cloudflare workers/miniflareOption::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87getConfig
and getDmmf
of Query EngineOption::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87Option::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87Option::unwrap()
on a None
value in query-engine/core/src/query_document/parser.rs:250:87InvalidDatasourceError
of Data Proxy Client outputs a code snippetHuge thanks to @shian15810, @zifeo, @ever0de, @rushabhhere for helping!
Prisma Day is back this year, and it'll be on June 15 - 16 at the James June Sommergarten in Berlin. Join us in-person or online for talks and workshops on modern application development and databases. Come and meet and chat with the team behind the Prisma ORM and Prisma Data Platform.
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 through the job descriptions and apply using the links provided.
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 9 at 5 pm Berlin | 8 am San Francisco.
Published by ruheni over 2 years ago
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
We are proud to announce the CockroachDB connector is now stable and Generally Available. The connector was built in joined efforts with the team at Cockroach Labs and comes with full Prisma Client and Prisma Migrate support.
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.
GIN
, GiST
, SP-GiST
, and BRIN
indexes support (Preview)We introduced the extendedIndexes
Preview feature in version 3.5.0
, and we have been adding new configuration options for indexes. We've expanded index type support with the GIN
, GiST
, SP-GiST
, and BRIN
indexes in this release.
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.
queryRaw
APIIn 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.
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.
You can enable the Preview feature in your Prisma schema as follows:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["improvedQueryRaw"]
}
Here's a list of the improvements improvedQueryRaw
comes with:
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.
⚠️ This change is not yet available in the SQLite connector.
The types of values from the database will be used instead of the types in the Prisma schema. 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>") }]
Here's a table that recaps the serialization type-mapping for raw results:
Database Type | Javascript Type |
---|---|
Text | String |
Int32 | Number |
Float | Number |
Double | Number |
Int64 | BigInt |
Numeric | Decimal |
Bytes | Buffer |
Json | Object |
DateTime | Date |
Date | Date |
Time | Date |
Uuid | String |
Xml | String |
We've also fixed a lot of PostgreSQL type-casts that were broken by enabling the improvedQueryRaw
Preview feature flag.
Here's an example of a 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 more type-casts in your queries:
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 under the improvedQueryRaw
feature flag:
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 coerce 42
to text
silently, but won’t anymore. As suggested by the hint, cast 42
to text
as follows:
await prisma.$queryRaw`SELECT LENGTH(${42}::text);`
This improvement is available without the
improvedQueryRaw
Preview feature flag.
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])}, ${new Prisma.Decimal("12.23")});`
incorrect binary data format in bind parameter 3
$queryRaw
generate
output with output
has weird package path on Windows$
from executeRaw
in error message "Invalid `prisma.executeRaw()` invocation:"Result::unwrap()
on an Err
value: Any { .. } in query-engine/connectors/sql-query-connector/src/error.rs:58:51referentialIntegrity = prisma
: Broken query on onUpdate: Cascade
| symbol ... not found
| The column ... does not exist in the current database.
N/A
. Message: error deserializing column 0: a Postgres value was
NULL``" error when using Postgres ARRAY_AGG with a nullable columndebugPanic
like functionality for getConfig
and getDmmf
of Query EngineResult::unwrap()
on an Err
value: Any { .. } in query-engine/connectors/sql-query-connector/src/error.rs:58:51Result::unwrap()
on an Err
value: Custom { kind: InvalidData, error: "stream did not contain valid UTF-8" } prisma format
panics when you use a colon to declare field type (field: Type
syntax)TEXT
or BLOB
in MySQL @id/@index/@uniqueError parsing attribute "@id"
but it's actually about @@id
Option::unwrap()
on a None
value provider=posgresql
schema--url
for db pull
ignored/overwrites provider=cockroachdb
Huge thanks to @ever0de, @flatplate, @njmaeff, @tnzk, @DePasqualeOrg for helping!
Prisma Day is back this year, and it'll be on June 15 - 16 at the JamesJune Sommergarten in Berlin. Join us in-person or online for talks and workshops on modern application development and databases. Come and meet and chat with the team behind the Prisma ORM and Prisma Data Platform.
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 hiring for a number of roles: Technical Support Engineer, Back-end Engineer: Prisma Data Platform, and a Developer Advocate(Frontend/ Fullstack). You can find more jobs we're hiring for on our jobs page.
Feel free to read through the job descriptions and apply using the links provided.
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, May 12 at 5 pm Berlin | 8 am San Francisco.
Published by ruheni over 2 years ago
Today, we are excited to share the 3.13.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
migrate diff
and db execute
are now Generally Available!We released two new Preview CLI commands in version 3.9.0
– prisma migrate diff
and prisma db execute
– to enable our users to create and understand migrations and build their workflows using the commands.
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
command creates a diff of your database schema, Prisma schema file, or the migration history. All you have to do is feed the command with a schema from
state and a schema to
state to get an SQL script or human-readable diff.
In addition to prisma migrate diff
, prisma db execute
is used to execute SQL scripts against a database. You can directly execute prisma migrate diff
's output using prisma db execute --stdin
.
Both commands are non-interactive, so it's possible to build many new workflows such as forward and backward migrations with some automation tooling. Take a look at our documentation to learn some of the popular workflows these commands unlock:
migrate diff
and db execute
Let us know what tools, automation, and scripts you build using these commands.
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.
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.
We're excited to announce that version 3.13.0
now supports OpenSSL 3.0. Operating systems such as Ubuntu 22.04 default to OpenSSL 3.0, and when running prisma generate
, you would run into the following error:
Error: Unknown binaryTarget debian-openssl-3.0.x
If you've run into a similar error, bump up to the latest Prisma version and give it another try!
prisma init
needs CockroachDB in the providers listDROP DATABASE "test-doesnotexists;"
says that Database postgres.public does not exist
migrate diff
just crashed. prisma init --datasource-provider=cockroachdb --url ...
sets provider to postgresql
--preview-feature
flag for Primitives (migrate diff
and db execute
)Huge thanks to @ever0de, @jacobhq, @dkantereivin, @CommanderRoot for helping!
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 Senior Software Engineer (Prisma Data Platform).
Feel free to read through the job descriptions and apply using the links provided.
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, April 28 at 5 pm Berlin | 8 am San Francisco.
Published by ruheni over 2 years ago
Today, we are excited to share the 3.12.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
If you’ve been using MongoDB since it was in Preview, we'd like to say: Thank you! Your testing and feedback has been essential during the preview phase, and our MongoDB support is much better because of it.
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"]
}
We’ve been working hard towards this day ever since we launched MongoDB in Preview in July 2021.
Here are some of the feature highlights we developed over this period:
db push
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 you check 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:
We made some changes in the 3.11.1
patch release in case you missed it.
We also added support for adding indexes on embedded document fields in MongoDB. This means that 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 the feature for now. This will be rolled out in a future release.
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 a lot of head-scratching, we were finally able to 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.
new PrismaClient()
can not find schema.prisma
file when use with pnpm workspaceInconsistent column data: Malformed ObjectID
by including the field(s) in the message Inconsistent column data: Failed to convert ...
error on invalid data in properties does not mention affected field (and other useful information)QueryEvent
type params
is undefined
Option::unwrap()
on a None
value Option::unwrap()
on a None
value prisma db push
on MongoDB with @unique
idOption::unwrap()
on a None
value Option::unwrap()
on a None
value migrate diff
correctly resolve relative SQLite file path from schema? Int32
=> Int
)prisma-fmt
panic when @db.Array()
is added in a MongoDB schemareferences
Array()
is still auto suggestedupdateMany
write operationdeleteMany
write operationHuge thanks to @ever0de, @chronotc, @hayes, @maddhruv, @jasimon, @codesee-maps[bot], @andyrichardson, @xnerhu, @Josh-a-e, @dusandz for helping!
If you're interested in joining our growing team to help empower developers build data-intensive applications, Prisma is the place for you.
We're looking for a Developer Success Engineer and Back-end Engineer: Prisma Data Platform.
Feel free to read through the job descriptions and apply using the links provided.
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, April 7 at 5 pm Berlin | 8 am San Francisco.
Published by dpetrick over 2 years ago
Today, we are issuing the 3.11.1
patch release.
undefined
fields by defaultIn 3.11.1
, 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.
There are a few exceptions to this new default:
having
filter on an aggregated field will return undefined
fields. This is because aggregation on undefined fields yields null
, not undefined
, thus matching the filter.undefined
) will currently include those relations in the result set.isSet
filter operationTo 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.
unset
operationIn 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.
updateMany
operationWe 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',
},
},
},
},
})
deleteMany
operationSimilar 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,
},
},
},
},
})
Published by Jolg42 over 2 years ago
Today, we are excited to share the 3.11.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
In the previous release, we added embedded document support for creates, updates, and deletes. In version 3.11.0
, we’re adding the ability to filter embedded documents.
Given the following schema:
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
photos Photo[]
}
model Order {
id String @id @default(auto()) @map("_id") @db.ObjectId
shippingAddress Address
billingAddress Address?
}
type Photo {
height Int
width Int
url String
}
type Address {
street String
city String
zip String
}
You can now filter within an embedded document:
// find all orders with the same shipping address
const orders = await prisma.order.findMany({
where: {
shippingAddress: {
equals: {
street: "555 Candy Cane Lane",
city: "Wonderland",
zip: "52337",
},
},
},
})
You can also 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.
In addition to filtering, Prisma version 3.11.0
now supports sorting 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.
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))
After enabling query logging, you'll start to see logs that resemble this in your console:
db.User.deleteMany({ _id: ( $in: [ “62261e0b18139c6099ba7097”, ], }, })
db.User.deleteMany({ _id: ( $in: [ “6226277a96069500743edcf9”, ], }, })
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.
We've updated the type inference behavior for MongoDB on introspection.
Prisma samples a field's data to select an appropriate type on introspection. 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 throw 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 instead. Additionally, Prisma will still show a warning on the console and add a comment to the introspected Prisma schema so it is clear where such cases occur and that you can do something to fix them.
In 3.11.0
, we’ve rewritten our internal logger to reduce lock contention and enable future features like tracing. This is the first of many upcoming changes to improve the Prisma Client’s throughput, so if you were running into an upper limit on query performance, it’s time to update Prisma Client and give it a try!
If you're running into query performance issues, please open an issue or connect with us on Slack.
We're excited to announce Preview support for migrations for CockroachDB. You can now evolve your Prisma schema and propagate the changes to your database using Prisma Migrate.
Give the feature a try and let us know what you think in this issue.
migrate diff
using exit codePrisma version 3.11.0
includes a new --exit-code
flag to the migrate diff
command to detect the state of a diff in several ways.
You can use the flag as follows:
npx prisma migrate diff --preview-feature \
--exit-code \
--from-[...] \
--to-[...]
Here's a list of the default and changed behavior of the error codes:
## Default behavior of exit codes
0: Returned when the diff is empty or non-empty
1: Returned on error
## Changed behavior when --exit-code is used
0: Returned when the diff is empty
1: Returned on error
2: Returned when the diff is non-empty
Read about it in the reference documentation.
db push
with empty schema.prisma
: Error: TypeError: Cannot read properties of undefined (reading 'url')
db execute
cannot resolve SQLite file path from schemaPANIC: called Option::unwrap() on a None
Option::unwrap()
on a None
valuetlsCAFile
failsOption::unwrap()
on a None
value in query-engine/connectors/mongodb-query-connector/src/root_queries/write.rs:301:74contains
string filter not working with mongoDBOption::unwrap()
on a None
value in query-engine\connectors\mongodb-query-connector\src\root_queries\read.rs:112:74@map
panics on 3.10.0'then' in PrimsaPromise
returns falsemap
does not exist for M:N in MongoDBequals
read operationis
read operationisNot
read operationisEmpty
read operationevery
read operationsome
read operationnone
read operationHuge thanks to @hayes, @maddhruv, @jasimon for helping!
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, March 17 at 5 pm Berlin | 8 am San Francisco.
Published by ruheni over 2 years ago
Today, we are excited to share the 3.10.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
We are working towards a stable release of MongoDB and are shipping lots of improvements. All the new features and 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.
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",
// Create an embedded list of photos in the product
photos: [
{ height: 100, width: 200, url: "1.jpg" },
{ height: 300, width: 400, url: "2.jpg" },
],
},
})
Best of all, the query is entirely type-safe! This scratches the surface of what's possible with embedded documents. You can read further in our documentation.
If you run into anything, feel free to open an issue, and we’ll give you a hand!
We added Preview support for Introspection of 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 how we handle the default values in MongoDB:
model Post {
- id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
+ id String @id @default(auto()) @map("_id") @db.ObjectId
}
references
argumentPrisma 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])
+ 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])
+ posts Post[] @relation(fields: [post_ids], references: [id])
}
@db.Array(ObjectId)
is now updated to @db.ObjectId
We've adjusted the Prisma schema format for scalar lists with native types (like lists of Object IDs). This will likely affect those with many-to-many relationships in MongoDB. We made this change to align MongoDB with our existing SQL databases better:
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
- categoryIDs String[] @db.Array(ObjectId)
+ categoryIDs String[] @db.ObjectId
categories Category[] @relation(fields: [categoryIDs], references: [id])
}
model Category {
id String @id @default(auto()) @map("_id") @db.ObjectId
- postIDs String[] @db.Array(ObjectId)
+ postIDs String[] @db.ObjectId
posts Post[] @relation(fields: [postIDs], references: [id])
}
@db.ObjectId
isn't presentdatasource
blocksprisma init --url
does not like mongodb+srv://
Code 19
and unformatted list output during Re-Introspectionid_
special caseUnsupported("Unknown")
causes schema validation to crash@db.Array(ObjectId)
to @db.ObjectId
Unsupported(...)
fields are not rejected on composite types@default(autoincrement())
Option::unwrap()
on a None
value _id
of type ObjectId
are introspected without native type @db.ObjectId
@default(dbgenerated())
with @default(auto())
prisma db pull
doesn't read .env
file and errors with Environment variable not found: DATABASE_URLModel "undefined", field: ...
Multiple data types found: Array(Array(Array(Double))): 86.2%, Array(Array(Array(Array(Double)))): 13.8% out of 195 sampled entries
InteractiveTransaction
: Middleware param runInTransaction
set to false
.count
does not work with whereinteractiveTransactions
feature breaks long running transactionsa_ids String[] @db.ObjectId
3.9.1
prisma
as driverInfo
to MongoDBHuge thanks to @andyrichardson, @xnerhu, @Josh-a-e, @dusandz, @hyochan, @cesconix, @benkroeger, @YassinEldeeb, @chenkie for helping!
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, February 03 at 5 pm Berlin | 8 am San Francisco.
Published by millsp over 2 years ago
Today, we are issuing the 3.9.2
patch release.
Published by Jolg42 over 2 years ago
Today, we are issuing the 3.9.1
patch release.
Published by Jolg42 over 2 years ago
Today, we are excited to share the 3.9.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
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
prisma db execute
The prisma migrate diff
command creates a diff of your database schema, Prisma schema file, or the migration history. All you would have to do is feed the command with a schema from
state and a schema to
state to get an SQL script or human-readable diff in return.
As a companion to the prisma migrate diff
, we also built prisma db execute
to execute SQL scripts against a database. You can pipe the output from prisma migrate diff
directly to prisma db execute
.
Both commands are non-interactive, so it's possible to build many new workflows such as forward and backward migrations with some automation tooling.
Both commands are in Preview, and we are 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.
We are excited to announce Preview support for CockroachDB 🎉
CockroachDB is a distributed SQL database that shines in its ability to scale efficiently while maintaining developer agility and reducing operational overhead.
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.
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,
})
The raw query API for MongoDB differs from Prisma's $queryRaw
SQL API to handle some low-level differences between databases to give you a better API and developer experience.
Learn more about Prisma's new raw query API and how you can use it in our documentation.
In 3.9.0
, we fixed a number of issues around timeouts and rollbacks when there were concurrent reads and writes.
This is part of the Interactive Transactions preview release, so you'll need to enable the interactiveTransactions
preview feature to enable this feature.
If you experienced timeouts or your interactive transactions weren't working quite as you expected, now's the time to upgrade and give it another go!
Learn more about Interactive Transactions in our documentation.
DMMF.Field.type
fieldcockroachdb
provider and preview feature flagHuge thanks to @dusandz, @hyochan, @cesconix, @benkroeger, @YassinEldeeb, @chenkie, @Akxe, @safareli for helping!
We're making a slight change to our release cadence to every 3 weeks from every 2 weeks.
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, February 03 at 5 pm Berlin | 8 am San Francisco.
Published by millsp almost 3 years ago
Today, we are issuing the 3.8.1
patch release.
Published by Jolg42 almost 3 years ago
Today, we are excited to share the 3.8.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
We're back from the holidays with a special treat for you.
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()
indexes 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
Preview Features are now mutually exclusiveBefore Prisma 3.8.0
, Prisma $transaction
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.
push
when adding an element to an array in MongoDBIn 3.8.0
, we 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("...")
}
}
})
A special thanks to Anthony Luzquiños for raising this issue!
generator.engineType
is not validatedname
validationspreviewFeatures = []
gets lost after Introspectionmigrate dev
fails on second run with specific schematype
support to the Query EngineError querying the database: db error: ERROR: unsupported startup parameter: options
@prisma/client
intermittently added and removed from transitivePeerDependencies
in lockfiletabSize
configuration when indenting blocksBigInt
breaks studioHuge thanks to @hyochan, @cesconix for helping!
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, January 13 at 5 pm Berlin | 8 am San Francisco.
Published by Jolg42 almost 3 years ago
Today, we are excited to share the 3.7.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
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)
- author User @relation(fields: [userId], references: [id])
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.
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!
type
in Prisma SchemaWith Prisma 3.7.0
release, the Prisma 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.
An example of that is string aliasing:
type MyId = String @id @default(dbgenerated(new_uuid()))
model A {
id MyId
}
We plan to remove that functionality entirely with the next major release of Prisma. If you happen to depend on similar functionality for type aliasing, please leave a comment on the issue.
BigInt
fields are also resolved.@@fulltext(fields:[])
or @@fulltext([])
or @@index([])
or @@unique([])
.Huge thanks to @otan, @benkroeger, @YassinEldeeb, @chenkie for helping!
Learn about the latest release and other news from the Prisma community by joining us for another "What's new in Prisma Holiday Special" livestream.
The stream takes place on YouTube on Tuesday, December 21 at 5 pm Berlin | 8 am San Francisco.
Published by Jolg42 almost 3 years ago
Today, we are excited to share the 3.6.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
In this version we introduce support for full-text indexes in the db pull
, db push
and migrate
commands for MySQL and MongoDB databases as a Preview feature. This allows using them in the Prisma schema and prevents validation errors in some database schemas.
For now we do not enable the full-text search commands in the Prisma Client. They will be implemented separately, and the progress can be followed 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])
}
Please note that 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 check out our documentation.
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.
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 check out our documentation.
Until this release, the language server powering the Prisma VS Code extension relied on logic from the Prisma engines in the form of a native binary. Downloading and running the native binary required a large amount of custom logic and led to problems due to network failures, operating system permissions and malicious code detection issues.
Starting with 3.6.0
, the language server and the VS Code extension use logic compiled to WebAssembly and distributed through npm. There is no runtime binary download and no external process involved anymore. We expect this new distribution model to be more robust and hence provide a better experience for our users.
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
}
}
})
Thanks @serejkaaa512 for your contribution!
Json
fields now accept read-only typesThis is a small quality-of-life improvement. 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.
If you've spent some time using the new Interactive Transaction API with the binary engine, you may have encountered this timeout error:
Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'.
This could happen if you had two concurrent requests modifying the same resource at the same time using the binary engine type.
It took us a while to track down the source of this error, but it turned out to be a low-level misconfiguration in our HTTP client. We disabled HTTP pipelining to fix this problem.
notIn
filters for large queriesThis most likely didn't affect you, but if you ever tried using notIn
with a large query, you may have received an incorrect result.
The query engine automatically breaks up large queries into smaller queries and intersects the results. Most of the time this works as expected but for certain queries like notIn
, the intersection of results is incorrect.
We fixed this in 3.6.0
. You can now use in
and notIn
operations on the Bytes
type:
const denyList = [/* ... large list of user ids ... */]
const result = await prisma.user.findMany({
where: {
id: {
notIn: denyList
}
}
})
This query will break up the query into chunks that your database can manage:
select * where User not in ($1,$2, ..., $5000)
select * where User not in ($1000,$1001, ..., $6000)
... and return the correct results. Learn more in this issue.
in
natively for bytesThe provided database string is invalid. Invalid MongoDB connection string in database URL.
insteadprisma migrate dev
with timeout but works with prisma db seed
dbgenerated
migrations in MySQL are broken (since 3.4.x)Huge thanks to @Akxe, @safareli for helping!
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, December 02 at 5pm Berlin | 8am San Francisco.