Skip to content
This repository was archived by the owner on Oct 19, 2022. It is now read-only.

⬆️ Update prisma monorepo to v4 (major)#24

Open
renovate[bot] wants to merge 1 commit intomainfrom
renovate/major-prisma-monorepo
Open

⬆️ Update prisma monorepo to v4 (major)#24
renovate[bot] wants to merge 1 commit intomainfrom
renovate/major-prisma-monorepo

Conversation

@renovate
Copy link
Contributor

@renovate renovate bot commented Jul 3, 2022

Mend Renovate

This PR contains the following updates:

Package Change Age Adoption Passing Confidence
@prisma/client (source) ^3.13.0 -> ^4.0.0 age adoption passing confidence
prisma (source) ^3.13.0 -> ^4.0.0 age adoption passing confidence

Release Notes

prisma/prisma

v4.3.1

Compare Source

Today, we are issuing the 4.3.1 patch release.

Fixes in Prisma Client
Fixes in Prisma CLI

v4.3.0

Compare Source

🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟

Major improvements

Field reference support on query filters (Preview)

We're excited to announce Preview support for field references. You can enable it with the fieldReference Preview feature flag.

Field references will allow you to compare columns against other columns. For example, given the following schema:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fieldReference"]
}

model Invoice {
  id     Int @​id @​default(autoincrement)
  paid   Int
  due    Int
}

You can now compare one column with another after running prisma generate, for example:

// Filter all invoices that haven't been paid yet
await prisma.invoice.findMany({
  where: {
    paid: {
      lt: prisma.invoice.fields.due // paid < due
    }
  }
})

Learn more about field references in our documentation. Try it out and let us know what you think in this GitHub issue.

Count by filtered relation (Preview)

In this release, we're adding support for the ability to count by a filtered relation. You can enable this feature by adding the filteredRelationCount Preview feature flag.

Given the following Prisma schema:

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["filteredRelationCount"]
}

model User {
  id    Int     @&#8203;id @&#8203;default(autoincrement())
  email String  @&#8203;unique
  name  String?
  posts Post[]
}

model Post {
  id        Int      @&#8203;id @&#8203;default(autoincrement())
  title     String
  content   String?
  published Boolean  @&#8203;default(false)

  author    User?    @&#8203;relation(fields: [authorId], references: [id])
  authorId  Int?
}

You can now express the following query with the Preview feature after re-generating Prisma Client:

// Count all published user posts 
await prisma.user.findMany({
  select: {
    _count: {
      posts: { where: { published: true } },
    },
  },
})

Learn more in our documentation and let us know what you think in this issue

Multi-schema support (Preview)

In this release, we're adding very early Preview support of multi-schema support for PostgreSQL and SQL Server behind the multiSchema Preview feature flag. With it, you can write a Prisma schema that accesses models across multiple schemas.

Read further in this GitHub issue. Try it out and let us know what you think in this GitHub issue.

Prisma CLI exit code fixes

We've made several improvements to the Prisma CLI:

  • prisma migrate dev previously returned a successful exit code (0) when prisma db seed was triggered but failed due to an error. We've fixed this and prisma migrate dev will now exit with an unsuccessful exit code (1) when seeding fails.

  • prisma migrate status previously returned a successful exit code (0) in unexpected cases. The command will now exit with an unsuccessful exit code (1) if:

    • An error occurs
    • There's a failed or unapplied migration
    • The migration history diverges from the local migration history (/prisma/migrations folder)
    • Prisma Migrate does not manage the database' migration history
  • The previous behavior when canceling a prompt by pressing Ctrl + C was returning a successful exit code (0). It now returns a non-successful, SIGINT, exit code (130).

  • In the rare event of a Rust panic from the Prisma engine, the CLI now asks you to submit an error report and exit the process with a non-successful exit code (1). Prisma previously ended the process with a successful exit code (0).

Improved precision for the tracing Preview feature

Before this release, you may have occasionally seen some traces that took 0μs working with the tracing Preview feature. In this release, we've increased the precision to ensure you get accurate traces.

Let us know if you run into any issues in this GitHub issue.

prisma format now uses a Wasm module

Initially, the prisma format command relied on logic from the Prisma engines in form of a native binary. In an ongoing effort to make prisma more portable and easier to maintain, we decided to shift to a Wasm module.

prisma format now uses the same Wasm module as the one the Prisma language server uses, i.e. @prisma/prisma-fmt-wasm, which is now visible in prisma version command's output.

Let us know what you think. In case you run into any issues, let us know by creating a GitHub issue.

MongoDB query fixes

⚠️ This may affect your query results if you relied on this buggy behavior in your application.

