Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
APACHE-2.0 License
Bot releases are hidden (Show)
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.24.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
Json
and Enum
SupportWe just added Json
and enum
support to the MongoDB provider
for Prisma Client. Here's an example with both:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongodb"]
}
model Log {
id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
message String
level Level @default(Info)
meta Json
}
enum Level {
Info
Warn
Error
}
You can then use the generated client like this:
await prisma.log.create({
data: {
level: "info",
message: "User signed in",
meta: { user_id: 1 },
},
})
As a reminder, the mongodb
provider is still in Early Access. If you'd like to use MongoDB with Prisma, please fill out this 2-minute Typeform and we'll get you an invite to our Getting Started Guide and private Slack channel right away!
The Prisma Data Platform (PDP) helps developers collaborate better in projects that are using the open-source tools. One of its main features today is an online data browser.
You can now view your project's schema in order to better understand your application or collaborate with your colleagues. The only roles that can view it are: Admin and Developer
You can now delete your project from your settings.
You can also edit your Project's URL, so you can now correct any mistakes you might have made while creating your project.
If your database is behind a proxy and you need a static IP to allowlist in order to give access to it, you can now get in touch with us by creating an issue or sending an email at [email protected]
and we'll enable it for you.
Please note that while this feature is freely available now, it will be offered as part of a paid plan in the future (towards the end of '21 or beginning of '22).
Result::unwrap()
on an Err
value: FieldNotFound { name: "_count", model: "Post" }Huge thanks to @Sytten 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 3rd at 5pm Berlin | 8am San Francisco.
Save the date for Prisma Day 2021 and join us for two days of talks and workshops by the most exciting members of the Prisma community.
We look forward to seeing you there!
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.23.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
Starting today, you can now filter rows by data inside a Json
type. JSON filtering support is available in PostgreSQL and MySQL. You can try it today by adding the filterJson
preview flag to your generator
block. This has been one of our most popular feature requests, so we're very excited to be getting it into your hands!
To get an idea of how JSON filtering works, let's see how you might query application logs stored in your database. Given the following Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["filterJson"]
}
model Log {
id Int @id @default(autoincrement())
level Level
message String
meta Json
}
enum Level {
INFO
WARN
ERROR
}
And the following records in your PostgreSQL database:
id | level | message | meta |
---|---|---|---|
2 | INFO |
application listening on port 3000 | {"host": "bob"} |
3 | INFO |
upgrading account | {"host": "alice", "request_id": 10} |
4 | INFO |
charging customer | {"host": "alice", "amount": 20, "request_id": 10} |
5 | ERROR |
credit card expired | {"host": "alice", "amount": 20, "request_id": 10} |
6 | INFO |
signing up | {"host": "bob", "request_id": 1} |
7 | INFO |
application listening on port 3000 | {"host": "alice"} |
8 | INFO |
signed up | {"host": "bob", "email": "[email protected]", "request_id": 1} |
We can now filter logs by the data inside the meta
field. Let's query by the request_id
inside the meta
field to track the journey that led up to the error.
We can write the following query:
const logs = await prisma.log.findMany({
where: {
meta: {
// path looks for the request_id key inside meta
path: ["request_id"],
// and we select rows whose request_id is 10
equals: 10,
},
},
orderBy: {
id: "asc",
},
});
Giving us the entire journey of this person's request:
[
{
id: 3,
level: 'INFO',
message: 'upgrading account',
meta: { host: 'alice', request_id: 10 }
},
{
id: 4,
level: 'INFO',
message: 'charging customer',
meta: { host: 'alice', amount: 20, request_id: 10 }
},
{
id: 5,
level: 'ERROR',
message: 'credit card expired',
meta: { host: 'alice', amount: 20, request_id: 10 }
}
]
Please note that the path
syntax varies depending on the database. We pass the path
query directly to the database, so there will be syntactical differences.
For example, querying by key in Postgres is request_id
, while in MySQL it would be $.request_id
. Please consult your database's documentation to learn more.
If you run into any questions or have any feedback, we're available in this issue.
📚 Documentation: Working with Json fields
prisma db seed
In previous versions, a seed file could only be executed as a script. prisma db seed
was simply executing the script by either calling node ./prisma/seed.js
for JavaScript or ts-node ./prisma/seed.ts
for TypeScript.
Now, you can directly export a function that Prisma executes on your behalf. Here's the rules that describe the new behavior: Prisma checks if the seed file has ...
seed
and executes itIf there's no function exported as seed
or via a default export, the behaviour of prisma db seed
is exactly the same as before, meaning it will simply be executed as a script file.
groupBy
queries are now prefixed with an underscoreThe options in groupBy
are now prefixed with an underscore, for example:
// API
const result = await prisma.user.groupBy({
by: ['name'],
- count: true,
+ _count: true,
})
Here's an overview of the exact changes of each option:
Before 2.23.0
|
2.23.0 and later |
---|---|
count |
_count |
max |
_max |
min |
_min |
avg |
_avg |
sum |
_sum |
Note that this also changes the names of the fields in the objects that are returned by Prisma Client. For example, in the above case you now access the returned count value like so:
- console.log(result.count)
+ console.log(result._count)
We made this change to avoid clashes with user-defined fields. You can learn more about the problem in these issues.
We're sorry for the inconvenience! If you have any questions or need any help, please reach out in this discussion.
aggregate
queriesWith the changes to groupBy
discussed above and recent features like orderBy an aggregate, we took this opportunity to unify min
, max
, avg
, sum
and count
keywords across Prisma Client queries.
const result = await prisma.user.aggregate({
- avg: {
+ _avg: {
age: true,
},
})
- result.avg
+ result._avg
Similar to groupBy
, this is the case for all of our aggregations:
Before 2.23.0
|
2.23.0 and later |
---|---|
count |
_count |
max |
_max |
min |
_min |
avg |
_avg |
sum |
_sum |
This is not a breaking change. The aggregate queries you wrote prior to 2.23.0
will continue to work as expected. We ask that you make adjustments when you can to future-proof your application.
If you have any questions or need any help, please reach out in this discussion.
dbgenerated("gen_random_uuid()::TEXT")
Option::unwrap()
on a None
value Error: Invalid data source URL, see https://www.prisma.io/docs/reference/database-reference/connection-urls
in 2.22.0Huge thanks to @Sytten, @schiller-manuel, @mongolyy, @paularah, @Iamshankhadeep, @meeq 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, May 20 at 5pm Berlin | 8am San Francisco.
Save the date for Prisma Day 2021 and join us for two days of talks and workshops by the most exciting members of the Prisma community.
We look forward to seeing you there!
Published by Jolg42 over 3 years ago
Today, we are issuing the 2.22.1
patch release.
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.22.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
prisma db push
is now Generally Availableprisma db push
enables you to update the database schema from the Prisma schema file, without generating any migrations.
This is especially useful when prototyping a new feature, iterating on the schema changes before creating migrations or generally if you are at stage of your development process, where you don't need to persist the schema change history via database migrations.
It is now promoted from Preview to General Availabilty.
You can find more info on prisma db push
in the official docs.
provider
fieldsIn this release, we are also entirely removing the array notation for the provider
fields on datasource
blocks. This has been deprecated since 2.11.0 (November 2020).
You can read more about our reasons for this deprecation here.
AND
operatorWe've always had OR
, but this release we also added AND
support:
first, err := client.User.FindFirst(
User.Or(
User.Email.Equals("[email protected]"),
User.And(
User.Name.Equals("John"),
User.Username.Equals("johno"),
),
),
).Exec(ctx)
Learn more in our docs.
provider
as known error that does not trigger Error ReportingOption::unwrap()
on a None
valueprisma migrate deploy
autoincrement()
default value is used on a non-indexed field even though the datasource does not support this."migrate dev
with shadow database errors with "Database already exists FK__Address__userId" when migration fails because of existing foreign keyHuge thanks to @Sytten, @schiller-manuel, @mongolyy, @paularah, @Iamshankhadeep, @meeq 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, May 06 at 5pm Berlin | 8am San Francisco.
Published by Jolg42 over 3 years ago
Today, we are issuing the 2.21.2
patch release.
Published by Jolg42 over 3 years ago
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.21.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo ☝️ or tweeting about the release.
Whew, that's a tongue-twister for a neat feature.
Let's say you want to group your users by the city they live in and then order the results by the cities with the most users. In 2.21.0
, now you can!
const userRatingsCount = await prisma.user.groupBy({
by: ['city'],
count: {
city: true,
},
orderBy: {
_count: {
city: 'desc',
},
},
})
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
city String
}
The query returns the following:
[
{ city: 'Berlin', count: { city: 3 } },
{ city: 'Paris', count: { city: 2 } },
{ city: 'Amsterdam', count: { city: 1 } },
]
Enable this feature with the orderByAggregateGroup
preview flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["orderByAggregateGroup"]
}
📚 Documentation: Order by aggregate group
Before 2.21.0
, aggregations on nullable fields always returned 0, even when there was no record or if all aggregated records were nulls. Returning 0 for null values made it impossible to differentiate between these two different results.
We are changing aggregates to follow what the database returns:
For example, previously, if there's no record in the database or if all records are nulls, the following aggregation:
const result = await prisma.post.aggregate({
sum: { amount: true },
})
Results in:
{
sum: {
amount: 0
}
}
The result.sum
type is currently of type { amount: number }
.
Starting this release, the same query returns:
{
sum: {
amount: null
}
}
And result.sum
is of type { amount: number | null }
📚 Documentation: Aggregates are nullable
disconnect
no longer throws an error on unconnected recordsPrior to 2.21.0
, if you ran the following code:
const user = await prisma.user.update({
where: { email: '[email protected]' },
data: {
profile: {
disconnect: true,
},
},
})
And no profile was connected to Bob, the client would throw with this error:
The records for relation `UserToProfile` between the `User` and `Profile` models are not connected.
We learned from you that handling this added unnecessary boilerplate to your applications. As of 2.21.0
, we've removed this error. Now, if you try disconnecting an unconnected record, the operation does nothing and passes through.
This change is unlikely to affect you unless you explicitly handle the disconnect
error. In that case, adjust your code because the command no longer throws an error.
📚 Documentation: $disconnect()
@default(dbgenerated(""))
is no longer permittedThe dbgenerated()
function allows you to define default values generated directly by the database and cannot yet be represented in the Prisma schema.
Previously, you could pass an empty string, i.e., @default(dbgenerated(""))
, which would fail since the contents are added into the migration SQL as columnName COLUMN_TYPE DEFAULT <contents of dbgenerated>
As of 2.21.0
, if a value is present, it cannot be an empty string.
If you want an empty string default, the correct syntax is @default(dbgenerated("''")
(or other quotation marks, depending on the database provider).
📚 Documentation: dbgenerated()
count
throws an error if include
is specified12.22.0
DROP COLUMN ..., ADD COLUMN ...
sequence of SQL statements. These silently drop the indexes present on the column, and migrate would only re-create them with the next migration. With this release, the issue has been fixed, and Migrate recreates the index in the same migration.This line is invalid. It does not start with any known Prisma schema keyword.
in introspection for an invalid schema.db push
crashes when used on specific Postgres connection string with non existing databaseWe worked on shipping some minor improvements and bug fixes:
Huge thanks to @Sytten, @endor, @iBluemind, @schiller-manuel, @mongolyy, @matthewmueller, @paularah, @Iamshankhadeep, @meeq, @safinsingh, @darioielardi 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, April 15 at 5pm Berlin | 8am San Francisco.
Published by Jolg42 over 3 years ago
Today, we are issuing the 2.20.1
patch release.
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.20.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
This highly requested feature is now in Preview. You can now count the number of related records by passing _count
to the select
or include
options and then specifying which relation counts should be included in the resulting objects via another select
.
For example, counting the number of posts that an user has written:
const users = await prisma.user.findMany({
include: {
_count: {
select: { posts: true },
},
},
})
The structure of the returned User
objects is as follows:
{
id: 1,
email: '[email protected]',
name: 'Alice',
_count: { posts: 2 }
}
You can enable this featrues with the selectRelationCount
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["selectRelationCount"]
}
There may be some rough edges during the Preview period. If you run into any problems, you can reach us in this issue.
Node-API
is now in PreviewNode-API is a new technique for binding Prisma's Rust-based query engine directly to Prisma Client. This reduces the communication overhead between the Node.js and Rust layers when resolving Prisma Client's database queries.
You can enable this feature with the napi
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["napi"]
}
Enabling the Node-API will not affect your workflows in any way, the experience of using Prisma will remain exactly the same.
The Node-API has different runtime characteristics than the current communication layer between Node.js and Rust.
There may be some rough edges during the Preview period. If you run into any problems, you can reach us in this issue.
push
operation available for arrays on PostgreSQLPostgreSQL supports array data structures (sometimes also called scalar lists). As an example, consider the permissions
field on the following User
model:
model User {
id Int @id @default(autoincrement())
permissions String[]
}
As of this release, you can append a new item to existing lists atomically with the push
command:
await prisma.user.update({
where: { id: 42 },
data: {
permission: {
push: "chat:read",
},
},
})
Learn more in this issue.
groupBy
and createMany
are now Generally AvailableFor the pioneers among you, you can now remove the groupBy
and createMany
from your Preview features:
generator client {
provider = "prisma-client-js"
- previewFeatures = ["groupBy", "createMany"]
}
Learn more in our documentation about groupBy
and createMany
.
BigInt
, Decimal
and Bytes
Prisma Client Go continues to get more powerful every release. With this release, we've added support for more native database types: BigInt
, Decimal
and Bytes
:
var views db.BigInt = 1
bytes := []byte("abc")
dec := decimal.NewFromFloat(1.23456789)
created, err := client.User.CreateOne(
db.User.Picture.Set(bytes),
db.User.Balance.Set(dec),
db.User.Views.Set(views),
).Exec(ctx)
@prisma/cli
package has reached its end of lifeFor all you holdovers, you've seen warnings like this for a couple months now:
warn @prisma/cli has been renamed to prisma.
Please uninstall @prisma/cli: npm remove @prisma/cli
And install prisma: npm i prisma
It's now time to upgrade. Follow the instructions and switch over to the new prisma
package today:
npm remove @prisma/cli
npm install -D prisma
Thanks to this change, running npx prisma
will now always invoke the right Prisma CLI, no matter what your local setup looks like.
yarn remove @prisma/cli
yarn add -D prisma
.aggregate
will change to return null
in 2.21.0Subscribe to this issue for updates on how to prepare your code.
Schema is inconsistent
error messageprisma format
cli commandprisma migrate
set field as unique automaticallypush
method to scalar list update input in addition to setResult::unwrap()
on an Err
value: FieldNotFound { name: "origin", model: "Field not found in record Record { values: [Int(1011), String("https://woman.mynavi.jp/article/190924-7/")], parent_id: None }. Field names are: ["id", "link"], looking for: "origin"" }SKIP_GENERATE
from Client postinstall script to PRISMA_SKIP_POSTINSTALL_GENERATE
We fixed two security issues:
Big thanks to @erik-krogh (Erik Krogh Kristensen) and @Ry0taK for reporting these issues.
Huge thanks to @endor, @iBluemind, @matthewmueller, @paularah, @Iamshankhadeep 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, April 01 at 5pm Berlin | 8am San Francisco.
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.19.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
We are excited to announce that Prisma Migrate enters General Availability. You can learn more about the launch in the announcement article.
There are no major changes to how Prisma Migrate works except that the --preview-feature
flag is being removed:
Before v2.19.0
npx prisma migrate <COMMAND> --preview-feature
# for example:
npx prisma migrate dev --preview-feature
Now
npx prisma migrate <COMMAND>
# for example:
npx prisma migrate dev
Besides making Prisma Migrate ready for production in this release, it comes with a number of smaller fixes and improvements:
migrate dev
, migrate reset
and db push
, generation is always triggered to avoid issues where the Prisma Client API is outdated due to changes in relation names which have an impact on the database schema (GitHub issue)migrate dev
produces warnings (GitHub issue)uuid()
📚 Documentation:
This release makes it possible to order by the aggregates (e.g. count) of relations in your Prisma Client queries. Here's is an example that orders a list of users by the number of the posts they created:
const orderedUsers = await prisma.user.findMany({
orderBy: {
posts: {
count: 'asc'
}
}
})
This feature is released in Preview which means you have to explicitly enable it via the orderByRelation
feature flag in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["orderByRelation"]
}
Don't forget to run npx prisma generate
after you've added the feature flag to your Prisma schema so that the Prisma Client API gets updated accordingly.
Transaction
APIPreviously in the Go Client, you could write data within a transaction, but you couldn't get the results back from the transaction. Now you can! Learn more in the documentation.
npx prisma generate
with custom engine binariespool_timeout
value hides connect timeoutsOption::unwrap()
on a None
value prisma migrate dev
migrate dev
prompts for migration name when running after --create-onlyintrospect
when env var contains wrong connection string protocolString
field to Enum
in a migration - PostgresResult::unwrap()
on an Err
value: TypeMismatchError { expected_type: "constant literal", received_type: "string", raw: "tenantId", span: Span { start: 6221, end: 6231 } } db push
and migrate dev
even if the changes result in no database schema changesmigrate dev
Huge thanks to @endor, @iBluemind, @meeq for their help in this release! ✨
We hope you join us for the upcoming Prisma Enterprise Event on Thursday, March 25th which is centered around the following topics:
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 18 at 5pm Berlin | 8am San Francisco.
Published by Jolg42 over 3 years ago
Today, we are excited to share the 2.18.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
prisma introspect
is becoming prisma db pull
In 2.10.0
we introduced the prisma db push
command that enables developers to update their database schema from a Prisma schema file without using migrations.
For the "opposite" motion (i.e., updating the Prisma schema from an existing database schema), we currently have the prisma introspect
command. In this release, prisma introspect
is being renamed to prisma db pull
. However, the prisma introspect
command will be kept around for a few more releases so that you have enough time to switch over to the new command.
Here is how we are planning to execute the renaming:
prisma db pull
, which behaves exactly the same as prisma introspect
.prisma introspect
CLI command.prisma introspect
will be removed.There is no specific timeline to execute on this deprecation and we want to make sure we give developers a generous period of time to switch over.
Prisma has a set of rules for defining relations between models in the Prisma schema.
The prisma format
command automatically helps to apply these rules by inserting missing pieces. As an example, consider this data model with an invalid relation:
model User {
id String @id
name String?
posts Post[]
}
model Post {
id String @id
authorId String?
author User? // not valid because the `@relation` attribute is missing
}
This example is not valid because the @relation
attribute is missing. Running npx prisma format
, automatically inserts the missing attribute:
model User {
id String @id
name String?
posts Post[]
}
model Post {
id String @id
authorId String?
+ author User? @relation(fields: [authorId], references: [id])
}
In previous releases, this expansion logic was applied automatically in several scenarios without running the formatter (by running npx prisma format
explicitly, or formatting via VS code), e.g. when running prisma migrate
. While helpful in some scenarios, these "magic" insertions often resulted in others errors that were harder to interpret and to debug for developers and ourselves.
In this release, the "magical" instertions are removed and developers need to explicitly run npx prisma format
if they want still make use of them.
The ts-node
command options can now be customized via package.json
to pass specific options to ts-node
. This makes prisma db seed
work with tools that have specific requirements when used with TypeScript, such as Next.js.
Here is an example that works with Next.js:
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"ts-node": "ts-node --compiler-options '{\"module\":\"CommonJS\"}'"
},
"devDependencies": {
"@types/node": "^14.14.21",
"ts-node": "^9.1.1",
"typescript": "^4.1.3"
}
}
Prisma Client Go now supports upsert operations:
post, _ := client.Post.UpsertOne(
// query
Post.ID.Equals("upsert"),
).Create(
// set these fields if document doesn't exist already
Post.Title.Set("title"),
Post.Views.Set(0),
Post.ID.Set("upsert"),
).Update(
// update these fields if document already exists
Post.Title.Set("new-title"),
Post.Views.Increment(1),
).Exec(ctx)
Learn more in the documentation and share your feedback in the #prisma-client-go
channel on Slack.
WHERE
clause with 1=0 as conditionERROR: zero-length delimited identifier at or near """"
Couldn\'t parse default value
ShadowDatabaseUrl
to use Prisma Migrate in the cloud, a valid URL is always enforced across every environment, even though it's only needed in development.prisma db pull
command for introspectionDateTime
field to null
We want to ensure our release notes are as helpful as possible for you! You can help us achieve this by taking part in the poll in this GitHub issue.
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 04 at 5pm Berlin | 8am San Francisco.
Published by timsuchanek over 3 years ago
Today, we are excited to share the 2.17.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
prisma db push
prisma db seed
now supports custom schema locationsNote that this release comes with some breaking changes. Read the Breaking changes section below to learn more.
The nativeTypes
preview feature flag has first been introduced in 2.10.0
. Thanks to your continuous and awesome feedback for this feature, we're now able to release usage of native database types in the Prisma schema for General Availability 🎉
Note that this release comes with a few minor breaking changes compared to previous versions. Please read about the Breaking Changes below.
If you haven't followed previous releases, expand below to learn more about everything that's now possible with the new native types.
Each Prisma type can now map to one of multiple native database types. Native database type attributes are:
@db.Boolean
for Boolean
whereas MySQL uses @db.TinyInt
VarChar
or Text
)@db
, where db
is the name of the datasource
block in your Prisma schemaType attributes give you:
String
can be @db.VarChar(200)
or @db.Char(50)
String
is varchar(200)
or just text
.To learn more about all the possible native type attributes, check out the type mapping reference in the docs.
Column types which are not (yet?) supported by Prisma Migrate can be used with Prisma Migrate and introspection through the Prisma type Unsupported
which was introduced in Preview in the last release:
model User {
id Int @id @default(autoincrement())
email String @unique
name String? @default("")
multilinestringField Unsupported("multilinestring") @unique
}
dbgenerated()
in the @default
directive can now take a String argument that enables developers to reflect database-level DEFAULT
constraints not yet supported by Prisma Migrate. These default values will be surfaced when introspecting with prisma introspect
and created/changed when using Prisma Migrate.
Developers can now add @@ignore
and @ignore
attributes to models and fields, for fields they want to manage via Prisma Migrate but not surfaced in Prisma Client. These attributes are added by Prisma when introspecting entities which are not supported, e.g. a table with no unique column. They are now also kept in the Prisma schema when re-introspecting a database.
Before this release, Prisma Migrate could be used to apply migrations in a cloud-hosted environment (CI/CD pipeline, manual deployment to production, staging, etc.), but it was impossible to create new migrations, due to the requirement of a shadow database. Prisma Migrate expects to have privileges to create the shadow database using the same credentials, but cloud providers generally do not allow creating logical databases.
Starting from this release, prisma migrate dev
can now be used in development with cloud-hosted databases by configuring a separate connection URL for the shadow database.
To develop natively in the cloud with Prisma Migrate, developers can create two cloud-hosted databases, one being the development- and the other being the shadow-database.
The connection URI for the shadow database can be configured in the datasource
block of the Prisma schema file, similarly to the datasource URL, by defining a shadowDatabaseUrl
variable:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}
Another common limitation of cloud-hosted environments is that the database cannot be dropped and re-created using DROP DATABASE
and CREATE DATABASE
, due to insufficient privileges. Prisma Migrate so far relied on these statements to ensure the database is empty when it needs to be reset.
Database resets in the context of Prisma Migrate now gracefully fall back to dropping constraints, indexes and tables, if there are insufficient privileges to reset the database using DROP DATABASE
.
Note that this comes with the caveat that there could be other entities in the database, which Prisma Migrate could fail to clean up.
migrate dev
- if a non-interactive environment is detected, you'll be suggested to use prisma migrate deploy
instead.prisma/migrations/20210119114009_init
(missing migration.sql
file).prisma db push
prisma db push
now handles unexecutable migrations better, offering a path forward by resetting the database. For example, adding a new required field without a default value when there are rows in the table is considered an unexecutable migration; in such situations you will be prompted to first reset the database.—-force
has been renamed to --accept-data-loss
to be more explicit - this is required for certain changes that involve losing data, e.g. dropping a table or dropping a column if there are rows.—-force-reset
which first resets the database and then updates the schema - this can be useful to start from scratch and as a way to deal with unexecutable migrations (see above).prisma db seed
now supports custom schema locationsYou can now point the prisma db seed
command to a custom schema location using either of two approaches:
--schema
option when running the commandpackage.json
which will be picked up every time you run the command.server_name
fix: Before we couldn't connect to certain kind of SQL Server instances. If the server was a managed instance from Azure, connecting to it with Prisma would return Server name cannot be determined
. Additionally, when running a shared Azure SQL database, if the firewall setting was set to redirect
(the default setting), our connection would first fail with advising the user to connect to a new server, and when changing the connection string regarding the error, the new connection would fail with the same error Server name cannot be determined
. This is now fixed. Azure managed instances just work, as do redirections (which are done under the hood, automatically).NVarChar
/NChar
length and a maximum of 4000 for VarChar
/Char
/VarBinary
/Binary
length. The actual maximums are 4000
for first and 8000
for the latter types.executeRaw
to insert number values to a numeric
type in PostgreSQL, sometimes the stored value would be zero instead of the user input. An example value of 12345.0
is converted by JavaScript as an integer of 12345, which then is written as an integer to the table. The table column being numeric, the integer representation would always be zero in these cases. Now we should be able to convert integers to numeric
without any trouble.Byte
and BigInt
.createMany
preview feature doesn't crash Studio any moreFloat
has changed from Decimal
to Double
in MySQL and PostgreSQLIf you use the Float
scalar type in your Prisma schema and used Prisma Migrate to create the database schema in previous Prisam versions, the corresponding database column has the type DECIMAL(65,30)
.
For example, given the following Prisma schema:
model Post {
id Int @id @default(autoincrement())
title String
content String?
reward Float // Previously mapped to DECIMAL(65,30). From 2.17.0 will map to Double
published Boolean @default(false)
}
Previous version of Prisma Migrate would generate the following migration:
-- CreateTable
CREATE TABLE "Post" (
"id" SERIAL NOT NULL,
"title" TEXT NOT NULL,
"content" TEXT,
"reward" DECIMAL(65,30) NOT NULL, //
"published" BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY ("id")
);
As of 2.17.0
, the remapping of the Float
type from Decimal(65,30)
to Double
will cause Migrate to attempt to alter the database type of the reward
column to Double
the next time you create a migration.
Nothing changes in Prisma Client until the next time you want to make a change to your schema. In that case, you'll need to decide if you want to keep using the Decimal(65,30)
type in the database:
Decimal(65,30)
, you need to change the type in the Prisma schema from Float
to Decimal
. Alternatively, you can also run prisma introspect
which will automatically remap the previous Float
fields to Decimal
. Note that this will also change the type that Prisma Client returns from Number
to Decimal.js
.Decimal(65,30)
to Double
, leave the Prisma schema as is and create a new migration. Prisma Migrate will alter the column's type to Double
. Note that if you have rows with data for the column, they will be cast from Decimal(65,30)
to Double
.Check out this video guide, which covers how to upgrade and address the remapping of Float.
Prisma has default mappings between each scalar type in the Prisma schema to the underlying database type. For example, the String
scalar type in Prisma schema is mapped to a TEXT
column on PostgreSQL by default.
Before this release, Prisma supported using a range of database column types for a given Prisma scalar. For example, define a field in Prisma schema as String
and use VARCHAR(50)
as the column type in the database using the @db.varchar(50)
type annotation .
With the introduction of native types in General Availability, you can now specify your desired database type for columns in the Prisma schema via the @db.DB_TYPE
field attributes, e.g., @db.varchar(50)
.
Because the @db.DB_TYPE
attribute now exists, Prisma no longer allows the loose mapping of Prisma scalar types to database column types without the specific notation. The only exception to this rule is when you want to use default mapping, e.g., the String
Prisma scalar will map to TEXT
on PostgreSQL.
Given the following table in PostgreSQL:
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"nickName" VARCHAR(50),
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);
Prisma would introspect the table as follows:
model User {
id Int @id @default(autoincrement())
nickName String? //defaults to TEXT on PostgreSQL but works with varchar
name String //defaults to TEXT on PostgreSQL but works with varchar
}
Because VARCHAR(50)
can be expressed in native type notation. The matching Prisma schema for the User
database table above on PostgreSQL is the following:
// Example for PostgreSQL
model User {
id Int @id @default(autoincrement())
nickName String? @db.VarChar(50) // Prisma expects the column to be varchar and Prisma Migrate will change it if not
name String // Prisma expects the column to be of type TEXT (default for String) and Prisma Migrate will change it if not
}
Moving forward, if you want specific database column types, which are supported by Prisma, you should make sure to use the native type notation for the corresponding fields in the Prisma schema.
For users of Prisma Migrate with existing databases, you must understand that Prisma Migrate will try to migrate every column of a type different than what's defined in the schema.
If we go back to the previous example with loose type mapping, with this Prisma schema:
model User {
id Int @id @default(autoincrement())
nickName String? //defaults to TEXT on PostgreSQL but works with varchar
name String //defaults to TEXT on PostgreSQL but works with varchar
}
and this initial database schema:
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"nickName" VARCHAR(50),
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);
On PostgreSQL, from this release on, Prisma will the columns for the fields nickName
and name to be of type TEXT
and will generate a migration to alter the type of the nickName
column:
-- AlterTable
ALTER TABLE "User" ALTER COLUMN "nickName" SET DATA TYPE TEXT;
To avoid unnecessary migrations to change types you may have defined on purpose, you can run introspection once, which will add the native annotations to any fields when they do not match the default mappings by Prisma.
For the initial database schema we used in the example
-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"nickName" VARCHAR(50),
"name" TEXT NOT NULL,
PRIMARY KEY ("id")
);
This would be the resulting Prisma schema after running prisma introspect
model User {
id Int @id @default(autoincrement())
nickName String? @db.VarChar(50)
name String
}
undefined
value shouldn't return datamakeEnum
nativeTypes
localhost
for MySQL, MariaDB and SQL Server (mostly when running those via Docker)PRISMA_DISABLE_WARNINGS
Option::unwrap()
on a None
value ALTER TYPE
enum migrations fail in PostgreSQL@@ignore
and @ignore
on re-introspectionundefined
db seed
not documented in help output for prisma db --help
prisma migrate deploy
in migrate dev
non interactive error message for better discoverability.prisma migrate dev --create-only
- if there are data loss warnings, the CLI prompts suggest the new migration will be applied when it is (rightfully)not @ignore
code completion is supported in VS code extensionclippy
to migration-engine
clippy
to introspection-engine
clippy
to libs/datamodel
clippy
to all libs/*
(except datamodel)You can find all the features that are currently planned and in progress on our roadmap.
Huge thanks to @safinsingh for helping!
Published by pimeys over 3 years ago
Today, we introduce the 2.16.1
patch release.
This fixes a problem some users are having with certain Docker, MariaDB, MySQL or SQL Server configurations, preventing Prisma to connect with localhost
. A recent Docker update caused a regression related to IPv6 and name resolution.
Published by timsuchanek over 3 years ago
Today, we are excited to share the 2.16.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟
@prisma/cli
to the prisma
npm packageGoing forward, you can install the Prisma CLI via the prisma
npm package:
npm install prisma --save-dev
or
yarn add prisma --dev
The reason for this is that a number of users were experiencing issues when running the npx prisma
command. Without a local installation of the @prisma/cli
package, this would invoke the Prisma 1 CLI leading to an error message. From now on, npx prisma
is always going to work.
We will also deprecate the @prisma/cli
package. Please do a find and replace across your codebase to transition over from @prisma/cli
to prisma
. To make this transition easier, we'll keep publishing updates to both packages for another month and plan to stop updating the @prisma/cli
package with release 2.18.0
.
There are no changes to the @prisma/client
npm package name.
createMany
Insert data a whole lot faster with createMany
. Here's an example:
const result = await prisma.user.createMany({
data: [
{ email: "[email protected]" },
{ email: "[email protected]" },
{ email: "[email protected]" },
{ email: "[email protected]" },
],
});
console.log(`Created ${result.count} users!`);
This feature is in preview right now. Enable it with the createMany
preview flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["createMany"]
}
📚 Documentation: Create multiple records
Learn more in this issue.
orderBy
Ever wish you could order posts by an author's name? Or sort transactions by account? Now you can! We've expanded orderBy
to support ordering by relations:
cons posts = await prisma.post.findMany({
orderBy: [
{
author: {
name: "asc",
},
},
],
});
This feature is in preview right now. Enable it with the orderByRelation
preview flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["orderByRelation"]
}
📚 Documentation: Sort by relation
Learn more in this issue.
nativeTypes
Preview featureWe are working hard on making the Prisma experience smoother for folks that are using the nativeTypes
Preview feature and are getting close to releasing it for General Availability.
If you have any feedback for this feature, please share it on GitHub.
Unsupported
type allows to surface any database type in the Prisma schemaThis release introduces a new Unsupported
type in the Prisma schema. It acts as an escape hatch and allows to surface fields in Prisma schema for database types that are not yet supported by Prisma. For example, MySQL's POLYGON
type is not yet natively supported by Prisma, but can now be added to the Prisma schema using the Unsupported("polygon")
type.
The new type is especially relevant during introspection where previously fields of unsupported types would have been commented out, they're now included in the Prisma schema and of type Unsupported
.
Fields of the Unsupported
type are added to the Prisma schema in either of two ways:
Unsupported
in the Prisma schemaNote that fields of type Unsupported
will not be surfaced in the Prisma Client API.
Here's an example of the new Unsupported
type that uses MySQL's multilinestring
:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
bio Unsupported("multilinestring") @unique
}
Prisma Migrate generates the following SQL for the User
model:
CREATE TABLE `User` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`email` VARCHAR(191) NOT NULL,
`name` VARCHAR(191),
`bio` multilinestring NOT NULL,
UNIQUE INDEX `User.email_unique`(`email`),
UNIQUE INDEX `User.bio_unique`(`bio`),
PRIMARY KEY (`id`)
);
Unsupported
fields affect the Prisma Client APISince Prisma Client doesn't yet "understand" the Unsupported
type and therefore cannot read or write to its fields, we've also disabled creates and upserts on models that have a required Unsupported
field without a default value. This prevents constraint violations at runtime.
To make this explicit, a new @@ignore
attribute is added to the models that contain fields of type Unsupported
during introspection:
model User {
id Int @id @default(autoincrement())
location Unsupported("point")
@@ignore
}
// Not permitted because the database requires a `location`, but it can't be
// provided because the `point` type is unsupported by Prisma Client.
const user = await prisma.user.create({});
If the @@ignore
attribute is added to a model, the relation fields of that model on other models will be annotated with the @ignore
attribute, for example:
model User {
id Int @id @default(autoincrement())
location Unsupported("point")
@@ignore
}
model Post {
id Int @id @default(autoincrement())
title String
author User @ignore
}
dbgenerated()
dbgenerated()
in the @default
field directive can now take a String
argument that enables developers to reflect database-level default values that are not yet natively supported by Prisma.
This changes the signature of the attribute from dbgenerated()
to dbgenerated(default: String)
. As an example, you can use @default(dbgenerated("''"))
to define an empty string as the default value for a column in MySQL.
These default values will be surfaced when introspecting the database or created/changed when defined manually in combination with Prisma Migrate.
This feature can be used alongside the new Unsupported
type as well as with regular Prisma types.
Setting a default value on a multilinestring
column:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
bio Unsupported("multilinestring") @unique @default(dbgenerated("''"))
}
Prisma Migrate generates the following SQL for the User
model:
CREATE TABLE `User` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`email` VARCHAR(191) NOT NULL,
`name` VARCHAR(191),
`multilinestringField` multilinestring NOT NULL DEFAULT '',
UNIQUE INDEX `User.email_unique`(`email`),
UNIQUE INDEX `User.bio_unique`(`bio`),
PRIMARY KEY (`id`)
);
Setting a default value for UUIDs via the pgcrypto
PostgreSQL extension:
model User {
id String @id @db.Uuid @default(dbgenerated("gen_random_uuid()"))
name String?
}
Prisma Migrate generates the following SQL for the User
model:
CREATE TABLE "User" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"name" TEXT,
PRIMARY KEY ("id")
);
Note that the example above requires the corresponding extension to be enabled (in this case: CREATE EXTENSION "pgcrypto";
).
We've added new native types for the postgresql
provider. Here's an overview of the new type mappings:
PostgreSQL | Prisma | Note |
---|---|---|
Inet |
String |
|
Money |
Decimal |
|
Oid |
Int |
|
Citext |
String |
Requires the Citext extension |
Here's an example that uses the four new types in a Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
ipAddress String? @db.Inet
balance Decimal @db.Money
oid Int @db.Oid
citextName String @db.Citext
}
Prisma Migrate generates the following SQL for the User
model:
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"ipAddress" INET,
"balance" MONEY NOT NULL,
"oid" OID NOT NULL,
"citextName" CITEXT NOT NULL,
PRIMARY KEY ("id")
);
nativeTypes
Preview featurenativeTypes
Preview feature, introspection will only render a native attribute if the column type does not map to Prisma's corresponding default type. This might remove any existing type annotations upon (re-)introspection where the default mapping is currently in place.BIT(1)
can now be mapped to Prisma's Boolean
type as well using the Bit
native type attribute, e.g. myField Boolean @db.Bit(1)
.Float
type has been changed from DECIMAL(65,30)
to Double
.Float
type has been changed from DECIMAL(65,30)
to Double
.Decimal
type has been changed from REAL
to DECIMAL
.prisma migrate dev
, Prisma Migrate will generate DDL statements to change columns of Prisma's type Float
to use Double
instead of Decimal
. These changes may lead to rounding errors due to differences in precision.Decimal
and continue using that as as the column type.
Decimal
Decimal
or re-introspect your database with prisma introspect after enabling native typesmyField Float
myField Decimal @db.Decimal(65,30)
Decimal
before on SQLite, with the native type feature flag enabled, Prisma Migrate will change the type in the next migration from REAL
to DECIMAL
.Decimal
to Float
, or running re-introspection which will do the same.queryRaw
Breaking ChangesOn MySQL only, fields of type Boolean
are stored as TINYINT(1)
in the database. We no longer coerce the value to a Boolean. That means queryRaw
now returns integers of value 0
or 1
instead of true
or false
for Boolean
fields.
You can host your own instance of Prisma Studio on Vercel by following the instructions in the README of this example repo.
prisma migrate dev
or prisma migrate reset
with the —-skip-seed
flag.--schema
option on the prisma db seed
command to execute the command with a custom Prisma schema location.Give your users more control over how they filter and order their data. Build up filters over time instead of all at once.
Here's an example of setting specific attributes dynamically:
func CreateUser(w http.ResponseWriter, r *http.Request) {
var params []db.UserSetParam
email := r.PostFormValue("email")
kind := r.PostFormValue("kind")
if kind == "customer" {
// Set the referrer for users of type customer only
params = append(params, db.User.Referer.Set(r.Header.Get("Referer"))
}
user, err := client.User.CreateOne(
db.User.Kind.Set(kind),
db.User.Email.Set(email),
params...,
).Exec(r.Context())
// ... Handle the response
}
Learn more in the Go documentation.
.prisma/client
"Result::unwrap()
on an Err
value: Could not parse stored DateTime string: 2020-11-27 01:17:30 (input contains invalid characters)rejectOnNotFound
count
query not working in react-prismaOpen in new tab
for relation lists does not work as expectedFloat
min
and max
aggregate for Json types to DMMFldd
output of enginesHuge thanks to @aruld for helping!
Published by timsuchanek over 3 years ago
Today, we are excited to share the 2.15.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release.
In 2.11.0, we introduced support for native database types in the Prisma schema that allow you to map Prisma's scalar types to more specific types in the underlying database. However, these have not been compatible with the current Preview version of Prisma Migrate yet.
This release makes it possible to use Prisma Migrate with the native type annotations in your Prisma schema!
Here's an example that uses several type annotations:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @id @default(autoincrement()) @db.Integer
published Boolean @default(false)
content String? @db.VarChar(1000)
title String @db.VarChar(191)
buffer Bytes?
}
Running a migration using the prisma migrate
command, the following SQL is created:
CREATE TABLE "Post" (
"id" SERIAL,
"published" BOOLEAN NOT NULL DEFAULT false,
"content" VARCHAR(1000),
"title" VARCHAR(191) NOT NULL,
"buffer" BYTEA,
PRIMARY KEY ("id")
);
A common requirement, especially for local development, is the ability to quickly seed your database with initial data. This is now possible with Prisma using the new prisma db seed
command which is introduced in Preview in this release. Seeding is currently supported via scripts written in TypeScript, JavaScript, Go and Shell.
The command expects a file called seed
with the respective file extension inside your main prisma
directory.
prisma/seed.js
prisma/seed.ts
prisma/seed.go
prisma/seed.sh
For example, this prisma/seed.ts
file could be invoked using the new command:
// prisma/seed.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// A `main` function so that we can use async/await
async function main() {
const newUser = await prisma.user.create({
data: {
email: "[email protected]"
}
})
console.log(`new user created`, newUser.id)
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
To execute the seeding, run the new command with the --preview-feature
flag:
prisma db seed --preview-feature
Please provide feedback for the new prisma db seed
command here.
findFirst
and findUnique
queries if no record is foundWith the new rejectOnNotFound
option, you can now tell Prisma Client to throw an exception when findFirst
or findUnique
does not find any records.
Here's an example:
const user = await client.user.findUnique({
where: {
id: 10,
},
rejectOnNotFound: true
})
// Throws "NotFoundError: No User found" if the
// user with id = 10 does not exist.
If you omit rejectOnNotFound
, these calls continue to return undefined
.
We've added some new capabilities to your where
condition for filtering arrays in PostgreSQL:
has
: a value is contained within the arrayhasEvery
: all values are contained within the arrayhasSome
: at least one values is contained in the arrayisEmpty
: the array is emptyHere's an example:
model User {
id Int @id
roles Role[]
}
enum Role {
ADMIN
EDITOR
READER
}
const admin = await prisma.user.findFirst({
where: {
id: 1,
roles: {
has: 'ADMIN'
}
}
})
Learn more about this feature from this GitHub comment.
select
When using count
queries, you can provide a number of options, e.g. for filtering. This release introduces the select
option for count
queries which lets you filter for non-null values of multiple fields in a single query.
Assume you have this User
model with a number of optional fields:
model User {
id Int @id @default(autoincrement()) @db.Integer
createdAt DateTime @default(now())
name String?
email String?
birthday DateTime?
}
You can send the following query to retrieve the count of records that contain non-null values for the respective field:
const userCounts = await prisma.user.count({
select: {
name: true,
email: true,
birthday: true
}
})
This will return an object with the following structure, where the value of each field indicates how many records in the database contain a value for it:
{
name: 2,
email: 0,
birthday: 1
}
This is also works with aggregate
and groupBy
:
// new possibility:
const usersAggregation = await prisma.user.aggregate({
count: { name: true }
})
// same for group by:
const groupedByName = await prisma.user.aggregate({
by: ["name"],
count: true
})
// or more fine-grained control over the fields to be counted
const groupedByNameCount = await prisma.user.aggregate({
by: ["name"],
count: { name: true, _all: true }
})
In 2.11.0, we introduced the uncheckedScalarInputs
preview flag which allowed you to modify relations by directly setting foreign keys in your queries (as opposed to using a nested write with the connect
option).
Fire up that delete key because you can now remove this flag from your Prisma schema.
generator client {
provider = "prisma-client-js"
- previewFeatures = ["uncheckedScalarInputs"]
}
As a reminder, this allows you to set foreign keys directly:
// An example of the new API that directly sets the foreign key
const user = await prisma.profile.create({
data: {
bio: 'Hello World',
userId: 42
},
})
// If you prefer, you can still use the previous API via `connect`
const user = await prisma.profile.create({
data: {
bio: 'Hello World',
user: {
connect: { id: 42 }, // sets userId of Profile record
},
},
})
Read more about in the documentation on relation queries.
provider
on your datasource
block, for example when the migrations have been created with sqlite
but the provider
is now set to postgresql
. Prisma Migrate will now print a helpful error message in these cases.prisma migrate reset
can now be used in non-interactive environments (e.g. CI/CD) by passing the --force
flag.prisma migrate reset
is called to reset and repopulate the database in development. It's also triggered when the database is reset interactively after calling prisma migrate dev
.As of this release, Prisma Studio can be used in dark mode! You can use the Settings icon in the top right corner to switch between light and dark mode.
We also included more powerful ways for you to filter the records of a table:
Json
fieldsnativeTypes
Preview featureThis version of introduces a few changes to the nativeTypes
Preview feature:
Numeric
alias for Decimal
on PostgreSQL, MySQL and Microsoft SQL Server. Replace any Numeric
types with Decimal
when you upgrade.Serial
, SmallSerial
, and BigSerial
aliases for INT AUTOINCREMENT
, SMALLINT AUTOINCREMENT
, and BIGINT AUTOINCREMENT
on PostgreSQL. You can use Int @default(autoincrement())
, Int @db.SmallInt @default(autoincrement())
or Int @db.BigInt @default(autoincrement())
when you upgrade.JSON
to Json
on MySQL.Datetime
to DateTime
on MySQL.FindOneModelArgs
and FindManyModelArgs
type definitions to improve consistency. See this issue for more details.findOne
and moved many of the Typescript types under the Prisma
namespace.Prisma Client Go now supports database transactions with a sparkly new Transaction
API:
createUserA := client.User.CreateOne(
db.User.ID.Set("c"),
db.User.Email.Set("a"),
)
createUserB := client.User.CreateOne(
db.User.ID.Set("d"),
db.User.Email.Set("b"),
)
err := client.Prisma.Transaction(createUserA, createUserB).Exec(ctx)
if err != nil {
return err
}
Learn more about Transaction
in the reference. If you'd like to try out Prisma Client Go, check out the Quickstart for a gentle introduction.
We now support secure connections between a Mac and SQL Server so your data is encrypted while in transit.
uncheckedScalarInputs
@prisma/cli
and @prisma/client
have different versions in package.json
$on('beforeExit')
select
& include
(in Client requests) through typesprisma migrate reset
in non-interactive environmentsprisma migrate reset
fails if the db is not already initializedHuge thanks to @qsona, @mikebobadilla, @cyrus-za for helping!
Published by timsuchanek almost 4 years ago
We hope everyone enjoyed their holidays and recharged for 2021! Today, we are excited to share the 2.14.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release.
Prisma Client now supports group by queries! Opt-in to this feature by adding the groupBy
flag to the generator
block in your Prisma schema:
generator client {
provider = "prisma-client-js"
+ previewFeatures = ["groupBy"]
}
model Agent {
id String @id
name String
location String
rate Float
}
Now you can re-generate your Prisma Client to have access to the new groupBy
API:
npx prisma generate
With the updated Prisma Client, you can invoke the new groupBy
query:
const locations = await client.agent.groupBy({
by: ['location'],
min: {
rate: true
},
})
// Result:
// [
// { location: "Los Angeles", min: { rate: 10.00 } },
// { location: "London", min: { rate: 20.00 } },
// { location: "Tokyo", min: { rate: 30.00 } }
// ]
Prisma also supports the having
side of group by, so you can further filter your groups:
const locations = await client.agent.groupBy({
by: ['location', 'rate'],
min: {
rate: true
},
having: {
rate: {
gte: 20
}
}
})
// Result:
// [
// { location: "London", rate: 20.00, min: { rate: 20.00 } },
// { location: "Tokyo", rate: 30.00, min: { rate: 30.00 } }
// ]
Read more in the documentation.
Good news for Linux users! Prisma now supports Linux ARM64 out of the box. If you already generate the Prisma Client on a Linux ARM box, it will just work. To target the specific binary, you can add a binaryTarget
to the generator
block in your Prisma schema:
generator client {
provider = "prisma-client-js"
binaryTargets = ["linux-arm-openssl-1.1.x"]
}
Learn more in the documentation.
PostgreSQL users who are using the PostGIS extension can now use Prisma Migrate as well.
This release introduces a breaking change for TypeScript users. Prisma Client now requires TypeScript v4.1 or above. You can read more about upgrading your TypeScript version on their wiki.
prisma
react-prisma
prototypeprisma-client-js
...
)migrate
language-tools
studio
prisma-engines
Huge thanks to @qsona for helping!
We love open-source and are commited to building world-class database tools that make developers more productive. In addition to building open-source tools, we are currently planning a cloud offering that will improve many database workflows, especially in collaborative environments.
If you want to help us shape the future of this offering, we would much appreciate if you could fill out this short survey that represents a potential onboarding flow for that cloud offering.
Published by timsuchanek almost 4 years ago
Today, we are issuing the 2.13.1
patch release.
INSERT..OUTPUT
if the table has triggers on MSSQLPublished by timsuchanek almost 4 years ago
Today, we are excited to share the 2.13.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release.
We are releasing Prisma Migrate in Preview; read the announcement blog post to learn more. This version is the evolution of the Experimental Prisma Migrate we released last year. We've changed Migrate to be more predictable and providing fine-grained control over how exactly database schema changes are carried out. You can learn more about the Preview stage in the Prisma docs.
Please try out Prisma Migrate and share your feedback for it here.
Prisma Migrate still picks up the changes in your Prisma schema file to generate migration files. The main difference compared to the previous Migrate version is that these migration files are now plain SQL and fully customizable; this allows for:
This evolved version of Prisma Migrate is now deterministic making sure migrations are always executed in a predictable way. The tool supports both workflows for deploying migrations to production and other environments. It also comes with an interactive development command that not only helps to create and apply migrations, but also helps developers to get back on track when they run into certain issues.
The new Preview version is not backward compatible with the previous Experimental version. You can learn more about the upgrade process in the docs.
Until now, you could not import any typings that are generated by Prisma Client in a browser application. This changed in this release! With 2.13.0, you can now import all your enums and all types from Prisma Client in any browser environment. This also works across all the universal Javascript frameworks like Next.js, Blitz, Gatsby, and Vue.js.
Let's take a look at an example of a React component utilizing the new exports. Assume you have the following Prisma schema:
model User {
id String @id
hobbies Hobby[]
}
enum Hobby {
Tennis
Prisma
Basketball
}
Once you've generated the @prisma/client
node module, you can import the generated types in your frontend application as follows:
import { Hobby, User } from '@prisma/client'
type Props = {
user: User
}
export function HobbyComponent({ user }: Props) {
return (
<div>
Hello {user.name}! <br />
The available hobbies are: <br />
<ul>
{Object.values(Hobby).map(hobby => <li key={hobby}>{hobby}</li>)}
</ul>
</div>
)
}
You can now use your keyboard to navigate between tabs in the Prisma Studio standalone app:
You can now use your keyboard to zoom in and out in the Prisma Studio standalone app:
Inline editing of arrays (scalar lists) has sometimes been cumbersome with the Prisma Studio UI. With this release, we include a smoother UX for this.
Note that you can try out Studio with some sample datasets here.
We've had JSON support in Prisma Client JS for quite a while, but we're pleased to announce that the Go version of Prisma Client now has JSON support as well. Head over to the documentation to learn more!
Join us online for the second Prisma Meetup and learn more about the Preview version of Prisma Migrate from Alberto Perdomo and Tom Houlé who have been deeply involved building it.
prisma
prisma init
to write to .env instead of prisma/.envdeleteMany
should be valid without parametersdeleteMany
without args in TypeScriptSymbol.toStringTag
to Prisma Clientdbgenerated()
is added via introspectionmigrate
language-tools
studio
prisma-engines
Huge thanks to @qsona for helping!
Published by timsuchanek almost 4 years ago
Today, we are issuing the 2.12.1
patch release.
Published by timsuchanek almost 4 years ago
Today, we are excited to share the 2.12.0
stable release 🎉
🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release.
We have repackaged Prisma Studio to work also as a standalone macOS application. This should help you run Studio with just a double click and without opening your terminal, just in case you quickly want to browse or edit your data.
Download the installation files from the Studio release page. Support for more platforms (Windows and Linux) will come soon. Let us know if which one you would want first!
With today's release, we took the opportunity to cleanup some rough edges in the Prisma Client API which partially results in breaking changes. To help you with upgrading your codebase to 2.12.0
, we're introducing @prisma/codemods
.
The @prisma/codemods
package provides a powerful CLI that scans your codebase and automatically updates the code to the new API calls from the provided version.
The upgrade workflow looks like this:
cd my-app
npm install @prisma/cli @prisma/client
npx @prisma/codemods update-2.12 ./
Hot off the presses: You can now use database native types with Microsoft SQL Server! You'll need to specify both previewFeatures = ["microsoftSqlServer", "nativeTypes"]
to get started:
generator js {
provider = "prisma-client-js"
previewFeatures = ["microsoftSqlServer", "nativeTypes"]
}
datasource ms {
provider = "sqlserver"
url = env("DATABASE_URL")
}
model User {
id BigInt @id @default(autoincrement()) @ms.BigInt
name String? @ms.VarChar(255)
}
model Post {
id BigInt @id @default(autoincrement()) @ms.BigInt
title String @ms.VarChar(100)
views BigInt @default(0) @ms.BigInt
wordCount Int @default(0) @ms.SmallInt
}
Note that Prisma Migrate does not yet work with Microsoft SQL Server, nor does Prisma Client Go.
We’ve got a Preview release of Prisma Migrate nearing up with a large set of changes. You can test it in Early Access, see the upcoming changes, and provide feedback! Get started with the Early Access version here.
To join the conversation, join the #product-feedback
channel on our Slack.
As mentioned before, we're cleaning up the Prisma Client API which partially results in breaking changes. You can upgrade to the latest version using the new @prisma/codemods
package as explained above.
$
methodsA few months back, we began prefixing our top-level Prisma methods with $
. For example, prisma.transaction
became prisma.$transaction
. We did this to avoid clashes with your application's model names.
The non-$
methods were deprecated but continued to work until this release. In this release, we removed the deprecated methods.
This means if you are still using calls like prisma.transaction
or prisma.disconnect
instead of prisma.$transaction
or prisma.$disconnect
in your code, your app is going to break after upgrading to 2.12.0
.
The @prisma/codemods
workflow describe above will automatically fix any remaining non-$ methods in your codebase.
You can read more about this change in on Github.
In this version, we're adding a new requirement for 1-1-relations that you define in your Prisma schema. In previous versions, it used to be allowed to have both sides of the relation required. As of this release, the virtual side of the relation (i.e. the side that does not store the foreign key in the underlying database) must be optional.
Before
model User {
id Int @id @default(autoincrement())
name String?
profile Profile // ❌ this is not allowed as of 2.12.0
}
model Profile {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
}
After
model User {
id Int @id @default(autoincrement())
profile Profile? // ✅ the virtual side of the relation needs to be optional
}
model Profile {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
}
The easiest way to adjust your schema to these new requirements is by running the introspect
command which will automatically make the virtual relation fields optional on 1-1-relations:
npx prisma introspect
Json[]
fields is storedWe fixed how the Json[]
type is stored in 2.12.0
. Previously, we were storing JSON arrays as a string inside a your database's JSON
column. Now, we properly encode JSON arrays as JSON
in the database. This fix will allow us to add database native JSON operations down the line.
If you are using the Json[]
type in your schema, you'll need to migrate your data. We anticipate this breaking change will only affect a handful of folks. Please reach out to us in this issue and we'll help you with the migration.
Here is an overview of how the behaviour changes in 2.12.0
:
Given | 2.11.0 |
2.12.0 |
---|---|---|
[] |
[[]] |
[] |
[{test:"test"}] |
["{\"test\":\"test\"}"] |
[{"test":"test"}] |
[{ test: "test" }, { test: "test2" }] |
["[{\"test\": \"test\"}, {\"test\": \"test2\"}]"] |
[{"test": "test"},{"test": "test2"}] |
[3] |
3 |
[3] |
findOne
to findUnique
This release renames findOne
to findUnique
and deprecates findOne
.
We made this change to reduce confusion. Many people expected findOne
to be more loose, e.g: "Find the first record that matches my conditions.".
The @prisma/codemods
workflow describe above will automatically rename findOne
to findUnique
across your codebase.
Prisma
namespaceWe moved most of the generated types under a new Prisma
namespace and are deprecating the top-level exports. This change also resolves some existing namespace clashes.
Before
import { PrismaClient, User, UserCreateInput } from '@prisma/client'
async function createUser(input: UserCreateInput): Promise<User> {
return prisma.user.create(input)
}
After
import { PrismaClient, User, Prisma } from '@prisma/client'
async function createUser(input: Prisma.UserCreateInput): Promise<User> {
return prisma.user.create(input)
}
This means that with this release, there are exactly three kinds of exports in @prisma/client
:
PrismaClient
is the constructor your Prisma Client instanceUser
and Post
Prisma
as the new namespace under which you can now access the remaining generarted typesThe @prisma/codemods
workflow describe above will automatically fix the type names in your code!
With this change, we've greatly reduced the number of reserved words that could clash with your application's names. Go forth and add models with names like Transaction
or Aggregate
!
prisma
dbgenerated()
values in an issue via "warning" output in IntrospectionfindOne
with findUnique
n
Prisma Client instances are instantiatedprisma-client-js
TypeError: Cannot read property 'findMany' of undefined
for non existing model?migrate
name
on index when creation fails because of lengthlanguage-tools
studio
prisma-engines
Huge thanks to @matt-eric, @muxahuk for helping!