prisma

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

APACHE-2.0 License

Downloads
64.3M
Stars
39.2K
Committers
259

Bot releases are hidden (Show)

prisma - 4.2.0

Published by ruheni about 2 years ago

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

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.

prisma - 4.1.1

Published by Jolg42 about 2 years ago

prisma - 4.1.0

Published by ruheni over 2 years ago

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

prisma - 4.0.0

Published by ruheni over 2 years ago

We're excited to share the 4.0.0 stable release today. 🎉

Prisma 4.0.0 features a variety of improvements across Prisma Migrate, Prisma schema, and Prisma Client. These changes will impact most Prisma users, particularly those who used some of our most popular Preview features around advanced index management, raw SQL queries, and filtering rows by properties of JSON.

As this is a major release, we included many breaking bug fixes and other enhancements, but we believe upgrading is worthwhile. You can learn about upgrading in our Prisma 4 Upgrade guide and the Prisma 4 Upgrade video.

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

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 @@index attribute to define the kind of index that should be created in your database. You can configure the following indexes in your Prisma Schema:

The length argument is available on MySQL on the @id, @@id, @unique, @@unique, and @@index fields. It allows Prisma to support indexes and constraints on String with a TEXT native type and Bytes types.

The sort argument is available for all databases on the @unique, @@unique, and @@index fields. SQL Server also allows it on @id and @@id.

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

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

  @@id([title(length: 100), abstract(length: 10)])
  @@index([author, created_at(sort: Desc)])
}
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model A {
  id    Int @id
  value Int  
  
  @@index([value], type: Hash)
}
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Post {
  id      Int     @id
  title   String
  content String?
  tags    Json?

  @@index([tags], type: Gin)
}
datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

model Post {
  id      Int     @default(autoincrement()) @id(clustered: false)
  title   String
  content String?
}

Refer to our docs to learn how you can configure indexes in your Prisma schema and the supported indexes for the different databases.

⚠️ Breaking change: If you previously configured the index properties at the database level, refer to the upgrade guide for a detailed explanation and steps to follow.

filterJson is now Generally 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:

Raw queries now deserialize scalar values to their corresponding JavaScript types.

Note: Types are inferred from the values and not from the Prisma Schema types.

Here's an example query and response:

const res = await prisma.$queryRaw`SELECT bigint, bytes, decimal, date FROM "Table";`
console.log(res) 
// [{ bigint: BigInt("123"), bytes: Buffer.from([1, 2]), decimal: new Prisma.Decimal("12.34"), date: Date("<some_date>") }]

Below is a table that recaps the serialization type-mapping for raw results:

Database Type JavaScript Type
Text String
Int32 Number
Int64 BigInt
Float Number
Double Number
Numeric Decimal
Bytes Buffer
Json Object
DateTime Date
Date Date
Time Date
Uuid String
Xml String

Previously, PostgreSQL type-casts were broken. Here's an example query that used to fail:

await prisma.$queryRaw`SELECT ${1.5}::int as int`;
// Before: db error: ERROR: incorrect binary data format in bind parameter 1
// After: [{ int: 2 }]

You can now perform some type-casts in your queries as follows:

await prisma.$queryRaw`SELECT ${2020}::float4, (NOW() - ${"1 day"}::interval), ${"2022-01-01 00:00:00"}::timestamptz;`

A consequence of this fix is that some subtle implicit casts are now handled more strictly and would fail. Here's an example that used to work but won't work anymore:

await prisma.$queryRaw`SELECT LENGTH(${42});`
// ERROR: function length(integer) does not exist
// HINT: No function matches the given name and argument types. You might need to add explicit type casts.

The LENGTH PostgreSQL function only accept text as input. Prisma used to silently coerce 42 to text but won’t anymore. As suggested by the hint, cast 42 to text as follows:

await prisma.$queryRaw`SELECT LENGTH(${42}::text);`

Refer to our docs to learn more on raw query type mappings in Prisma.

⚠️ Breaking change: To learn how you can smoothly upgrade to version 4.0.0, refer to our upgrade guide: Raw query type mapping: scalar values are now deserialized as their correct JavaScript types and Raw query mapping: PostgreSQL type-casts.

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      @id @default(autoincrement())
  posts          Post[]
  favoriteColors String[] @default(["red", "blue", "green"])
}

To learn more about default values for scalar lists, refer to our docs.

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

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

type Photo {
  height Int    @default(200)
  width  Int    @default(100)
  url    String
}

Refer to our docs to learn more on default values for required fields on composite types.

⚠️ Breaking change: Refer to our upgrade guide for detailed explanation and steps when working with default fields on composite types in MongoDB from version 4.0.0.

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

model Profile {
  id   Int   @id @default(autoincrement())
  user User?
}

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

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        @id @default(autoincrement())
-  categories Category[] @relation("my-relation", references: [id])
+  categories Category[] @relation("my-relation")
}

model Category {
  id    Int    @id @default(autoincrement())
-  posts Post[] @relation("my-relation", references: [id]) 
+  posts Post[] @relation("my-relation")
}

This is because the only valid value for references was id, so removing this argument clarifies what can and cannot be changed.

Refer to our docs to learn more about implicit m:n relations.

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

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: "[email protected]",
  },
})

user.email //  You don't need to check if the user is null

The APIs will be convenient for scripts API routes where you're already handling exceptions and want to fail fast.

Note: Please use the APIs with care. If you use these APIs, add the proper guardrails to your application.

Refer to the API reference in our docs to learn how findUniqueOrThrow and findFirstOrThrow differ from findUnique and findFirst respectively.

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 '@prisma/client'
const prisma = new PrismaClient()

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