While implementing field reference support, we noticed a few correctness bugs in our MongoDB connector that we fixed along the way:

  1. mode: insensitive alphanumeric comparisons (e.g. “a” > “Z”) didn’t work (GitHub issue)
  2. mode: insensitive didn’t exclude undefined (GitHub issue)
  3. isEmpty: false on lists types (e.g. String[]) returned true when a list is empty (GitHub issue)
  4. hasEvery on list types wasn’t aligned with the SQL implementations (GitHub issue)
JSON filter query fixes

⚠️ This may affect your query results if you relied on this buggy behavior in your application.
We also noticed a few correctness bugs in when filtering JSON values when used in combination with the NOT condition. For example:

await prisma.log.findMany({
  where: {
    NOT: {
      meta: {
        string_contains: "GET"
      }
    }
  }
})
Prisma schema
model Log {
  id      Int  @&#8203;id @&#8203;default(autoincrement())
  level   Level
  message String
  meta    Json
}

enum Level {
  Info
  Warn
  Error
}

If you used NOT with any of the following queries on a Json field, double-check your queries to ensure they're returning the correct data:

  • string_contains
  • string_starts_with
  • string_ends_with
  • array_contains
  • array_starts_with
  • array_ends_with
  • gt/gte/lt/lte
Prisma extension for VS Code improvements

The Prisma language server now provides Symbols in VS Code. This means you can now:

  • See the different blocks (datasource, generator, model, enum, and type) of your Prisma schema in the Outline view. This makes it easier to navigate to a block in 1 click
    A few things to note about the improvement are that:

    • CMD + hover on a field whose type is an enum will show the block in a popup
    • CMD + left click on a field whose type is a model or enum will take you to its definition.
  • Enable Editor sticky scroll from version 1.70 of VS Code. This means you can have sticky blocks in your Prisma schema, improving your experience when working with big schema files

Make sure to update your VS Code application to 1.70, and the Prisma extension to 4.3.0.

We'd also like to give a big Thank you to @​yume-chan for your contribution!

Prisma Studio improvements

We've made several improvements to the filter panel which includes:

  • Refined filter panel

    • Reducing the contrast of the panel in dark mode
    • Ability to toggle filters in the panel
  • Refined error handling for MongoDB m-n relations
    Prisma Studio prevents fatal errors when interacting with m-n relations by explicitly disabling creating, deleting, or editing records for m-n relations

  • Multi-row copying
    You can select multiple rows and copy them to your clipboard as JSON objects using CMD + C on MacOS or Ctrl + C on Windows/ Linux

Prisma Client Extensions: request for comments

For the last couple of months, we've been working on a specification for an upcoming feature — Prisma Client extensions. We're now ready to share our proposed design and we would appreciate your feedback.

Prisma Client Extensions aims to provide a type-safe way to extend your existing Prisma Client instance. With Prisma Client Extensions you can:

  • Define computed fields
  • Define methods for your models
  • Extend your queries
  • Exclude fields from a model
    ... and much more!

Here’s a glimpse at how that will look:

const prisma = new PrismaClient().$extend({
  $result: {
    User: {
      fullName: (user) => {
        return `${user.firstName} ${user.lastName}`
      },
    },
  },
  $model: {
    User: {
      signup: async ({ firstName, lastName, email, password }) => {
        // validate and create the user here
        return prisma.user.create({ 
          data: { firstName, lastName, email, password }
        })
      },
    },
  },
})

const user = await prisma.user.signup({
  firstName: "Alice", 
  lastName: "Lemon", 
  email: "alice@prisma.io", 
  password: "pri$mar0ckz"
})
console.log(user.fullName) // Alice Lemon

For further details, refer to this GitHub issue. Have a read and let us know what you think!

Fixes and improvements

Prisma Client
Prisma
Prisma Migrate
Language tools (e.g. VS Code)

Credits

Huge thanks to @​abenhamdine, @​drzamich, @​AndrewSouthpaw, @​kt3k, @​lodi-g, @​Gnucki, @​apriil15, @​givensuman for helping!

Prisma Data Platform

We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:

  • Data Browser for navigating, editing, and querying data
  • Data Proxy for your database's persistent, reliable, and scalable connection pooling.
  • Query Console for experimenting with queries

Try it out and let us know what you think!

💼 We're hiring!

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.

📺 Join us for another "What's new in Prisma" livestream

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, September 1 at 5 pm Berlin | 8 am San Francisco.

v4.2.1

Compare Source

Today, we are issuing the 4.2.1 patch release.

Fix in Prisma Client

v4.2.0

Compare Source

🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟

Major improvements

Prisma Client tracing support (Preview)

We're excited to announce Preview support for tracing in Prisma Client! 🎉

