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.
Major improvements
Prisma Migrate now supports native database types (Preview)
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:
Running a migration using the Expand for an example usage of Prisma Migrate with native types
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?
}
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")
);
Integrated database seeding (Preview)
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.
- JavaScript:
prisma/seed.js
- TypeScript:
prisma/seed.ts
- Go:
prisma/seed.go
- Shell:
prisma/seed.sh
Expand for an example seeding workflow using TypeScript
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: "sarah@prisma.io"
}
})
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.
Throw exceptions in findFirst
and findUnique
queries if no record is found
With 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
.
Improved API for filtering arrays in PostgreSQL
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 empty
Here'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.
More powerful counting of records using 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 }
})
Modifying relations by directly setting foreign keys is now stable
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.
More improvements for Prisma Migrate
- Prisma Migrate now detects when the migrations don’t match the configured
provider
on yourdatasource
block, for example when the migrations have been created withsqlite
but theprovider
is now set topostgresql
. 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.- The new seeding functionality (see above) will be automatically triggered whenever
prisma migrate reset
is called to reset and repopulate the database in development. It's also triggered when the database is reset interactively after callingprisma migrate dev
.
Dark mode for Prisma Studio 🌒 & more powerful filtering
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:
- Filter by
Json
fields - Filter by the ID of a related model
Changes to the nativeTypes
Preview feature
This version of introduces a few changes to the nativeTypes
Preview feature:
- Removed the
Numeric
alias forDecimal
on PostgreSQL, MySQL and Microsoft SQL Server. Replace anyNumeric
types withDecimal
when you upgrade. - Removed the
Serial
,SmallSerial
, andBigSerial
aliases forINT AUTOINCREMENT
,SMALLINT AUTOINCREMENT
, andBIGINT AUTOINCREMENT
on PostgreSQL. You can useInt @default(autoincrement())
,Int @db.SmallInt @default(autoincrement())
orInt @db.BigInt @default(autoincrement())
when you upgrade. - Renamed
JSON
toJson
on MySQL. - Renamed
Datetime
toDateTime
on MySQL.
Breaking changes
- We've upgraded our RHEL base image from CentOS 6 to Amazon Linux 2. CentOS 6 reached end-of-life on November 30th, 2020. This may affect machines still running Amazon Linux 1. If you run into problems with this upgrade, please don't hesitate to reach out.
- We've renamed the
FindOneModelArgs
andFindManyModelArgs
type definitions to improve consistency. See this issue for more details. - Following the deprecation in 2.12.0, this release we've removed
findOne
and moved many of the Typescript types under thePrisma
namespace.
Other
Transaction API for Prisma Client Go
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.
SQL Server TLS Support on Mac
We now support secure connections between a Mac and SQL Server so your data is encrypted while in transit.
Fixes and improvements
Prisma Schema
Prisma Client
- Stabilize
uncheckedScalarInputs
- No warning is printed when
@prisma/cli
and@prisma/client
have different versions inpackage.json
- Connected fields do not get an updated by @updatedAt
- Error: Provided String, expected DateTime or DateTimeFieldUpdateOperationsInput
- $connect doesn't throw error on mysql connector if database is not reachable
- New count functionality
- Enable strict mode across the codebase
- Add types for
$on('beforeExit')
- Error due to sockets file getting deleted
- Sqlite client: ConversionError(cannot parse integer from empty string)
- Array relation unpack error
- OR operator behaving like AND
- Remove deprecated features
- Slow Nested Queries - taking 2 seconds plus
- Querying a relation field with include or select returns the wrong type
- Cannot read property 'isCanceled' of undefined
- Grouping by required fields should be not have nullable output type
- Enforce mutual exclusivity of
select
&include
(in Client requests) through types - PostgreSQL: "PANIC: column on null constraint violation error in /root/.cargo/git/checkouts/quaint-9f01e008b9a89c14/a1decce/src/connector/postgres/error.rs:67:35"
- Fails inside node cluster - Address already in use
- Rename FindOneModelArgs & FindManyModelArgs to ModelFindOneArgs and ModelFindManyArgs
Prisma Migrate
- Prisma Migrate: Improve UX when switching providers
- Ability to use
prisma migrate reset
in non-interactive environments prisma migrate reset
fails if the db is not already initialized
Prisma Studio
- Allow filtering of JSON fields
- Allow filtering by relation fields
- Linux app icon is incorrect
- Cannot open intended Model using Prisma Studio's search window with keyboard shortcut
Prisma Engines
Credits
Huge thanks to @qsona, @mikebobadilla, @cyrus-za for helping!