await prisma.log.findMany({
  data: {
    meta: dbNull,
  },
})

model Log {
  id   Int  @id
  meta Json
}

Prisma 4 resolves this using constants guaranteed to be unique to prevent this kind of inconsistent queries.

You can now read, write, and filter JSON fields as follows:

import { PrismaClient, Prisma } from '@prisma/client'
const prisma = new PrismaClient()


await prisma.log.create({
  data: {
    meta: Prisma.DbNull,
  },
})

We recommend you double-check queries that use Json after upgrading to Prisma 4. Ensure that you use the Prisma.DbNull, Prisma.JsonNull, and Prisma.AnyNull constants from Prisma Client, not string literals.

Refer to the Prisma 4 upgrade guide in case you run into any type errors.

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

Credits

Huge thanks to @shian15810, @zifeo, @ever0de, @givensuman, @peter-gy, @rushabhhere, @flatplate, @njmaeff, @tnzk, @DePasqualeOrg, @roboncode, @jacobhq for helping!

📺 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, June 30 at 5 pm Berlin | 8 am San Francisco.

📺 Learn how to upgrade in our webinar on July 12th

We're going to host a dedicated webinar with Prisma engineers to talk about the upgrade process. If you're unsure whether the breaking changes of this release affect you, be sure to not miss this livestream.

The stream takes place on YouTube on Tuesday, July 12 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.15.2

Published by millsp over 2 years ago

Today, we are issuing the 3.15.2 patch release.

Fixes

In order to use the Prisma Data Proxy via Prisma Client, you need to generate it with prisma generate --data-proxy as described in our documentation. We are introducing PRISMA_GENERATE_DATAPROXY="true" as an additional way to do the same thing, but via an environment variable.

This is necessary, for example, to reliably deploy a Prisma Client for Data Proxy on Vercel Serverless Functions, where it can be hard to update the build command to run prisma generate --data-proxy. Starting with this version you can just set PRISMA_GENERATE_DATAPROXY="true" as an environment variable the Vercel project settings.

If you are unfamiliar with the Data Proxy, read how to get started.

prisma - 3.15.1

Published by Jolg42 over 2 years ago

prisma - 3.15.0

Published by ruheni over 2 years ago

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

Major improvements

Improvements to Prisma Client for Data Proxy

In this release, we're shipping a couple of improvements to Prisma Client for Data Proxy.

The Prisma Data Proxy provides connection management and pooling for database connections for efficiently scaling database connections in serverless environments. The Prisma Client for Data Proxy provides support for connecting to the Prisma Data Proxy using HTTP.

We introduced this feature in version 3.3.0 and constantly shipped features, fixes, and improvements.

One of the changes in this release is improving the Prisma Client for the Data Proxy generation step.

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

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

You can generate Prisma Client for the Data Proxy it by using the --data-proxy flag:

npx prisma generate --data-proxy

We also updated how you can run Prisma Client using the Data Proxy in Cloudflare Workers and Edge environments. You can now use @prisma/client/edge instead of @prisma/client in your application.

import { PrismaClient } from '@prisma/client/edge'

To learn more, check out our documentation.

Prisma Client Metrics is now in Preview

Metrics is a new Preview feature that allows you to monitor how Prisma Client interacts with your database. Metrics expose a set of counters, gauges, and histograms that can be labeled and piped into an external monitoring system like Prometheus or StatsD.

You can use metrics in your project to help diagnose how your application's number of idle and active connections changes with counters, gauges, and histograms.

To get started using metrics in your project, enable the Preview feature flag in your Prisma schema:

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

You can then get started using metrics in your project:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

const metrics = await prisma.$metrics.json()
console.log(metrics)

To learn more, check out the metrics documentation. Give it a try and let us know what you think.

Regression

Azure SQL on MacOS

This release includes a known regression when connecting to Azure SQL from MacOS only and will be resolved soon. Follow this issue for updates and resolution.

Fixes and improvements

migrate reset returns with a non-0 exit code if the seed script returns with a non-0 exit code

This will help user scripts know more about the success of the command, but might break existing scripts.

Prisma

Prisma Client

Credits

Huge thanks to @shian15810, @zifeo, @ever0de, @rushabhhere for helping!

Prisma Day

Prisma Day is back this year, and it'll be on June 15 - 16 at the James June Sommergarten in Berlin. Join us in-person or online for talks and workshops on modern application development and databases. Come and meet and chat with the team behind the Prisma ORM and Prisma Data Platform.

💼 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 through 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, June 9 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.14.0

Published by ruheni over 2 years ago

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

Major improvements

CockroachDB connector is now Generally Available!

We are proud to announce the CockroachDB connector is now stable and Generally Available. The connector was built in joined efforts with the team at Cockroach Labs and comes with full Prisma Client and Prisma Migrate support.

If you're upgrading from Prisma version 3.9.0+ or the PostgreSQL connector, you can now run npx prisma db pull and review the changes to your schema. To learn more about CockroachDB-specific native types we support, refer to our docs.

To learn more about the connector and how it differs from PostgreSQL, head to our documentation.

PostgreSQL GIN, GiST, SP-GiST, and BRIN indexes support (Preview)

We introduced the extendedIndexes Preview feature in version 3.5.0, and we have been adding new configuration options for indexes. We've expanded index type support with the GIN, GiST, SP-GiST, and BRIN indexes in this release.

To make use of an index type, you can update your Prisma schema by providing the type argument to the @@index attribute:

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

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

model Post {
  id      Int     @id
  title   String
  content String?
  tags    Json?

  @@index([tags], type: Gin)
}

The following SQL will be generated in your migration when you run prisma migrate dev:

CREATE TABLE "Post" (
    "id" INTEGER NOT NULL,
    "title" TEXT NOT NULL,
    "content" TEXT,
    "tags" JSONB,
    CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
);

CREATE INDEX "Post_tags_idx" ON "Post" USING GIN ("tags");

To learn more about configuring index types in your schema, refer to our documentation.

Improved queryRaw API

In this release, we made improvements to the SQL raw API. Some improvements are breaking and will be available behind the new improvedQueryRaw Preview feature flag.

The improvedQueryRaw Preview feature solves most of the issues faced when working with the raw API. We would encourage you to turn on the Preview feature flag, try out the new API, and let us know how we can make it even better.

You can enable the Preview feature in your Prisma schema as follows:

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

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

Here's a list of the improvements improvedQueryRaw comes with:

1. Raw scalar values are deserialized as their correct JavaScript types

Prisma Client queries such as findMany deserialize database scalar values to their corresponding JavaScript types. For example, a DateTime value is deserialized as a JavaScript Date, and a Bytes would be deserialized as a JavaScript Buffer.

Raw queries now implement the same behavior when the improvedQueryRaw Preview feature flag is enabled.

⚠️ This change is not yet available in the SQLite connector.

The types of values from the database will be used instead of the types in the Prisma schema. Here's an example query and response:

const res = await prisma.$queryRaw`SELECT bigint, bytes, decimal, date FROM "Table";`
console.log(res) 
// [{ bigint: BigInt("123"), bytes: Buffer.from([1, 2]), decimal: new Prisma.Decimal("12.34"), date: Date("<some_date>") }]

Here's a table that recaps the serialization type-mapping for raw results:

Database Type Javascript Type
Text String
Int32 Number
Float Number
Double Number
Int64 BigInt
Numeric Decimal
Bytes Buffer
Json Object
DateTime Date
Date Date
Time Date
Uuid String
Xml String

2. PostgreSQL type-casts

We've also fixed a lot of PostgreSQL type-casts that were broken by enabling the improvedQueryRaw Preview feature flag.

Here's an example of a query that used to fail:

await prisma.$queryRaw`SELECT ${1.5}::int as int`;
// Before: db error: ERROR: incorrect binary data format in bind parameter 1
// After: [{ int: 2 }]

You can now perform some more type-casts in your queries:

await prisma.$queryRaw`SELECT ${2020}::float4, (NOW() - ${"1 day"}::interval), ${"2022-01-01 00:00:00"}::timestamptz;`

A consequence of this fix is that some subtle implicit casts are now handled more strictly and would fail. Here's an example that used to work but won't work anymore under the improvedQueryRaw feature flag:

await prisma.$queryRaw`SELECT LENGTH(${42});`
// ERROR: function length(integer) does not exist
// HINT: No function matches the given name and argument types. You might need to add explicit type casts.

The LENGTH PostgreSQL function only accept text as input. Prisma used to coerce 42 to text silently, but won’t anymore. As suggested by the hint, cast 42 to text as follows:

await prisma.$queryRaw`SELECT LENGTH(${42}::text);`

3. Query parameters are correctly sent to the database

This improvement is available without the improvedQueryRaw Preview feature flag.

Before this release, query parameters of type BigInt, Bytes, and Decimal were incorrectly sent to the database leading to instances of unexpected inserts. Passing the types as query parameters now works:

await prisma.$executeRaw`INSERT INTO "Table" ("bigint", "bytes", "decimal") VALUES (${BigInt("123")}, ${Buffer.from([1, 2, 3])}, ${new Prisma.Decimal("12.23")});`

Fixes and improvements

Prisma Client

Prisma

Prisma Migrate

Language tools (e.g. VS Code)

Credits

Huge thanks to @ever0de, @flatplate, @njmaeff, @tnzk, @DePasqualeOrg for helping!

Prisma Day

Prisma Day is back this year, and it'll be on June 15 - 16 at the JamesJune Sommergarten in Berlin. Join us in-person or online for talks and workshops on modern application development and databases. Come and meet and chat with the team behind the Prisma ORM and Prisma Data Platform.

💼 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 hiring for a number of roles: Technical Support Engineer, Back-end Engineer: Prisma Data Platform, and a Developer Advocate(Frontend/ Fullstack). You can find more jobs we're hiring for on our jobs page.

Feel free to read through the job descriptions and apply using the links provided.

📺 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, May 12 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.13.0

Published by ruheni over 2 years ago

Today, we are excited to share the 3.13.0 stable release 🎉

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

Major improvements

migrate diff and db execute are now Generally Available!

We released two new Preview CLI commands in version 3.9.0prisma migrate diff and prisma db execute – to enable our users to create and understand migrations and build their workflows using the commands.

We're proud to announce that the commands are now Generally Available and can now be used without the --preview-feature flag. 🎉

The prisma migrate diff command creates a diff of your database schema, Prisma schema file, or the migration history. All you have to do is feed the command with a schema from state and a schema to state to get an SQL script or human-readable diff.

In addition to prisma migrate diff, prisma db execute is used to execute SQL scripts against a database. You can directly execute prisma migrate diff's output using prisma db execute --stdin.

Both commands are non-interactive, so it's possible to build many new workflows such as forward and backward migrations with some automation tooling. Take a look at our documentation to learn some of the popular workflows these commands unlock:

Let us know what tools, automation, and scripts you build using these commands.

SQL Server index clustering (Preview)

In version 3.5.0, we introduced the extendedIndexes Preview feature which we have constantly been adding new configuration options for indexes. In this release, we added support for enabling or disabling index/constraint clustering in SQL Server.

By default, indexes will be clustered by default. You can update this in your schema as follows to disable index clustering:

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

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