Tracing allows you to track requests as they flow through your application. This is especially useful for debugging distributed systems where each request can span multiple services.

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.

Isolation levels for interactive transactions

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.

Renaming of Prisma Client Metrics

In this release, we've renamed the metrics — counters, gauges, and histograms — returned from prisma.$metrics() to make it a little easier to understand at a glance.

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.

Syntax highlighting for raw queries in Prisma Client

This release adds syntax highlighting support for raw SQL queries when using $queryRaw`` and $executeRaw`` . This is made possible using Prisma's VS Code extension.

Screenshot 2022-08-09 at 12 30 27

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.

Experimental Cloudflare Module Worker Support

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.

Upgrade to Prisma 4

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!

Request for feedback

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! 🙌🏽

Fixes and improvements

Prisma Client
Prisma
Language tools (e.g. VS Code)
Prisma Studio

Credits

Huge thanks to @​shian15810, @​zifeo, @​lodi-g, @​Gnucki, @​apriil15, @​givensuman, @​peter-gy for helping!

Prisma Data Platform

We're working on the Prisma Data Platform — a collaborative environment for connecting apps to databases. It includes the:

  • Data Browser for navigating, editing, and querying data
  • Data Proxy for persistent, reliable, and scalable connection pooling for your database.
  • Query Console for experimenting with queries

Try it out and let us know what you think!

💼 We're hiring!

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.

📺 Join us for another "What's new in Prisma" livestream

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.

v4.1.1

Compare Source

Today, we are issuing the 4.1.1 patch release.

Fix in Prisma Studio

v4.1.0

Compare Source

🌟 Help us spread the word about Prisma by starring the repo or tweeting about the release. 🌟

Upgrading to Prisma 4

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!

Major improvements
Ordering by nulls first and last support (Preview)

In this release, we're adding support for choosing how to sort null values in a query.

To get started, enable the orderByNulls Preview feature flag in your Prisma schema:

 generator client {
   provider        = "prisma-client-js"
   previewFeatures = ["orderByNulls"]
 }

Next, run prisma generate to re-generate Prisma Client. You will now have new fields you can now use to order null values:

await prisma.post.findMany({
  orderBy: {
    updatedAt: { 
      sort: 'asc',
      nulls: 'last'
    },
  },
})

Learn more in our documentation and don't hesitate to share your feedback in this issue.

Fixed memory leaks and CPU usage in Prisma Client

In this release, we've fixed the following issues experienced when setting up and tearing down Prisma Client while running tests:

  1. Prisma Client now correctly releases memory on Prisma Client instances that are no longer being used. Learn more in this GitHub issue
  2. Reduced CPU usage spikes when disconnecting Prisma Client instances while using Prisma Client. You can learn more in this GitHub issue

These fixes will allow you to run your tests a little faster!

Prisma Studio improvements

We're refining the experience when working with Prisma studio with the following changes:

  1. An always visible filter panel and functionality to clear all filters at once

  1. Improved relationship model view with more visible buttons

Let us know what you think, and in the event, you run into any issues, please create a GitHub issue

Fixes and improvements
Prisma
Prisma Client
Prisma Migrate
Language tools (e.g. VS Code)
@​prisma/engines npm package
Credits

Huge thanks to @​shian15810, @​zifeo, @​lodi-g, @​Gnucki, @​apriil15 for helping!

💼 We're hiring!

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.

📺 Join us for another "What's new in Prisma" livestream

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.

v4.0.0

Compare Source

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. 🌟

Major improvements

Here's a TL;DR:

  • Preview features moved to General Availability
    • extendedIndexes
    • filterJson
    • improvedQueryRaw
  • Improvements to the Prisma Schema
    • Defaults values for scalar lists (arrays)
    • Improved default support for embedded documents in MongoDB
    • Explicit unique constraints for 1:1 relations
    • Removed support for usage of references on implicit m:n relations
    • Enforcing uniqueness of referenced fields in the references argument in 1:1 and 1:m relations for MySQL
    • Removal of undocumented support for the type alias
    • Removal of the sqlite protocol for SQLite URLs
    • Better grammar for string literals
  • New Prisma Client APIs
    • findUniqueOrThrow
    • findFirstOrThrow
  • General improvements
    • Deprecating rejectOnNotFound
    • Fix rounding errors on big numbers in SQLite
    • DbNull, JsonNull, and AnyNull are now objects
    • Prisma Studio updates
    • Dropped support for Node 12
    • New default sizes for statement cache
    • Renaming of @prisma/sdk npm package to @prisma/internals
    • Removal of the internal schema property from the generated Prisma Client
extendedIndexes is now Generally Available

Starting 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 @@&#8203;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:

Sort, sort order, and length

