yarn prisma 2.15.0

latest releases: 5.23.0-dev.10, 5.23.0-dev.9, 5.23.0-integration-engines-5-23-0-8-integration-include-field-native-type-data-to-dmmf-f616ccc38c3d791e452ebd52f830a7fad0161650.2...
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.

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!

Expand for an example usage of Prisma Migrate with native types

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")
);

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 array
  • hasEvery: all values are contained within the array
  • hasSome: at least one values is contained in the array
  • isEmpty: 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 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.
  • 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 calling prisma 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 for Decimal on PostgreSQL, MySQL and Microsoft SQL Server. Replace any Numeric types with Decimal when you upgrade.
  • Removed the 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.
  • Renamed JSON to Json on MySQL.
  • Renamed Datetime to DateTime 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 and FindManyModelArgs 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 the Prisma 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

Prisma Migrate

Prisma Studio

Prisma Engines

Credits

Huge thanks to @qsona, @mikebobadilla, @cyrus-za for helping!

Don't miss a new prisma release

NewReleases is sending notifications on new releases.