model Post {
  id      Int     @default(autoincrement()) @id(clustered: false)
  title   String
  content String?
}

The following SQL will be generated in your migration when you run prisma migrate dev

CREATE TABLE [Post] (
  id INT NOT NULL,
  [title] VARCHAR(255) NOT NULL,
  [content] NVARCHAR(1000),
  CONSTRAINT [Post_pkey] PRIMARY KEY NONCLUSTERED (id)
)

If you've enabled the extendedIndexes Preview feature, this is potentially a breaking change. Refer to our documentation to learn how you can upgrade from a previous version.

Updated native types for CockroachDB (Preview)

We have revamped the native types available in the CockroachDB connector. We initially re-used the PostgreSQL native types because they were close enough, but we have now adapted our list of the supported native types to match what CockroachDB supports.

If you are already using CockroachDB in your project, you can run prisma db pull to update all the native types in your Prisma schema. Refer to our documentation for the complete list of all CockroachDB native types.

OpenSSL 3.0 Support

We're excited to announce that version 3.13.0 now supports OpenSSL 3.0. Operating systems such as Ubuntu 22.04 default to OpenSSL 3.0, and when running prisma generate, you would run into the following error:

Error: Unknown binaryTarget debian-openssl-3.0.x

If you've run into a similar error, bump up to the latest Prisma version and give it another try!

Fixes and improvements

Prisma Client

Prisma

Language tools (e.g. VS Code)

Prisma Engines

Credits

Huge thanks to @ever0de, @jacobhq, @dkantereivin, @CommanderRoot 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 Senior Software Engineer (Prisma Data Platform).

Feel free to read through 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, April 28 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.12.0

Published by ruheni over 2 years ago

Today, we are excited to share the 3.12.0 stable release 🎉

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

Major improvements and new features

MongoDB is now Generally Available

If you’ve been using MongoDB since it was in Preview, we'd like to say: Thank you! Your testing and feedback has been essential during the preview phase, and our MongoDB support is much better because of it.

Today we’re proud to announce that MongoDB is now stable and production-ready. After upgrading to 3.12.0, you can remove the MongoDB preview flag in your schema:

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

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

We’ve been working hard towards this day ever since we launched MongoDB in Preview in July 2021.

Here are some of the feature highlights we developed over this period:

  • Expressive and type-safe operations for querying MongoDB embedded documents
  • Thorough introspection support for using Prisma with existing MongoDB databases
  • Declarative index management right from your Prisma Schema with db push
  • Powerful raw query APIs to help you incrementally migrate to Prisma

You can learn about these features in the release blog post, and more, in our freshly brewed MongoDB Guide. For newcomers to Prisma with MongoDB, we recommend you check out our Getting Started Guide.

To celebrate this milestone, we invite you to join Prisma’s MongoDB Launch Week starting on April 25th. Enjoy a jam-packed week of exclusive workshops with plenty of opportunities to win free MongoDB Atlas credits and swag. It’s free to sign-up and available anywhere you have an internet connection.

🚨 Please be aware that we made a few breaking changes to tie up loose ends before General Availability:

We made some changes in the 3.11.1 patch release in case you missed it.

Index support on composite type fields

We also added support for adding indexes on embedded document fields in MongoDB. This means that you can now define a normal, unique, or full-text index in your schema.

type Address {
  street String
  number Int
}

model User {
  id      Int     @id
  email   String
  address Address

  @@index([email, address.number])  /// normal index
  @@unique([email, address.street])  /// unique index
  @@fulltext([email, address.street]) /// full-text index
}

Note: Prisma Client does not yet fully support the feature for now. This will be rolled out in a future release.

Improved Connection Pooling Resiliency

In 3.12.0, we busted a ghost that has been bugging teams since the early days of the Prisma ORM. Under certain amounts of load, some people reported that the connection pool would sometimes drop connections or deadlock and not recover.

After many sightings and a lot of head-scratching, we were finally able to reproduce the issue. This allowed us to narrow down the problem to one of our dependencies and fix the problem.

To read the nitty gritty details of the problem and our solution, check out this issue.

Fixes and improvements

Prisma Client

Prisma

Prisma Migrate

Language tools (e.g. VS Code)

Prisma Engines

Credits

Huge thanks to @ever0de, @chronotc, @hayes, @maddhruv, @jasimon, @codesee-maps[bot], @andyrichardson, @xnerhu, @Josh-a-e, @dusandz for helping!

💼 We're hiring!

If you're interested in joining our growing team to help empower developers build data-intensive applications, Prisma is the place for you.

We're looking for a Developer Success Engineer and Back-end Engineer: Prisma Data Platform.

Feel free to read through the job descriptions and apply using the links provided.

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

prisma - 3.11.1

Published by dpetrick over 2 years ago

Today, we are issuing the 3.11.1 patch release.

MongoDB (Preview)

Breaking: Filters no longer return undefined fields by default

In 3.11.1, we've changed what data is returned when filtering MongoDB documents on undefined fields. The new rule is that undefined fields are excluded by default unless explicitly filtered for. This allows you to query for undefined and null values separately.

Let's take a look at a concrete example. Given the following Prisma schema:

model Address {
    id     Int    @id @map("_id")
    city   String
    street String? // Note that street is optional
}

For Mongo, optional fields can either be null or undefined (absent). The following documents are all valid for the schema above:

{ "_id": 1, "city": "San Fransisco", "street": "Market st." }
{ "_id": 2, "city": "Seattle", "street": null }
{ "_id": 3, "city": "Chicago" }

Prior to 3.11.1, if you queried for where: { street: null }, you'd get _id: 2 and _id: 3. In 3.11.1, you'll only get _id: 2. The ability to also query for the missing fields has also been added. For details, refer to the new isSet below to learn more.

There are a few exceptions to this new default:

  • A having filter on an aggregated field will return undefined fields. This is because aggregation on undefined fields yields null, not undefined, thus matching the filter.
  • Filters on undefined to-many relations (e.g., the backing array of a many-to-many is undefined) will currently include those relations in the result set.

New isSet filter operation

To compensate for missing fields on documents no longer being returned by the filters above, we’ve added a new isSet: bool filter. This filter can be used to include fields that are undefined on documents.

Using the example above, to include the undefined fields, you can use an OR:

await prisma.address.findMany({
  where: {
    OR: [
      { street: { isSet: false } },
      { street: null }
    ]
  }
})

The isSet operation has been added to all scalar and embedded fields that are optional.

New unset operation

In 3.11.1, you can also remove a field with the unset operation.

Using the example above, let's write a query to remove the street field:

await prisma.address.update({
  where: {
    id: 10,
  },
  data: {
    street: {
      unset: true,
    },
  },
})

This effectively sets the street field to undefined in the database.

New updateMany operation

We now support updating embedded documents that match specific criteria.

For example, given the following schema:

model Product {
  id          Int  @id @map("_id")
  name        String  @unique
  photos      Photo[]
}

type Photo {
  height Int    @default(200)
  width  Int    @default(100)
  url    String
}

Let's update the photo with a url of 1.jpg to 2.png:

const product = prisma.product.update({
  where: {
    id: 10,
  },
  data: {
    photos: {
      updateMany: {
        where: {
          url: '1.jpg',
        },
        data: {
          url: '2.png',
        },
      },
    },
  },
})

New deleteMany operation

Similar to updateMany, you can also remove embeds that match specific criteria.

Using the Prisma Schema above, let's delete all photos with a height of 100:

const product = prisma.product.update({
  where: {
    id: 10,
  },
  data: {
    photos: {
      deleteMany: {
        where: {
          height: 100,
        },
      },
    },
  },
})
prisma - 3.11.0

Published by Jolg42 over 2 years ago

Today, we are excited to share the 3.11.0 stable release 🎉

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

Major improvements and new features

Experimental support for Embedded Document Filters

In the previous release, we added embedded document support for creates, updates, and deletes. In version 3.11.0, we’re adding the ability to filter embedded documents.

Given the following schema:

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

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

model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  photos Photo[]
}

model Order {
  id              String   @id @default(auto()) @map("_id") @db.ObjectId
  shippingAddress Address
  billingAddress  Address?
}

type Photo {
  height Int
  width  Int
  url    String
}

type Address {
  street String
  city   String
  zip    String
}

You can now filter within an embedded document:

// find all orders with the same shipping address
const orders = await prisma.order.findMany({
  where: {
    shippingAddress: {
      equals: {
        street: "555 Candy Cane Lane",
        city: "Wonderland",
        zip: "52337",
      },  
    },
  },
})

You can also filter on a "contains many" relationship:

// find all products that don't have photos
const product = prisma.product.findMany({
  where: {
    photos: {
      isEmpty: true
    }
  },
})

This scratches the surface of what's possible. For a complete list of available operations, have a look at our documentation. Please share your feedback in this issue.

Ordering by embedded documents is in Preview

In addition to filtering, Prisma version 3.11.0 now supports sorting by an embedded document.

Using the example schema above, you can sort orders by their zip code:

// sort orders by zip code in ascending order
const orders = await prisma.order.findMany({
  orderBy: {
    shippingAddress: {
      zip: "asc",
    },
  },
})

Learn more about this feature in our documentation and don’t hesitate to reach out in this issue.

MongoDB query logging support

In this release, we’ve added the ability to log MongoDB queries. You can enable query logging in the PrismaClient constructor:

const prisma = new PrismaClient({
  log: [
    {
      emit: 'event',
      level: 'query',
    },
  ]
})

prisma.$on('query', (e) => console.log(e.query))

After enabling query logging, you'll start to see logs that resemble this in your console:

db.User.deleteMany({ _id: ( $in: [ “62261e0b18139c6099ba7097”, ], }, }) 
db.User.deleteMany({ _id: ( $in: [ “6226277a96069500743edcf9”, ], }, })

The logs output by Prisma have the same format as the mongosh console, so you can pipe the queries from your logs directly into your shell.

MongoDB introspection update

We've updated the type inference behavior for MongoDB on introspection.

Prisma samples a field's data to select an appropriate type on introspection. In the past, Prisma picked the type used most often for fields with data with multiple types. However, this could cause problems when retrieving mixed data during runtime and throw exceptions, such as Prisma Studio or in Prisma Client queries.

From 3.11.0, Prisma defaults to the Json type to all fields with mixed data types instead. Additionally, Prisma will still show a warning on the console and add a comment to the introspected Prisma schema so it is clear where such cases occur and that you can do something to fix them.

Prisma Client logger revamp

In 3.11.0, we’ve rewritten our internal logger to reduce lock contention and enable future features like tracing. This is the first of many upcoming changes to improve the Prisma Client’s throughput, so if you were running into an upper limit on query performance, it’s time to update Prisma Client and give it a try!

If you're running into query performance issues, please open an issue or connect with us on Slack.

CockroachDB now supports migrations (Preview)

We're excited to announce Preview support for migrations for CockroachDB. You can now evolve your Prisma schema and propagate the changes to your database using Prisma Migrate.

Give the feature a try and let us know what you think in this issue.

Detecting state of a diff with migrate diff using exit code

Prisma version 3.11.0 includes a new --exit-code flag to the migrate diff command to detect the state of a diff in several ways.

You can use the flag as follows:

npx prisma migrate diff --preview-feature \
--exit-code \
--from-[...] \
--to-[...]

Here's a list of the default and changed behavior of the error codes:

## Default behavior of exit codes
0: Returned when the diff is empty or non-empty
1: Returned on error

## Changed behavior when --exit-code is used
0: Returned when the diff is empty
1: Returned on error
2: Returned when the diff is non-empty

Read about it in the reference documentation.

Fixes and improvements

Prisma

Prisma Client

Prisma Migrate

Language tools (e.g. VS Code)

Prisma Engines

Credits

Huge thanks to @hayes, @maddhruv, @jasimon for helping!

📺 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, March 17 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.10.0

Published by ruheni over 2 years ago

Today, we are excited to share the 3.10.0 stable release 🎉

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

Major improvements and new features

We are working towards a stable release of MongoDB and are shipping lots of improvements. All the new features and changes in this release therefore only apply to the MongoDB connector. Take a closer look if you are using the Preview of MongoDB as some of the changes are breaking.

Embedded documents support is now in Preview

We're super excited to announce that Prisma version 3.10.0 supports reading and modifying embedded documents. Embedded documents will provide access to a new type keyword in your Prisma schema that you can use to define composite types.

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

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

model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  name   String
  photos Photo[]
}

type Photo {
  height Int
  width  Int
  url    String
}

Given the schema above, you can now read and write to the embedded photos array:

// Create a new product with an embedded list of photos
const product = await prisma.product.create({
  data: {
    name: "Forest Runners",
    // Create an embedded list of photos in the product
    photos: [
      { height: 100, width: 200, url: "1.jpg" },
      { height: 300, width: 400, url: "2.jpg" },
    ],
  },
})

Best of all, the query is entirely type-safe! This scratches the surface of what's possible with embedded documents. You can read further in our documentation.

If you run into anything, feel free to open an issue, and we’ll give you a hand!

Introspection of embedded documents is now enabled by default

We added Preview support for Introspection of embedded documents in version 3.4.0 and are now activating it for all users. Running prisma db pull against your MongoDB database will generate type definitions within your Prisma schema.

When introspecting your database, you can switch off the depth with --composite-type-depth=0, or limit it with, for example, --composite-type-depth=2.

Feel free to drop your feedback on the feature on GitHub.

@default(dbgenerated()) is now replaced with @default(auto())

The original purpose of dbgenerated is to support SQL expressions Prisma doesn’t understand yet. However, MongoDB doesn’t have a concept of default value expressions like SQL does. We took this opportunity to simplify how we handle the default values in MongoDB:

model Post {
-  id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
+  id String @id @default(auto()) @map("_id") @db.ObjectId
}

Many-to-Many relations now require a references argument

Prisma version 3.10.0 now enforces all arguments in a MongoDB many-to-many relation. This means a @relation attribute must define fields and references arguments on both sides.

The fields argument must point to a scalar field in the same model, and this scalar field must be an array. The references arguments must point to a scalar field in the opposite model, and it must be a singular type of the same base type as the referencing array on the other side.

model Post {
  id           String     @id @map("_id") @default(auto()) @db.ObjectId
  category_ids String[]   @db.ObjectId
- categories   Category[] @relation(fields: [category_ids])
+ categories   Category[] @relation(fields: [category_ids], references: [id])
}
    
model Category {
  id       String   @id @map("_id") @default(auto()) @db.ObjectId
  post_ids String[] @db.ObjectId
- posts    Post[]   @relation(fields: [post_ids])
+ posts    Post[]   @relation(fields: [post_ids], references: [id])
}

@db.Array(ObjectId) is now updated to @db.ObjectId

We've adjusted the Prisma schema format for scalar lists with native types (like lists of Object IDs). This will likely affect those with many-to-many relationships in MongoDB. We made this change to align MongoDB with our existing SQL databases better:

model Post {
  id          String     @id @default(auto()) @map("_id") @db.ObjectId
- categoryIDs String[]   @db.Array(ObjectId)
+ categoryIDs String[]   @db.ObjectId
  categories  Category[] @relation(fields: [categoryIDs], references: [id])
}

model Category {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId
- postIDs String[] @db.Array(ObjectId)
+ postIDs String[] @db.ObjectId
  posts   Post[]   @relation(fields: [postIDs], references: [id])
}

Fixes and improvements

Prisma Migrate

Prisma Client

Credits

Huge thanks to @andyrichardson, @xnerhu, @Josh-a-e, @dusandz, @hyochan, @cesconix, @benkroeger, @YassinEldeeb, @chenkie for helping!

📺 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, February 03 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.9.1

Published by Jolg42 over 2 years ago

prisma - 3.9.0

Published by Jolg42 over 2 years ago

Today, we are excited to share the 3.9.0 stable release 🎉

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

Major improvements and new features

Prisma Migrate improvements to troubleshoot migrations

Last year, we released Prisma Migrate for General Availability. Since then, we've gotten feedback from you to understand the challenges you experience building, testing, and deploying migrations.

We're thrilled to announce that we're introducing new CLI commands to improve the experience troubleshooting migrations:

  • prisma migrate diff
  • prisma db execute

The prisma migrate diff command creates a diff of your database schema, Prisma schema file, or the migration history. All you would have to do is feed the command with a schema from state and a schema to state to get an SQL script or human-readable diff in return.

As a companion to the prisma migrate diff, we also built prisma db execute to execute SQL scripts against a database. You can pipe the output from prisma migrate diff directly to prisma db execute.

Both commands are non-interactive, so it's possible to build many new workflows such as forward and backward migrations with some automation tooling.

Both commands are in Preview, and we are looking forward to learning how they work for you and how we could make them better.

You can learn about them here and give us feedback on the issue.

Preview support for CockroachDB

We are excited to announce Preview support for CockroachDB 🎉

CockroachDB is a distributed SQL database that shines in its ability to scale efficiently while maintaining developer agility and reducing operational overhead.

CockroachDB support in Prisma is the product of collaboration with the Cockroach Labs team, and with this release you can use Prisma in existing CockroachDB projects with introspection.

Raw query support for MongoDB

Prisma version 3.9.0 introduces raw queries to the MongoDB (Preview) connector. Raw queries help writing queries that Prisma doesn't support yet, such as:

// To find zero or more documents matching a filter
const result = await prisma.user.findRaw({
  filter: { age: { $gt: 25 } },
  options: { projection: { _id: false } },
})

// To perform aggregation operations on a collection
await prisma.user.aggregateRaw({
  pipeline: [
    { $match: { status: 'registered' } },
    { $group: { _id: '$country', total: { $sum: 1 } } },
  ],
})

// To run a command against the database
await prisma.$runCommandRaw({
  aggregate: 'User',
  pipeline: [
    { $match: { name: 'Bob' } },
    { $project: { email: true, _id: false } },
  ],
  explain: false,
})

The raw query API for MongoDB differs from Prisma's $queryRaw SQL API to handle some low-level differences between databases to give you a better API and developer experience.

Learn more about Prisma's new raw query API and how you can use it in our documentation.

Concurrency issues with Interactive Transactions

In 3.9.0, we fixed a number of issues around timeouts and rollbacks when there were concurrent reads and writes.

This is part of the Interactive Transactions preview release, so you'll need to enable the interactiveTransactions preview feature to enable this feature.

If you experienced timeouts or your interactive transactions weren't working quite as you expected, now's the time to upgrade and give it another go!

Learn more about Interactive Transactions in our documentation.

Fixes and improvements

Prisma Client

Prisma Migrate

Prisma Studio

Prisma Engines

Credits

Huge thanks to @dusandz, @hyochan, @cesconix, @benkroeger, @YassinEldeeb, @chenkie, @Akxe, @safareli for helping!

Change in release cadence

We're making a slight change to our release cadence to every 3 weeks from every 2 weeks.

📺 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, February 03 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.8.1

Published by millsp almost 3 years ago

Today, we are issuing the 3.8.1 patch release.

Fixes

prisma - 3.8.0

Published by Jolg42 almost 3 years ago

Today, we are excited to share the 3.8.0 stable release 🎉

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

Major improvements and new features

Full-text search support for MySQL is now in Preview 🚀

We're back from the holidays with a special treat for you.

Prisma now supports full-text search in MySQL. You can enable full-text support by adding the fullTextIndex and fullTextSearch Preview flags in your Prisma schema and defining @@fulltext() indexes on fields you'd like to use full-text search on.

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["fullTextIndex", "fullTextSearch"]
}

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

model Post {
  id     Int    @id @default(autoincrement())
  title  String @unique
  @@fulltext([title])
}

Run prisma db push or prisma migrate dev to update your database schema. Prisma Client will also be re-generated, enabling you to use full-text search in your application.

// search for titles that contain cat, but not fox
await prisma.post.findMany({
  where: {
    title: {
      search: "+cat -fox",
    },
  },
})

Learn more in our documentation.

dataProxy and interactiveTransactions Preview Features are now mutually exclusive

Before Prisma 3.8.0, Prisma $transaction queries would fail whenever the Data Proxy and Interactive Transactions Preview features were used together. The interactiveTransactions and dataProxy Preview flags cannot be used together in this release. Generating the Prisma Client when both Preview features are enabled will throw an error.

Fixed support for push when adding an element to an array in MongoDB

In 3.8.0, we fixed push support for ObjectIds on MongoDB.

Given the following schema:

model Course {
  id          String   @id @default(dbgenerated()) @map("_id") @db.ObjectId
  title       String
  students    String[] @db.Array(ObjectId)
}

You can now run the following query:

// Add a new student to the course
await prisma.course.update({
  where: {
    id: 1
  },
  data: {
    students: {
      push: new ObjectID("...")
    }
  }
})

A special thanks to Anthony Luzquiños for raising this issue!

Fixes and improvements

Prisma Migrate

Prisma Client

Language tools (e.g. VS Code)

Prisma Studio

Credits

Huge thanks to @hyochan, @cesconix for helping!

📺 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, January 13 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.7.0

Published by Jolg42 almost 3 years ago

Today, we are excited to share the 3.7.0 stable release 🎉

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

Major improvements

Referential actions support for MongoDB

In 3.7.0, we've added MongoDB support for onDelete and onUpdate to specify how you want to handle changes to relationships.

MongoDB does not support referential actions out of the box, but we can emulate this feature inside the Prisma Query Engine.

Given the following schema:

 model User {
   id    String @id @default(dbgenerated()) @map("_id") @db.ObjectId
   posts Post[]
   name  String
 }

 model Post {
   id     String @id @default(dbgenerated()) @map("_id") @db.ObjectId
+  author User   @relation(fields: [userId], references: [id], onDelete: Cascade)
-  author User   @relation(fields: [userId], references: [id])
   title  String
   userId String @db.ObjectId
 }

By specifying onDelete: Cascade, Prisma will also delete posts whenever the author of the posts is deleted. There's a lot more to referential actions than cascading deletes. Head over to our documentation to learn more.

Prisma exposes features and workflows that database vendors don't offer.

Prevent referential cycles on MongoDB

As part of getting onDelete and onUpdate ready for MongoDB, we’ve tightened up our validation rules to prevent a potential stack overflow if you create a loop with referential actions.

This change may cause some existing schemas using the mongodb preview feature to become invalid, where your schema now errors out with the following message:

Error parsing attribute "@relation": Reference causes a cycle.

If you run into this, you can learn how to resolve it with this documentation. If you’re still stuck, feel free to open a discussion and we’ll lend a hand!

Deprecating undocumented usage of type in Prisma Schema

With Prisma 3.7.0 release, the Prisma VS Code extension (and other IDEs using our language server implementation) will start to show a warning when detecting unsupported usage of the type keyword.

An example of that is string aliasing:

type MyId = String @id @default(dbgenerated(new_uuid()))

model A {
  id MyId
}

We plan to remove that functionality entirely with the next major release of Prisma. If you happen to depend on similar functionality for type aliasing, please leave a comment on the issue.

Prisma Studio

  • Due to how Prisma Studio executes Prisma Client queries, it was possible to execute arbitrary code on Studio’s local server. This has since been patched.
  • Issues with viewing and updating models with BigInt fields are also resolved.

Fixes and improvements

Prisma Client

Prisma Migrate

Language tools (e.g. VS Code)

Credits

Huge thanks to @otan, @benkroeger, @YassinEldeeb, @chenkie for helping!

📺 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 Holiday Special" livestream.

The stream takes place on YouTube on Tuesday, December 21 at 5 pm Berlin | 8 am San Francisco.

prisma - 3.6.0

Published by Jolg42 almost 3 years ago

Today, we are excited to share the 3.6.0 stable release 🎉

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

Major improvements & new features

Prisma Migrate

Full-text index support in MySQL and MongoDB (Preview)

In this version we introduce support for full-text indexes in the db pulldb push and migrate commands for MySQL and MongoDB databases as a Preview feature. This allows using them in the Prisma schema and prevents validation errors in some database schemas.

For now we do not enable the full-text search commands in the Prisma Client. They will be implemented separately, and the progress can be followed in the MongoDB and MySQL issues.

Add the preview feature fullTextIndex to the Prisma schema, after which the @@fulltext attribute is allowed in the Prisma schema:

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

model A {
  id      Int    @id
  title   String @db.VarChar(255)
  content String @db.Text
  
  @@fulltext([title, content])
}

Please note that it is mandatory to do db pull with the preview feature enabled before using Prisma Migrate on existing MySQL databases, so the index types can be converted and will not get overwritten in the next migration.

For more details check out our documentation.

Hash index support for PostgreSQL (Preview)

With the extendedIndexes preview feature, it is now possible to use Hash instead of the default BTree as the index algorithm on PostgreSQL databases. A hash index can be much faster for inserts, but it only supports equals operation in the database.

An example of using a hash index:

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

model A {
  id    Int @id
  value Int  
  
  @@index([value], type: Hash)
}

For more details check out our documentation.

VS Code extension now uses a Wasm module

Until this release, the language server powering the Prisma VS Code extension relied on logic from the Prisma engines in the form of a native binary. Downloading and running the native binary required a large amount of custom logic and led to problems due to network failures, operating system permissions and malicious code detection issues.

Starting with 3.6.0, the language server and the VS Code extension use logic compiled to WebAssembly and distributed through npm. There is no runtime binary download and no external process involved anymore. We expect this new distribution model to be more robust and hence provide a better experience for our users.

If you have any feedback, please leave an issue in the prisma/language-tools repository.

Prisma Client

Bytes can now be filtered with in and notIn

You can now use in and notIn operations on the Bytes type:

const audioTracks = raws.map(raw => {
  return Buffer.from(raw)
})

const result = await prisma.audio.find({
  where: {
    track: 
      in: audioTracks
    }
  }
})

Thanks @serejkaaa512 for your contribution!

Json fields now accept read-only types

This is a small quality-of-life improvement. You can now pass immutable values into Json fields. In the following example, audit is a Json field that accepts a read-only array:

const trail = [
  { event: "signup" },
  { event: "subscribe" },
  { event: "invite friend" }
] as const

await prisma.user.create({
  data: {
    audit: trail
  }
})

Learn more in this issue.

Reducing interactive transactions timeouts for binary engine

If you've spent some time using the new Interactive Transaction API with the binary engine, you may have encountered this timeout error:

Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'.

This could happen if you had two concurrent requests modifying the same resource at the same time using the binary engine type.

It took us a while to track down the source of this error, but it turned out to be a low-level misconfiguration in our HTTP client. We disabled HTTP pipelining to fix this problem.

Fix notIn filters for large queries

This most likely didn't affect you, but if you ever tried using notIn with a large query, you may have received an incorrect result.

The query engine automatically breaks up large queries into smaller queries and intersects the results. Most of the time this works as expected but for certain queries like notIn, the intersection of results is incorrect.

We fixed this in 3.6.0. You can now use in and notIn operations on the Bytes type:

const denyList = [/* ... large list of user ids ... */]
const result = await prisma.user.findMany({
  where: {
    id: {
      notIn: denyList
    }
  }
})

This query will break up the query into chunks that your database can manage:

select * where User not in ($1,$2, ..., $5000)
select * where User not in ($1000,$1001, ..., $6000)

... and return the correct results. Learn more in this issue.

Fixes and improvements

Prisma Client

Prisma Migrate

Language tools (e.g. VS Code)

Prisma engines

Credits

Huge thanks to @Akxe, @safareli for helping!

📺 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, December 02 at 5pm Berlin | 8am San Francisco.

Package Rankings
Top 0.41% on Npmjs.org
Top 17.22% on Repo1.maven.org
Top 3.78% on Proxy.golang.org
Badges
Extracted from project README
Prisma Tests Status Ecosystem Tests Status