The length argument is available on MySQL on the @id, @@&#8203;id, @unique, @@&#8203;unique, and @&#8203;@&#8203;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, @@&#8203;unique, and @@&#8203;index fields. SQL Server also allows it on @id and @@&#8203;id.

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model Post {
  title      String   @&#8203;db.VarChar(300)
  abstract   String   @&#8203;db.VarChar(3000)
  slug       String   @&#8203;unique(sort: Desc, length: 42) @&#8203;db.VarChar(3000)
  author     String
  created_at DateTime

  @&#8203;@&#8203;id([title(length: 100), abstract(length: 10)])
  @&#8203;@&#8203;index([author, created_at(sort: Desc)])
}
Hash indexes for PostgreSQL
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model A {
  id    Int @&#8203;id
  value Int  
  
  @&#8203;@&#8203;index([value], type: Hash)
}
GIN, GiST, SP-GiST and BRIN indexes for PostgreSQL
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Post {
  id      Int     @&#8203;id
  title   String
  content String?
  tags    Json?

  @&#8203;@&#8203;index([tags], type: Gin)
}
SQL Server index clustering
datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

model Post {
  id      Int     @&#8203;default(autoincrement()) @&#8203;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 Available

This 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 Available

Prisma 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:

1. Scalar values are de-serialized as their correct JavaScript types

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
2. PostgreSQL type-casts

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.

Defaults values for scalar lists (arrays)

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      @&#8203;id @&#8203;default(autoincrement())
  posts          Post[]
  favoriteColors String[] @&#8203;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.

Improved default support for embedded documents in MongoDB

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  @&#8203;id @&#8203;default(auto()) @&#8203;map("_id") @&#8203;db.ObjectId
  name   String  @&#8203;unique
  photos Photo[]
}

type Photo {
  height Int    @&#8203;default(200)
  width  Int    @&#8203;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.

Explicit unique constraints for 1:1 relations

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      @&#8203;id @&#8203;default(autoincrement())
  profile   Profile? @&#8203;relation(fields: [profileId], references: [id])
  profileId Int?     @&#8203;unique // <-- include this explicitly
}

model Profile {
  id   Int   @&#8203;id @&#8203;default(autoincrement())
  user User?
}

⚠️ Breaking change: Refer to our upgrade path for a detailed explanation and steps to follow.

Removed support for usage of references on implicit m:n relations

This release removes the usage of the references argument, which was previously optional when using m:n relations.

model Post {
  id         Int        @&#8203;id @&#8203;default(autoincrement())
-  categories Category[] @&#8203;relation("my-relation", references: [id])
+  categories Category[] @&#8203;relation("my-relation")
}

model Category {
  id    Int    @&#8203;id @&#8203;default(autoincrement())
-  posts Post[] @&#8203;relation("my-relation", references: [id]) 
+  posts Post[] @&#8203;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.

Enforcing uniqueness of referenced fields in the references argument in 1:1 and 1:m relations for MySQL

From 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.

Removal of undocumented support for the type alias

With 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.

Removal of the sqlite protocol for SQLite URLs

Starting 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.

Better grammar for string literals

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.

New Prisma Client APIs: 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 found
  • findFirstOrThrow – retrieves the first record in a list as findFirst but throws a RecordNotFound exception when no record is found

Here's an example of usage of the APIs:

const user = await prisma.user.findUniqueOrThrow({
  where: {
    email: "alice@prisma.io",
  },
})

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.

Deprecating 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.

Fix rounding errors on big numbers in SQLite

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 objects

Previously, 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 '@&#8203;prisma/client'
const prisma = new PrismaClient()

const dbNull = "DbNull" // this string could come from anywhere!

await prisma.log.findMany({
  data: {
    meta: dbNull,
  },
})
Expand to view the underlying Prisma schema
model Log {
  id   Int  @&#8203;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 '@&#8203;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.

Prisma Studio updates

We've refined the experience when working with Prisma Studio with the following changes:

  • Including a confirmation dialog before deleting records
  • Adding a shortcut copy action on a cell – CMD + C on MacOS or Ctrl + C on Windows/ Linux
Dropped support for Node 12

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

New default sizes for statement cache

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.

Renaming of @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.

Removal of the internal schema property from the generated Prisma Client

We'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.

Fixes and improvements

Prisma

Configuration

📅 Schedule: Branch creation - "after 10pm every weekday,before 5am every weekday,every weekend" (UTC), Automerge - At any time (no schedule defined).

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about these updates again.


  • If you want to rebase/retry this PR, click this checkbox.

This PR has been generated by Mend Renovate. View repository job log here.

@renovate renovate bot added the dependencies label Jul 3, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants