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 - 2.24.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

MongoDB gets Json and Enum Support

We just added Json and enum support to the MongoDB provider for Prisma Client. Here's an example with both:

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

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

model Log {
  id      String @id @default(dbgenerated()) @map("_id") @db.ObjectId
  message String
  level   Level  @default(Info)
  meta    Json
}

enum Level {
  Info
  Warn
  Error
}

You can then use the generated client like this:

await prisma.log.create({
  data: {
    level: "info",
    message: "User signed in",
    meta: { user_id: 1 },
  },
})

As a reminder, the mongodb provider is still in Early Access. If you'd like to use MongoDB with Prisma, please fill out this 2-minute Typeform and we'll get you an invite to our Getting Started Guide and private Slack channel right away!

New features for the Prisma Data Platform

The Prisma Data Platform (PDP) helps developers collaborate better in projects that are using the open-source tools. One of its main features today is an online data browser.

View schema

You can now view your project's schema in order to better understand your application or collaborate with your colleagues. The only roles that can view it are: Admin and Developer

Delete & edit your project

You can now delete your project from your settings.

You can also edit your Project's URL, so you can now correct any mistakes you might have made while creating your project.

Static IPs are now supported

If your database is behind a proxy and you need a static IP to allowlist in order to give access to it, you can now get in touch with us by creating an issue or sending an email at [email protected] and we'll enable it for you.

Please note that while this feature is freely available now, it will be offered as part of a paid plan in the future (towards the end of '21 or beginning of '22).

Fixes and improvements

Prisma Client

Prisma Migrate

Prisma Studio

Prisma Engines

Credits

Huge thanks to @Sytten 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 3rd at 5pm Berlin | 8am San Francisco.

🌎 Prisma Day is coming

Save the date for Prisma Day 2021 and join us for two days of talks and workshops by the most exciting members of the Prisma community.

  • June 29th: Workshops
  • June 30th: Talks

We look forward to seeing you there!

prisma - 2.23.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

JSON Filtering is now in Preview

Starting today, you can now filter rows by data inside a Json type. JSON filtering support is available in PostgreSQL and MySQL. You can try it today by adding the filterJson preview flag to your generator block. This has been one of our most popular feature requests, so we're very excited to be getting it into your hands!

To get an idea of how JSON filtering works, let's see how you might query application logs stored in your database. Given the following Prisma schema:

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

model Log {
  id      Int    @id @default(autoincrement())
  level   Level
  message String
  meta    Json
}

enum Level {
  INFO
  WARN
  ERROR
}

And the following records in your PostgreSQL database:

id level message meta
2 INFO application listening on port 3000 {"host": "bob"}
3 INFO upgrading account {"host": "alice", "request_id": 10}
4 INFO charging customer {"host": "alice", "amount": 20, "request_id": 10}
5 ERROR credit card expired {"host": "alice", "amount": 20, "request_id": 10}
6 INFO signing up {"host": "bob", "request_id": 1}
7 INFO application listening on port 3000 {"host": "alice"}
8 INFO signed up {"host": "bob", "email": "[email protected]", "request_id": 1}

We can now filter logs by the data inside the meta field. Let's query by the request_id inside the meta field to track the journey that led up to the error.

We can write the following query:

const logs = await prisma.log.findMany({
  where: {
    meta: {
      // path looks for the request_id key inside meta
      path: ["request_id"],
      // and we select rows whose request_id is 10
      equals: 10,
    },
  },
  orderBy: {
    id: "asc",
  },
});

Giving us the entire journey of this person's request:

[
  {
    id: 3,
    level: 'INFO',
    message: 'upgrading account',
    meta: { host: 'alice', request_id: 10 }
  },
  {
    id: 4,
    level: 'INFO',
    message: 'charging customer',
    meta: { host: 'alice', amount: 20, request_id: 10 }
  },
  {
    id: 5,
    level: 'ERROR',
    message: 'credit card expired',
    meta: { host: 'alice', amount: 20, request_id: 10 }
  }
]

Please note that the path syntax varies depending on the database. We pass the path query directly to the database, so there will be syntactical differences.

For example, querying by key in Postgres is request_id, while in MySQL it would be $.request_id. Please consult your database's documentation to learn more.

If you run into any questions or have any feedback, we're available in this issue.

📚 Documentation: Working with Json fields

Improvement for prisma db seed

In previous versions, a seed file could only be executed as a script. prisma db seed was simply executing the script by either calling node ./prisma/seed.js for JavaScript or ts-node ./prisma/seed.ts for TypeScript.

Now, you can directly export a function that Prisma executes on your behalf. Here's the rules that describe the new behavior: Prisma checks if the seed file has ...

  • ... an exported function named seed and executes it
  • ... an exported function (via a default export) and executes it

If there's no function exported as seed or via a default export, the behaviour of prisma db seed is exactly the same as before, meaning it will simply be executed as a script file.

Breaking changes

Options in groupBy queries are now prefixed with an underscore

The options in groupBy are now prefixed with an underscore, for example:

// API
const result = await prisma.user.groupBy({
  by: ['name'],
-   count: true,
+   _count: true,
})

Here's an overview of the exact changes of each option:

Before 2.23.0 2.23.0 and later
count _count
max _max
min _min
avg _avg
sum _sum

Note that this also changes the names of the fields in the objects that are returned by Prisma Client. For example, in the above case you now access the returned count value like so:

- console.log(result.count)
+ console.log(result._count)

We made this change to avoid clashes with user-defined fields. You can learn more about the problem in these issues.

We're sorry for the inconvenience! If you have any questions or need any help, please reach out in this discussion.

Deprecations

Deprecating options in aggregate queries

With the changes to groupBy discussed above and recent features like orderBy an aggregate, we took this opportunity to unify min, max, avg, sum and count keywords across Prisma Client queries.

  const result = await prisma.user.aggregate({
-   avg: {
+   _avg: {
      age: true,
    },
  })

- result.avg
+ result._avg

Similar to groupBy, this is the case for all of our aggregations:

Before 2.23.0 2.23.0 and later
count _count
max _max
min _min
avg _avg
sum _sum

This is not a breaking change. The aggregate queries you wrote prior to 2.23.0 will continue to work as expected. We ask that you make adjustments when you can to future-proof your application.

If you have any questions or need any help, please reach out in this discussion.

Fixes and improvements

Prisma Migrate

Prisma Client

Prisma Studio

Prisma Engines

Credits

Huge thanks to @Sytten, @schiller-manuel, @mongolyy, @paularah, @Iamshankhadeep, @meeq 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, May 20 at 5pm Berlin | 8am San Francisco.

🌎 Prisma Day is coming

Save the date for Prisma Day 2021 and join us for two days of talks and workshops by the most exciting members of the Prisma community.

We look forward to seeing you there!

prisma - 2.22.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

prisma db push is now Generally Available

prisma db push enables you to update the database schema from the Prisma schema file, without generating any migrations.

This is especially useful when prototyping a new feature, iterating on the schema changes before creating migrations or generally if you are at stage of your development process, where you don't need to persist the schema change history via database migrations.

It is now promoted from Preview to General Availabilty.

You can find more info on prisma db push in the official docs.

Deprecation of array notation for provider fields

In this release, we are also entirely removing the array notation for the provider fields on datasource blocks. This has been deprecated since 2.11.0 (November 2020).

You can read more about our reasons for this deprecation here.

Prisma Client Go gets support for AND operator

We've always had OR, but this release we also added AND support:

first, err := client.User.FindFirst(
	User.Or(
		User.Email.Equals("[email protected]"),
		User.And(
			User.Name.Equals("John"),
			User.Username.Equals("johno"),
		),
	),
).Exec(ctx)

Learn more in our docs.

Fixes and improvements

Prisma Migrate

Prisma Client

Prisma Studio

Prisma engines

Credits

Huge thanks to @Sytten, @schiller-manuel, @mongolyy, @paularah, @Iamshankhadeep, @meeq 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, May 06 at 5pm Berlin | 8am San Francisco.

prisma - 2.21.2

Published by Jolg42 over 3 years ago

Today, we are issuing the 2.21.2 patch release.

Fix

Prisma Client

prisma - 2.21.1

Published by Jolg42 over 3 years ago

Today, we are issuing the 2.21.1 patch release.

Fix

Prisma Studio

prisma - 2.21.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

Order by an aggregate in groupBy is now in Preview

Whew, that's a tongue-twister for a neat feature.

Let's say you want to group your users by the city they live in and then order the results by the cities with the most users. In 2.21.0, now you can!

const userRatingsCount = await prisma.user.groupBy({
  by: ['city'],
  count: {
    city: true,
  },
  orderBy: {
    _count: {
      city: 'desc',
    },
  },
})
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  city  String
}

The query returns the following:

[
  { city: 'Berlin', count: { city: 3 } },
  { city: 'Paris', count: { city: 2 } },
  { city: 'Amsterdam', count: { city: 1 } },
]

Enable this feature with the orderByAggregateGroup preview flag:

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

📚 Documentation: Order by aggregate group

Breaking Changes

Aggregates are now nullable

Before 2.21.0, aggregations on nullable fields always returned 0, even when there was no record or if all aggregated records were nulls. Returning 0 for null values made it impossible to differentiate between these two different results.

We are changing aggregates to follow what the database returns:

  • All aggregated fields are now nullable. Aggregated fields can return null when there's either no record in the database or if all the aggregated records are null.
  • The only exception is count, which still returns 0, even if records are null or if there's no record.

For example, previously, if there's no record in the database or if all records are nulls, the following aggregation:

const result = await prisma.post.aggregate({
  sum: { amount: true },
})

Results in:

{
  sum: {
    amount: 0
  }
}

The result.sum type is currently of type { amount: number }.

Starting this release, the same query returns:

{
  sum: {
    amount: null
  }
}

And result.sum is of type { amount: number | null }

📚 Documentation: Aggregates are nullable

disconnect no longer throws an error on unconnected records

Prior to 2.21.0, if you ran the following code:

const user = await prisma.user.update({
  where: { email: '[email protected]' },
  data: {
    profile: {
      disconnect: true,
    },
  },
})

And no profile was connected to Bob, the client would throw with this error:

The records for relation `UserToProfile` between the `User` and `Profile` models are not connected.

We learned from you that handling this added unnecessary boilerplate to your applications. As of 2.21.0, we've removed this error. Now, if you try disconnecting an unconnected record, the operation does nothing and passes through.

This change is unlikely to affect you unless you explicitly handle the disconnect error. In that case, adjust your code because the command no longer throws an error.

📚 Documentation: $disconnect()

@default(dbgenerated("")) is no longer permitted

The dbgenerated() function allows you to define default values generated directly by the database and cannot yet be represented in the Prisma schema.

Previously, you could pass an empty string, i.e., @default(dbgenerated("")), which would fail since the contents are added into the migration SQL as columnName COLUMN_TYPE DEFAULT <contents of dbgenerated>

As of 2.21.0, if a value is present, it cannot be an empty string.

If you want an empty string default, the correct syntax is @default(dbgenerated("''") (or other quotation marks, depending on the database provider).

📚 Documentation: dbgenerated()

Fixes and improvements

Prisma Client

Prisma Migrate

Prisma Studio

We worked on shipping some minor improvements and bug fixes:

prisma-engines

Credits

Huge thanks to @Sytten, @endor, @iBluemind, @schiller-manuel, @mongolyy, @matthewmueller, @paularah, @Iamshankhadeep, @meeq, @safinsingh, @darioielardi 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, April 15 at 5pm Berlin | 8am San Francisco.

prisma - 2.20.1

Published by Jolg42 over 3 years ago

prisma - 2.20.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

Count on relations (Preview)

This highly requested feature is now in Preview. You can now count the number of related records by passing _count to the select or include options and then specifying which relation counts should be included in the resulting objects via another select.

For example, counting the number of posts that an user has written:

const users = await prisma.user.findMany({
  include: {
    _count: {
      select: { posts: true },
    },
  },
})

The structure of the returned User objects is as follows:

{
  id: 1,
  email: '[email protected]',
  name: 'Alice',
  _count: { posts: 2 }
}

You can enable this featrues with the selectRelationCount feature flag:

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

There may be some rough edges during the Preview period. If you run into any problems, you can reach us in this issue.

Node-API is now in Preview

Node-API is a new technique for binding Prisma's Rust-based query engine directly to Prisma Client. This reduces the communication overhead between the Node.js and Rust layers when resolving Prisma Client's database queries.

You can enable this feature with the napi feature flag:

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

Enabling the Node-API will not affect your workflows in any way, the experience of using Prisma will remain exactly the same.

The Node-API has different runtime characteristics than the current communication layer between Node.js and Rust.

There may be some rough edges during the Preview period. If you run into any problems, you can reach us in this issue.

New push operation available for arrays on PostgreSQL

PostgreSQL supports array data structures (sometimes also called scalar lists). As an example, consider the permissions field on the following User model:

model User {
  id          Int @id @default(autoincrement())
  permissions String[]
}

As of this release, you can append a new item to existing lists atomically with the push command:

await prisma.user.update({
  where: { id: 42 },
  data: {
    permission: {
      push: "chat:read",
    },
  },
})

Learn more in this issue.

groupBy and createMany are now Generally Available

For the pioneers among you, you can now remove the groupBy and createMany from your Preview features:

 generator client {
   provider        = "prisma-client-js"
-  previewFeatures = ["groupBy", "createMany"]
 }

Learn more in our documentation about groupBy and createMany.

Prisma Client Go now supports BigInt, Decimal and Bytes

Prisma Client Go continues to get more powerful every release. With this release, we've added support for more native database types: BigInt, Decimal and Bytes:

var views db.BigInt = 1
bytes := []byte("abc")
dec := decimal.NewFromFloat(1.23456789)
created, err := client.User.CreateOne(
  db.User.Picture.Set(bytes),
  db.User.Balance.Set(dec),
  db.User.Views.Set(views),
).Exec(ctx)

Breaking changes

The @prisma/cli package has reached its end of life

For all you holdovers, you've seen warnings like this for a couple months now:

warn @prisma/cli has been renamed to prisma.
Please uninstall @prisma/cli: npm remove @prisma/cli
And install prisma: npm i prisma

It's now time to upgrade. Follow the instructions and switch over to the new prisma package today:

npm

npm remove @prisma/cli
npm install -D prisma

Thanks to this change, running npx prisma will now always invoke the right Prisma CLI, no matter what your local setup looks like.

Yarn

yarn remove @prisma/cli
yarn add -D prisma

Upcoming breaking changes in the next version (2.21.0)

.aggregate will change to return null in 2.21.0

Subscribe to this issue for updates on how to prepare your code.

Fixes and improvements

Prisma Migrate

Prisma Client

Language tools (e.g. VS Code)

Security Fixes

We fixed two security issues:

Big thanks to @erik-krogh (Erik Krogh Kristensen) and @Ry0taK for reporting these issues.

Credits

Huge thanks to @endor, @iBluemind, @matthewmueller, @paularah, @Iamshankhadeep 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, April 01 at 5pm Berlin | 8am San Francisco.

prisma - 2.19.0

Published by Jolg42 over 3 years ago

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

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

Major improvements & new features

Prisma Migrate is now ready for General Availability 🚀

We are excited to announce that Prisma Migrate enters General Availability. You can learn more about the launch in the announcement article.

There are no major changes to how Prisma Migrate works except that the --preview-feature flag is being removed:

Before v2.19.0

npx prisma migrate <COMMAND> --preview-feature

# for example:
npx prisma migrate dev --preview-feature

Now

npx prisma migrate <COMMAND>

# for example:
npx prisma migrate dev

Besides making Prisma Migrate ready for production in this release, it comes with a number of smaller fixes and improvements:

  • After migrate dev, migrate reset and db push, generation is always triggered to avoid issues where the Prisma Client API is outdated due to changes in relation names which have an impact on the database schema (GitHub issue)
  • Improve UX when migrate dev produces warnings (GitHub issue)
  • Better error when adding a new required field and the default value is Prisma-level, e.g. uuid()
  • Small improvement where Prisma Migrate failed to create the database on DigitalOcean
  • Bugfix: Fix a bug when there are foreign keys referencing missing tables that resulted in a crash
  • Bugfix: Improvement when changing a field from type String to Enum (MySQL, PostgreSQL)
  • Bugfix: Improvement when migrating enums and a default enum value is defined (PostgreSQL)

📚 Documentation:

Order by aggregates of relations in Prisma Client queries (Preview)

This release makes it possible to order by the aggregates (e.g. count) of relations in your Prisma Client queries. Here's is an example that orders a list of users by the number of the posts they created:

const orderedUsers = await prisma.user.findMany({
  orderBy: {
    posts: {
      count: 'asc'
    }
  }
})

This feature is released in Preview which means you have to explicitly enable it via the orderByRelation feature flag in your Prisma schema:

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

Don't forget to run npx prisma generate after you've added the feature flag to your Prisma schema so that the Prisma Client API gets updated accordingly.

Prisma Client Go now returns results from the Transaction API

Previously in the Go Client, you could write data within a transaction, but you couldn't get the results back from the transaction. Now you can! Learn more in the documentation.

Fixes and improvements

Prisma Client

Prisma Migrate

Language tools (e.g. VS Code)

Prisma Studio

Credits

Huge thanks to @endor, @iBluemind, @meeq for their help in this release! ✨

💼 Learn about Enterprise use cases of Prisma on March 25th

We hope you join us for the upcoming Prisma Enterprise Event on Thursday, March 25th which is centered around the following topics:

  • Learn how top companies are addressing the challenges of data at scale
  • Discover how companies use Prisma to make their developers more productive
  • Get a better understanding of the future of data in the enterprise

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

prisma - 2.18.0

Published by Jolg42 over 3 years ago

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

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

Major changes & improvements

prisma introspect is becoming prisma db pull

In 2.10.0 we introduced the prisma db push command that enables developers to update their database schema from a Prisma schema file without using migrations.

For the "opposite" motion (i.e., updating the Prisma schema from an existing database schema), we currently have the prisma introspect command. In this release, prisma introspect is being renamed to prisma db pull. However, the prisma introspect command will be kept around for a few more releases so that you have enough time to switch over to the new command.

Here is how we are planning to execute the renaming:

  1. In this release, we are introducing a new command prisma db pull, which behaves exactly the same as prisma introspect.
  2. We will at some point in the near future add a deprecation warning to the prisma introspect CLI command.
  3. Eventually, prisma introspect will be removed.

There is no specific timeline to execute on this deprecation and we want to make sure we give developers a generous period of time to switch over.

Relation syntax will not be updated automatically any more

Prisma has a set of rules for defining relations between models in the Prisma schema.

The prisma format command automatically helps to apply these rules by inserting missing pieces. As an example, consider this data model with an invalid relation:

model User {
  id    String  @id
  name  String?
  posts Post[]
}

model Post {
  id       String  @id
  authorId String?
  author   User?   // not valid because the `@relation` attribute is missing
}

This example is not valid because the @relation attribute is missing. Running npx prisma format, automatically inserts the missing attribute:

model User {
  id    String  @id
  name  String?
  posts Post[]
}

model Post {
  id       String  @id
  authorId String?
+ author   User?   @relation(fields: [authorId], references: [id])
}

In previous releases, this expansion logic was applied automatically in several scenarios without running the formatter (by running npx prisma format explicitly, or formatting via VS code), e.g. when running prisma migrate. While helpful in some scenarios, these "magic" insertions often resulted in others errors that were harder to interpret and to debug for developers and ourselves.

In this release, the "magical" instertions are removed and developers need to explicitly run npx prisma format if they want still make use of them.

More flexible seeding in TypeScript

The ts-node command options can now be customized via package.json to pass specific options to ts-node. This makes prisma db seed work with tools that have specific requirements when used with TypeScript, such as Next.js.

Here is an example that works with Next.js:

{
  "name": "my-project",
  "version": "1.0.0",
  "scripts": {
    "ts-node": "ts-node --compiler-options '{\"module\":\"CommonJS\"}'"
  },
  "devDependencies": {
    "@types/node": "^14.14.21",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  }
}

New Upsert API for Prisma Client Go

Prisma Client Go now supports upsert operations:

post, _ := client.Post.UpsertOne(
    // query
    Post.ID.Equals("upsert"),
).Create(
    // set these fields if document doesn't exist already
    Post.Title.Set("title"),
    Post.Views.Set(0),
    Post.ID.Set("upsert"),
).Update(
    // update these fields if document already exists
    Post.Title.Set("new-title"),
    Post.Views.Increment(1),
).Exec(ctx)

Learn more in the documentation and share your feedback in the #prisma-client-go channel on Slack.

Fixes and improvements

Prisma Client

Prisma Migrate

Prisma Studio

Language tools (e.g. VS Code extension)

Prisma engines

📝 Help us improve our release notes

We want to ensure our release notes are as helpful as possible for you! You can help us achieve this by taking part in the poll in this GitHub issue.

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

prisma - 2.17.0

Published by timsuchanek over 3 years ago

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

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

Overview

  • Native types are now stable
  • Prisma Migrate now works with cloud-hosted databases (e.g. Heroku)
  • Soft resets for cloud-hosted environments
  • More improvements and bug fixes for Prisma Migrate
  • Improvements and changes for prisma db push
  • prisma db seed now supports custom schema locations
  • Improvements and bug fixes in Prisma Client

Note that this release comes with some breaking changes. Read the Breaking changes section below to learn more.

Major improvements & new features

Native types are now stable

The nativeTypes preview feature flag has first been introduced in 2.10.0. Thanks to your continuous and awesome feedback for this feature, we're now able to release usage of native database types in the Prisma schema for General Availability 🎉

Note that this release comes with a few minor breaking changes compared to previous versions. Please read about the Breaking Changes below.

If you haven't followed previous releases, expand below to learn more about everything that's now possible with the new native types.

Rich column type mapping for Prisma types

Each Prisma type can now map to one of multiple native database types. Native database type attributes are:

  • Specific to the underlying provider - for example, PostgreSQL uses @db.Boolean for Boolean whereas MySQL uses @db.TinyInt
  • Written in PascalCase (for example, VarChar or Text)
  • Prefixed by @db, where db is the name of the datasource block in your Prisma schema

Type attributes give you:

  • Exact control over what native type Prisma Migrate creates in the database - for example, a String can be @db.VarChar(200) or @db.Char(50)
  • An enriched schema when you introspect - you can see if String is varchar(200) or just text.

To learn more about all the possible native type attributes, check out the type mapping reference in the docs.

Extending Prisma schema beyond supported column types

Column types which are not (yet?) supported by Prisma Migrate can be used with Prisma Migrate and introspection through the Prisma type Unsupported which was introduced in Preview in the last release:

model User {
  id                    Int     @id @default(autoincrement())
  email                 String  @unique
  name                  String? @default("")
  multilinestringField  Unsupported("multilinestring") @unique
}

dbgenerated() in the @default directive can now take a String argument that enables developers to reflect database-level DEFAULT constraints not yet supported by Prisma Migrate. These default values will be surfaced when introspecting with prisma introspect and created/changed when using Prisma Migrate.

Developers can now add @@ignore and @ignore attributes to models and fields, for fields they want to manage via Prisma Migrate but not surfaced in Prisma Client. These attributes are added by Prisma when introspecting entities which are not supported, e.g. a table with no unique column. They are now also kept in the Prisma schema when re-introspecting a database.

Prisma Migrate now works with cloud-hosted databases (e.g. Heroku)

Before this release, Prisma Migrate could be used to apply migrations in a cloud-hosted environment (CI/CD pipeline, manual deployment to production, staging, etc.), but it was impossible to create new migrations, due to the requirement of a shadow database. Prisma Migrate expects to have privileges to create the shadow database using the same credentials, but cloud providers generally do not allow creating logical databases.

Starting from this release, prisma migrate dev can now be used in development with cloud-hosted databases by configuring a separate connection URL for the shadow database.

To develop natively in the cloud with Prisma Migrate, developers can create two cloud-hosted databases, one being the development- and the other being the shadow-database.

The connection URI for the shadow database can be configured in the datasource block of the Prisma schema file, similarly to the datasource URL, by defining a shadowDatabaseUrl variable:

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

Soft resets for cloud-hosted environments

Another common limitation of cloud-hosted environments is that the database cannot be dropped and re-created using DROP DATABASE and CREATE DATABASE, due to insufficient privileges. Prisma Migrate so far relied on these statements to ensure the database is empty when it needs to be reset.

Database resets in the context of Prisma Migrate now gracefully fall back to dropping constraints, indexes and tables, if there are insufficient privileges to reset the database using DROP DATABASE.

Note that this comes with the caveat that there could be other entities in the database, which Prisma Migrate could fail to clean up.

More improvements and bug fixes for Prisma Migrate

  • Prisma Migrate has now a built-in locking functionality to prevent multiple migrations from running concurrently.
  • Ensure the Prisma schema is valid before prompting developers to reset the database.
  • Better error message when using migrate dev - if a non-interactive environment is detected, you'll be suggested to use prisma migrate deploy instead.
  • Improved error handling when Prisma Migrate finds empty migration directories, e.g. prisma/migrations/20210119114009_init (missing migration.sql file).
  • In some occasions, when dealing with invalid schemas, e.g., duplicate constraint names, a panic in the Migration Engine would be triggered. These errors are now surfaced as validation errors instead.
  • In certain cases, when dealing with UUID columns, Prisma Migrate would drop and re-create the columns every time a migration was generated. This has now been fixed.

Improvements and changes for prisma db push

  • prisma db push now handles unexecutable migrations better, offering a path forward by resetting the database. For example, adding a new required field without a default value when there are rows in the table is considered an unexecutable migration; in such situations you will be prompted to first reset the database.
  • Changes to command options:
    • The flag —-force has been renamed to --accept-data-loss to be more explicit - this is required for certain changes that involve losing data, e.g. dropping a table or dropping a column if there are rows.
    • We've added a new flag —-force-reset which first resets the database and then updates the schema - this can be useful to start from scratch and as a way to deal with unexecutable migrations (see above).

prisma db seed now supports custom schema locations

You can now point the prisma db seed command to a custom schema location using either of two approaches:

  • Use the --schema option when running the command
  • Define a default schema location in your package.json which will be picked up every time you run the command.

Improvements and bug fixes in Prisma Client

  • Transaction rollback fix: We fixed an issue where if there was an error within the Prisma Client's runtime validation, the transaction wouldn't rollback. Learn more in this issue.
  • SQL Server server_name fix: Before we couldn't connect to certain kind of SQL Server instances. If the server was a managed instance from Azure, connecting to it with Prisma would return Server name cannot be determined. Additionally, when running a shared Azure SQL database, if the firewall setting was set to redirect (the default setting), our connection would first fail with advising the user to connect to a new server, and when changing the connection string regarding the error, the new connection would fail with the same error Server name cannot be determined. This is now fixed. Azure managed instances just work, as do redirections (which are done under the hood, automatically).
  • Native type fix for SQL Server: Our native type validations limits were set too low. We'd consider the maximum of 2000 for NVarChar/NChar length and a maximum of 4000 for VarChar/Char/VarBinary/Binary length. The actual maximums are 4000 for first and 8000 for the latter types.
  • PostgreSQL numeric type fix: In certain cases, when using executeRaw to insert number values to a numeric type in PostgreSQL, sometimes the stored value would be zero instead of the user input. An example value of 12345.0 is converted by JavaScript as an integer of 12345, which then is written as an integer to the table. The table column being numeric, the integer representation would always be zero in these cases. Now we should be able to convert integers to numeric without any trouble.

Bug fixes in Prisma Studio

  • Studio can now display fields that are of type Byte and BigInt.
  • Usage of the createMany preview feature doesn't crash Studio any more

Breaking changes

Type mapping from Prisma schema to the database for Float has changed from Decimal to Double in MySQL and PostgreSQL

Overview

If you use the Float scalar type in your Prisma schema and used Prisma Migrate to create the database schema in previous Prisam versions, the corresponding database column has the type DECIMAL(65,30).

For example, given the following Prisma schema:

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  reward    Float // Previously mapped to DECIMAL(65,30). From 2.17.0 will map to Double
  published Boolean @default(false)
}

Previous version of Prisma Migrate would generate the following migration:

-- CreateTable
CREATE TABLE "Post" (
    "id" SERIAL NOT NULL,
    "title" TEXT NOT NULL,
    "content" TEXT,
    "reward" DECIMAL(65,30) NOT NULL, // 
    "published" BOOLEAN NOT NULL DEFAULT false,
    PRIMARY KEY ("id")
);

As of 2.17.0, the remapping of the Float type from Decimal(65,30) to Double will cause Migrate to attempt to alter the database type of the reward column to Double the next time you create a migration.

What does this mean for users?

Nothing changes in Prisma Client until the next time you want to make a change to your schema. In that case, you'll need to decide if you want to keep using the Decimal(65,30) type in the database:

  • If you want to continue using Decimal(65,30), you need to change the type in the Prisma schema from Float to Decimal. Alternatively, you can also run prisma introspect which will automatically remap the previous Float fields to Decimal. Note that this will also change the type that Prisma Client returns from Number to Decimal.js.
  • If you would like to change the column's type in the database from Decimal(65,30) to Double, leave the Prisma schema as is and create a new migration. Prisma Migrate will alter the column's type to Double. Note that if you have rows with data for the column, they will be cast from Decimal(65,30) to Double.

Check out this video guide, which covers how to upgrade and address the remapping of Float.

Breaking changes due to strict type diffing and native types

Overview

Prisma has default mappings between each scalar type in the Prisma schema to the underlying database type. For example, the String scalar type in Prisma schema is mapped to a TEXT column on PostgreSQL by default.

Before this release, Prisma supported using a range of database column types for a given Prisma scalar. For example, define a field in Prisma schema as String and use VARCHAR(50) as the column type in the database using the @db.varchar(50) type annotation .

With the introduction of native types in General Availability, you can now specify your desired database type for columns in the Prisma schema via the @db.DB_TYPE field attributes, e.g., @db.varchar(50).

Because the @db.DB_TYPE attribute now exists, Prisma no longer allows the loose mapping of Prisma scalar types to database column types without the specific notation. The only exception to this rule is when you want to use default mapping, e.g., the String Prisma scalar will map to TEXT on PostgreSQL.

Before

Given the following table in PostgreSQL:

-- CreateTable
CREATE TABLE "User" (
    "id" SERIAL NOT NULL,
    "nickName" VARCHAR(50),
    "name" TEXT NOT NULL,

    PRIMARY KEY ("id")
);

Prisma would introspect the table as follows:

model User {
  id       Int      @id @default(autoincrement())
  nickName String?  //defaults to TEXT on PostgreSQL but works with varchar
  name     String   //defaults to TEXT on PostgreSQL but works with varchar
}
After

Because VARCHAR(50) can be expressed in native type notation. The matching Prisma schema for the User database table above on PostgreSQL is the following:

// Example for PostgreSQL

model User {
  id       Int      @id @default(autoincrement())
  nickName String?  @db.VarChar(50) // Prisma expects the column to be varchar and Prisma Migrate will change it if not
  name     String   // Prisma expects the column to be of type TEXT (default for String) and Prisma Migrate will change it if not
}

What does this mean for users?

Moving forward, if you want specific database column types, which are supported by Prisma, you should make sure to use the native type notation for the corresponding fields in the Prisma schema.

For users of Prisma Migrate with existing databases, you must understand that Prisma Migrate will try to migrate every column of a type different than what's defined in the schema.

If we go back to the previous example with loose type mapping, with this Prisma schema:

model User {
  id       Int      @id @default(autoincrement())
  nickName String?  //defaults to TEXT on PostgreSQL but works with varchar
  name     String   //defaults to TEXT on PostgreSQL but works with varchar
}

and this initial database schema:

-- CreateTable
CREATE TABLE "User" (
    "id" SERIAL NOT NULL,
    "nickName" VARCHAR(50),
    "name" TEXT NOT NULL,

    PRIMARY KEY ("id")
);

On PostgreSQL, from this release on, Prisma will the columns for the fields nickName and name to be of type TEXT and will generate a migration to alter the type of the nickName column:

-- AlterTable
ALTER TABLE "User" ALTER COLUMN "nickName" SET DATA TYPE TEXT;

To avoid unnecessary migrations to change types you may have defined on purpose, you can run introspection once, which will add the native annotations to any fields when they do not match the default mappings by Prisma.

For the initial database schema we used in the example

-- CreateTable
CREATE TABLE "User" (
    "id" SERIAL NOT NULL,
    "nickName" VARCHAR(50),
    "name" TEXT NOT NULL,

    PRIMARY KEY ("id")
);

This would be the resulting Prisma schema after running prisma introspect

model User {
  id       Int      @id @default(autoincrement())
  nickName String?  @db.VarChar(50)
  name     String   
}

Fixes and improvements

Prisma Client

Prisma Migrate

Language tools

Prisma Studio

Prisma Engines

Check out the official Prisma roadmap

You can find all the features that are currently planned and in progress on our roadmap.

Credits

Huge thanks to @safinsingh for helping!

prisma - 2.16.1

Published by pimeys over 3 years ago

Today, we introduce the 2.16.1 patch release.

This fixes a problem some users are having with certain Docker, MariaDB, MySQL or SQL Server configurations, preventing Prisma to connect with localhost. A recent Docker update caused a regression related to IPv6 and name resolution.

Prisma

Prisma Engines

prisma - 2.16.0

Published by timsuchanek over 3 years ago

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

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

Major improvements

The Prisma CLI moves from the @prisma/cli to the prisma npm package

Going forward, you can install the Prisma CLI via the prisma npm package:

npm install prisma --save-dev

or

yarn add prisma --dev

The reason for this is that a number of users were experiencing issues when running the npx prisma command. Without a local installation of the @prisma/cli package, this would invoke the Prisma 1 CLI leading to an error message. From now on, npx prisma is always going to work.

We will also deprecate the @prisma/cli package. Please do a find and replace across your codebase to transition over from @prisma/cli to prisma. To make this transition easier, we'll keep publishing updates to both packages for another month and plan to stop updating the @prisma/cli package with release 2.18.0.

There are no changes to the @prisma/client npm package name.

Efficient bulk creates with createMany

Insert data a whole lot faster with createMany. Here's an example:

const result = await prisma.user.createMany({
  data: [
    { email: "[email protected]" },
    { email: "[email protected]" },
    { email: "[email protected]" },
    { email: "[email protected]" },
  ],
});

console.log(`Created ${result.count} users!`);

This feature is in preview right now. Enable it with the createMany preview flag:

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

📚 Documentation: Create multiple records

Learn more in this issue.

Order by relation fields with orderBy

Ever wish you could order posts by an author's name? Or sort transactions by account? Now you can! We've expanded orderBy to support ordering by relations:

cons posts = await prisma.post.findMany({
  orderBy: [
    {
      author: {
        name: "asc",
      },
    },
  ],
});

This feature is in preview right now. Enable it with the orderByRelation preview flag:

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

📚 Documentation: Sort by relation

Learn more in this issue.

Improvements to the nativeTypes Preview feature

We are working hard on making the Prisma experience smoother for folks that are using the nativeTypes Preview feature and are getting close to releasing it for General Availability.

If you have any feedback for this feature, please share it on GitHub.

New Unsupported type allows to surface any database type in the Prisma schema

This release introduces a new Unsupported type in the Prisma schema. It acts as an escape hatch and allows to surface fields in Prisma schema for database types that are not yet supported by Prisma. For example, MySQL's POLYGON type is not yet natively supported by Prisma, but can now be added to the Prisma schema using the Unsupported("polygon") type.

The new type is especially relevant during introspection where previously fields of unsupported types would have been commented out, they're now included in the Prisma schema and of type Unsupported.

Fields of the Unsupported type are added to the Prisma schema in either of two ways:

  • via introspection in cases when Prisma detects a database column with a type that is not yet natively supported by Prisma
  • manually in combination with Prisma Migrate; in this case Prisma Migrate generates a SQL migration with the type that's provided as an argument to Unsupported in the Prisma schema

Note that fields of type Unsupported will not be surfaced in the Prisma Client API.

Example with Prisma Migrate

Here's an example of the new Unsupported type that uses MySQL's multilinestring:

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

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

model User {
  id    Int                            @id @default(autoincrement())
  email String                         @unique
  name  String?
  bio   Unsupported("multilinestring") @unique
}

Prisma Migrate generates the following SQL for the User model:

CREATE TABLE `User` (
  `id` INTEGER NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(191) NOT NULL,
  `name` VARCHAR(191),
  `bio` multilinestring NOT NULL,

  UNIQUE INDEX `User.email_unique`(`email`),
  UNIQUE INDEX `User.bio_unique`(`bio`),
  PRIMARY KEY (`id`)
);
How Unsupported fields affect the Prisma Client API

Since Prisma Client doesn't yet "understand" the Unsupported type and therefore cannot read or write to its fields, we've also disabled creates and upserts on models that have a required Unsupported field without a default value. This prevents constraint violations at runtime.

To make this explicit, a new @@ignore attribute is added to the models that contain fields of type Unsupported during introspection:

model User {
  id       Int                  @id @default(autoincrement())
  location Unsupported("point")

  @@ignore
}
// Not permitted because the database requires a `location`, but it can't be
// provided because the `point` type is unsupported by Prisma Client.
const user = await prisma.user.create({});

If the @@ignore attribute is added to a model, the relation fields of that model on other models will be annotated with the @ignore attribute, for example:

model User {
  id       Int                  @id @default(autoincrement())
  location Unsupported("point")

  @@ignore
}

model Post {
  id     Int    @id @default(autoincrement())
  title  String
  author User   @ignore
}

New notation for default values via dbgenerated()

dbgenerated() in the @default field directive can now take a String argument that enables developers to reflect database-level default values that are not yet natively supported by Prisma.

This changes the signature of the attribute from dbgenerated() to dbgenerated(default: String). As an example, you can use @default(dbgenerated("''")) to define an empty string as the default value for a column in MySQL.

These default values will be surfaced when introspecting the database or created/changed when defined manually in combination with Prisma Migrate.

This feature can be used alongside the new Unsupported type as well as with regular Prisma types.

Examples with Prisma Migrate

Setting a default value on a multilinestring column:

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

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

model User {
  id    Int                            @id @default(autoincrement())
  email String                         @unique
  name  String?
  bio   Unsupported("multilinestring") @unique @default(dbgenerated("''"))
}

Prisma Migrate generates the following SQL for the User model:

CREATE TABLE `User` (
  `id` INTEGER NOT NULL AUTO_INCREMENT,
  `email` VARCHAR(191) NOT NULL,
  `name` VARCHAR(191),
  `multilinestringField` multilinestring NOT NULL DEFAULT '',

  UNIQUE INDEX `User.email_unique`(`email`),
  UNIQUE INDEX `User.bio_unique`(`bio`),
  PRIMARY KEY (`id`)
);

Setting a default value for UUIDs via the pgcrypto PostgreSQL extension:

model User {
  id   String  @id @db.Uuid @default(dbgenerated("gen_random_uuid()"))
  name String?
}

Prisma Migrate generates the following SQL for the User model:

CREATE TABLE "User" (
    "id" UUID NOT NULL DEFAULT gen_random_uuid(),
    "name" TEXT,

    PRIMARY KEY ("id")
);

Note that the example above requires the corresponding extension to be enabled (in this case: CREATE EXTENSION "pgcrypto";).

New native type attributes available on PostgreSQL

We've added new native types for the postgresql provider. Here's an overview of the new type mappings:

PostgreSQL Prisma Note
Inet String
Money Decimal
Oid Int
Citext String Requires the Citext extension

Here's an example that uses the four new types in a Prisma schema:

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

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

model User {
  id                    Int     @id @default(autoincrement())
  ipAddress             String? @db.Inet
  balance               Decimal @db.Money
  oid                   Int     @db.Oid
  citextName            String  @db.Citext
}

Prisma Migrate generates the following SQL for the User model:

CREATE TABLE "User" (
    "id" SERIAL NOT NULL,
    "ipAddress" INET,
    "balance" MONEY NOT NULL,
    "oid" OID NOT NULL,
    "citextName" CITEXT NOT NULL,
    PRIMARY KEY ("id")
);

More changes to the nativeTypes Preview feature

  • When using the nativeTypes Preview feature, introspection will only render a native attribute if the column type does not map to Prisma's corresponding default type. This might remove any existing type annotations upon (re-)introspection where the default mapping is currently in place.
  • MySQL
    • Columns of type BIT(1) can now be mapped to Prisma's Boolean type as well using the Bit native type attribute, e.g. myField Boolean @db.Bit(1).
    • Default mapping for Prisma's Float type has been changed from DECIMAL(65,30) to Double.
  • PostgreSQL
    • Default mapping for Prisma's Float type has been changed from DECIMAL(65,30) to Double.
  • SQLite
    • Default mapping for Prisma's Decimal type has been changed from REAL to DECIMAL.
PostgreSQL and MySQL users
  • If no action is taken, the next time a new migration is created with prisma migrate dev, Prisma Migrate will generate DDL statements to change columns of Prisma's type Float to use Double instead of Decimal. These changes may lead to rounding errors due to differences in precision.
  • If changing the underlying column is not desired, users can specify Decimal and continue using that as as the column type.
    • Steps involved:
      1. make sure the preview feature flag for native types is enabled
      2. Change the field to be of scalar type Decimal
      3. use the native type notation to pin the underlying type to Decimal or re-introspect your database with prisma introspect after enabling native types
    • Example before: myField Float
    • Example after: myField Decimal @db.Decimal(65,30)
SQLite
  • If you were using Decimal before on SQLite, with the native type feature flag enabled, Prisma Migrate will change the type in the next migration from REAL to DECIMAL.
  • This can be avoided by changing the scalar type in the Prisma schema from Decimal to Float, or running re-introspection which will do the same.

queryRaw Breaking Changes

On MySQL only, fields of type Boolean are stored as TINYINT(1) in the database. We no longer coerce the value to a Boolean. That means queryRaw now returns integers of value 0 or 1 instead of true or false for Boolean fields.

Host Prisma Studio on Vercel

You can host your own instance of Prisma Studio on Vercel by following the instructions in the README of this example repo.

More improvements

  • You can now skip seeding when calling prisma migrate dev or prisma migrate reset with the —-skip-seed flag.
  • You can now use the --schema option on the prisma db seed command to execute the command with a custom Prisma schema location.

Prisma Client Go gets dynamic filters

Give your users more control over how they filter and order their data. Build up filters over time instead of all at once.

Here's an example of setting specific attributes dynamically:

func CreateUser(w http.ResponseWriter, r *http.Request) {
    var params []db.UserSetParam
    email := r.PostFormValue("email")
    kind := r.PostFormValue("kind")
    if kind == "customer" {
        // Set the referrer for users of type customer only
        params = append(params, db.User.Referer.Set(r.Header.Get("Referer"))
    }
    user, err := client.User.CreateOne(
        db.User.Kind.Set(kind),
        db.User.Email.Set(email),
        params...,
    ).Exec(r.Context())
    // ... Handle the response
}

Learn more in the Go documentation.

Fixes and improvements

Prisma Client

Prisma Migrate

Language tools (e.g. VS Code extension)

Prisma Studio

Prisma Engines

Credits

Huge thanks to @aruld for helping!

prisma - 2.15.0

Published by timsuchanek over 3 years ago

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

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

Major improvements

Prisma Migrate now supports native database types (Preview)

In 2.11.0, we introduced support for native database types in the Prisma schema that allow you to map Prisma's scalar types to more specific types in the underlying database. However, these have not been compatible with the current Preview version of Prisma Migrate yet.

This release makes it possible to use Prisma Migrate with the native type annotations in your Prisma schema!

Here's an example that uses several type annotations:

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

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

model Post {
  id        Int     @id @default(autoincrement()) @db.Integer
  published Boolean @default(false)
  content   String? @db.VarChar(1000)
  title     String  @db.VarChar(191)
  buffer    Bytes?
}

Running a migration using the prisma migrate command, the following SQL is created:

CREATE TABLE "Post" (
  "id" SERIAL,
  "published" BOOLEAN NOT NULL DEFAULT false,
  "content" VARCHAR(1000),
  "title" VARCHAR(191) NOT NULL,
  "buffer" BYTEA,
  PRIMARY KEY ("id")
);

Integrated database seeding (Preview)

A common requirement, especially for local development, is the ability to quickly seed your database with initial data. This is now possible with Prisma using the new prisma db seed command which is introduced in Preview in this release. Seeding is currently supported via scripts written in TypeScript, JavaScript, Go and Shell.

The command expects a file called seed with the respective file extension inside your main prisma directory.

  • JavaScript: prisma/seed.js
  • TypeScript: prisma/seed.ts
  • Go: prisma/seed.go
  • Shell: prisma/seed.sh

For example, this prisma/seed.ts file could be invoked using the new command:

// prisma/seed.ts

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// A `main` function so that we can use async/await
async function main() {
  const newUser = await prisma.user.create({
    data: {
      email: "[email protected]"
    }
  })
  console.log(`new user created`, newUser.id)
}

main()
  .catch((e) => {
    console.error(e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

To execute the seeding, run the new command with the --preview-feature flag:

prisma db seed --preview-feature

Please provide feedback for the new prisma db seed command here.

Throw exceptions in findFirst and findUnique queries if no record is found

With the new rejectOnNotFound option, you can now tell Prisma Client to throw an exception when findFirst or findUnique does not find any records.

Here's an example:

const user = await client.user.findUnique({
  where: {
    id: 10,
  },
  rejectOnNotFound: true
})
// Throws "NotFoundError: No User found" if the 
// user with id = 10 does not exist.

If you omit rejectOnNotFound, these calls continue to return undefined.

Improved API for filtering arrays in PostgreSQL

We've added some new capabilities to your where condition for filtering arrays in PostgreSQL:

  • has: a value is contained within the array
  • hasEvery: all values are contained within the array
  • hasSome: at least one values is contained in the array
  • isEmpty: the array is empty

Here's an example:

model User {
  id    Int    @id
  roles Role[]
}

enum Role {
  ADMIN
  EDITOR
  READER
}
const admin = await prisma.user.findFirst({
  where: {
    id: 1,
    roles: {
      has: 'ADMIN'
    }
  }
})

Learn more about this feature from this GitHub comment.

More powerful counting of records using select

When using count queries, you can provide a number of options, e.g. for filtering. This release introduces the select option for count queries which lets you filter for non-null values of multiple fields in a single query.

Assume you have this User model with a number of optional fields:

model User {
  id        Int       @id @default(autoincrement()) @db.Integer
  createdAt DateTime  @default(now())
  name      String?
  email     String?
  birthday  DateTime?
}

You can send the following query to retrieve the count of records that contain non-null values for the respective field:

const userCounts = await prisma.user.count({
  select: {
    name: true,
    email: true,
    birthday: true
  } 
})

This will return an object with the following structure, where the value of each field indicates how many records in the database contain a value for it:

{
  name: 2,
  email: 0,
  birthday: 1
}

This is also works with aggregate and groupBy:

// new possibility:
const usersAggregation = await prisma.user.aggregate({
  count: { name: true }
})

// same for group by:
const groupedByName = await prisma.user.aggregate({
  by: ["name"],
  count: true
})

// or more fine-grained control over the fields to be counted
const groupedByNameCount = await prisma.user.aggregate({
  by: ["name"],
  count: { name: true, _all: true }
})

Modifying relations by directly setting foreign keys is now stable

In 2.11.0, we introduced the uncheckedScalarInputs preview flag which allowed you to modify relations by directly setting foreign keys in your queries (as opposed to using a nested write with the connect option).

Fire up that delete key because you can now remove this flag from your Prisma schema.

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

As a reminder, this allows you to set foreign keys directly:

// An example of the new API that directly sets the foreign key
const user = await prisma.profile.create({
  data: {
    bio: 'Hello World',
    userId: 42
  },
})

// If you prefer, you can still use the previous API via `connect`
const user = await prisma.profile.create({
  data: {
    bio: 'Hello World',
    user: {
      connect: { id: 42 }, // sets userId of Profile record
    },
  },
})

Read more about in the documentation on relation queries.

More improvements for Prisma Migrate

  • Prisma Migrate now detects when the migrations don’t match the configured provider on your datasource block, for example when the migrations have been created with sqlite but the provider is now set to postgresql. Prisma Migrate will now print a helpful error message in these cases.
  • prisma migrate reset can now be used in non-interactive environments (e.g. CI/CD) by passing the --force flag.
  • The new seeding functionality (see above) will be automatically triggered whenever prisma migrate reset is called to reset and repopulate the database in development. It's also triggered when the database is reset interactively after calling prisma migrate dev.

Dark mode for Prisma Studio 🌒 & more powerful filtering

As of this release, Prisma Studio can be used in dark mode! You can use the Settings icon in the top right corner to switch between light and dark mode.

We also included more powerful ways for you to filter the records of a table:

  • Filter by Json fields
  • Filter by the ID of a related model

Changes to the nativeTypes Preview feature

This version of introduces a few changes to the nativeTypes Preview feature:

  • Removed the Numeric alias for Decimal on PostgreSQL, MySQL and Microsoft SQL Server. Replace any Numeric types with Decimal when you upgrade.
  • Removed the Serial, SmallSerial, and BigSerial aliases for INT AUTOINCREMENT, SMALLINT AUTOINCREMENT, and BIGINT AUTOINCREMENT on PostgreSQL. You can use Int @default(autoincrement()), Int @db.SmallInt @default(autoincrement()) or Int @db.BigInt @default(autoincrement()) when you upgrade.
  • Renamed JSON to Json on MySQL.
  • Renamed Datetime to DateTime on MySQL.

Breaking changes

  • We've upgraded our RHEL base image from CentOS 6 to Amazon Linux 2. CentOS 6 reached end-of-life on November 30th, 2020. This may affect machines still running Amazon Linux 1. If you run into problems with this upgrade, please don't hesitate to reach out.
  • We've renamed the FindOneModelArgs and FindManyModelArgs type definitions to improve consistency. See this issue for more details.
  • Following the deprecation in 2.12.0, this release we've removed findOne and moved many of the Typescript types under the Prisma namespace.

Other

Transaction API for Prisma Client Go

Prisma Client Go now supports database transactions with a sparkly new Transaction API:

createUserA := client.User.CreateOne(
	db.User.ID.Set("c"),
	db.User.Email.Set("a"),
)
createUserB := client.User.CreateOne(
	db.User.ID.Set("d"),
	db.User.Email.Set("b"),
)
err := client.Prisma.Transaction(createUserA, createUserB).Exec(ctx)
if err != nil {
	return err
}

Learn more about Transaction in the reference. If you'd like to try out Prisma Client Go, check out the Quickstart for a gentle introduction.

SQL Server TLS Support on Mac

We now support secure connections between a Mac and SQL Server so your data is encrypted while in transit.

Fixes and improvements

Prisma Schema

Prisma Client

Prisma Migrate

Prisma Studio

Prisma Engines

Credits

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

prisma - 2.14.0

Published by timsuchanek almost 4 years ago

We hope everyone enjoyed their holidays and recharged for 2021! Today, we are excited to share the 2.14.0 stable release 🎉

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

Major improvements

Group By queries are now in Preview

Prisma Client now supports group by queries! Opt-in to this feature by adding the groupBy flag to the generator block in your Prisma schema:

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

 model Agent {
   id         String @id
   name       String
   location   String
   rate       Float
 }

Now you can re-generate your Prisma Client to have access to the new groupBy API:

npx prisma generate

With the updated Prisma Client, you can invoke the new groupBy query:

const locations = await client.agent.groupBy({
  by: ['location'],
  min: {
    rate: true
  },
})

// Result:
// [
//   { location: "Los Angeles", min: { rate: 10.00 } },
//   { location: "London", min: { rate: 20.00 } },
//   { location: "Tokyo", min: { rate: 30.00 } }
// ]

Prisma also supports the having side of group by, so you can further filter your groups:

const locations = await client.agent.groupBy({
  by: ['location', 'rate'],
  min: {
    rate: true
  },
  having: {
    rate: {
      gte: 20
    }
  }
})

// Result:
// [
//   { location: "London", rate: 20.00, min: { rate: 20.00 } },
//   { location: "Tokyo", rate: 30.00, min: { rate: 30.00 } }
// ]

Read more in the documentation.

Linux ARM64 support

Good news for Linux users! Prisma now supports Linux ARM64 out of the box. If you already generate the Prisma Client on a Linux ARM box, it will just work. To target the specific binary, you can add a binaryTarget to the generator block in your Prisma schema:

generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["linux-arm-openssl-1.1.x"]
}

Learn more in the documentation.

Prisma Migrate fix for PostGIS users

PostgreSQL users who are using the PostGIS extension can now use Prisma Migrate as well.

Breaking changes

This release introduces a breaking change for TypeScript users. Prisma Client now requires TypeScript v4.1 or above. You can read more about upgrading your TypeScript version on their wiki.

Fixes and improvements

prisma

prisma-client-js

migrate

language-tools

studio

prisma-engines

Credits

Huge thanks to @qsona for helping!

Help shape the future of Prisma

We love open-source and are commited to building world-class database tools that make developers more productive. In addition to building open-source tools, we are currently planning a cloud offering that will improve many database workflows, especially in collaborative environments.

If you want to help us shape the future of this offering, we would much appreciate if you could fill out this short survey that represents a potential onboarding flow for that cloud offering.

prisma - 2.13.0

Published by timsuchanek almost 4 years ago

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

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

Major improvements

Prisma Migrate is now in Preview

We are releasing Prisma Migrate in Preview; read the announcement blog post to learn more. This version is the evolution of the Experimental Prisma Migrate we released last year. We've changed Migrate to be more predictable and providing fine-grained control over how exactly database schema changes are carried out. You can learn more about the Preview stage in the Prisma docs.

Please try out Prisma Migrate and share your feedback for it here.

Auto-generated migrations files in plain SQL

Prisma Migrate still picks up the changes in your Prisma schema file to generate migration files. The main difference compared to the previous Migrate version is that these migration files are now plain SQL and fully customizable; this allows for:

  • More control over how exactly schema changes are performed (e.g., renaming an existing column)
  • Performing data migrations
  • Using certain database features that can't be represented in the Prisma schema (e.g., creating stored procedures or triggers)
  • Orchestration of complex changes (e.g., an expand and contract pattern)

Integrated workflows for development and production

This evolved version of Prisma Migrate is now deterministic making sure migrations are always executed in a predictable way. The tool supports both workflows for deploying migrations to production and other environments. It also comes with an interactive development command that not only helps to create and apply migrations, but also helps developers to get back on track when they run into certain issues.

Breaking changes when upgrading from the Experimental version

The new Preview version is not backward compatible with the previous Experimental version. You can learn more about the upgrade process in the docs.

Import types and enums in the browser

Until now, you could not import any typings that are generated by Prisma Client in a browser application. This changed in this release! With 2.13.0, you can now import all your enums and all types from Prisma Client in any browser environment. This also works across all the universal Javascript frameworks like Next.js, Blitz, Gatsby, and Vue.js.

Let's take a look at an example of a React component utilizing the new exports. Assume you have the following Prisma schema:

model User {
  id      String @id
  hobbies Hobby[]
}

enum Hobby {
  Tennis
  Prisma
  Basketball
}

Once you've generated the @prisma/client node module, you can import the generated types in your frontend application as follows:

import { Hobby, User } from '@prisma/client'

type Props = {
  user: User
}

export function HobbyComponent({ user }: Props) {
  return (
    <div>
      Hello {user.name}! <br />
      The available hobbies are: <br />
      <ul>
        {Object.values(Hobby).map(hobby => <li key={hobby}>{hobby}</li>)}
      </ul>
    </div>
  )
}

Lots of improvements for Prisma Studio

New keyboard shortcuts in the standalone app

Navigating tabs

You can now use your keyboard to navigate between tabs in the Prisma Studio standalone app:

  • CMD+SHIFT+[ OR CMD+OPTION+: Navigate to left tab
  • CMD+SHIFT+] OR CMD+OPTION+: Navigate to right tab

Zooming in and out

You can now use your keyboard to zoom in and out in the Prisma Studio standalone app:

  • CMD++ OR CMD+SHIFT++ to zoom in
  • CMD+- OR CMD+SHIFT+- to zoom out

Improved UX for inline editing of arrays

Inline editing of arrays (scalar lists) has sometimes been cumbersome with the Prisma Studio UI. With this release, we include a smoother UX for this.

Note that you can try out Studio with some sample datasets here.

Prisma Client Go now supports JSON

We've had JSON support in Prisma Client JS for quite a while, but we're pleased to announce that the Go version of Prisma Client now has JSON support as well. Head over to the documentation to learn more!

🌎 Join us for the second Prisma Online Meetup

Join us online for the second Prisma Meetup and learn more about the Preview version of Prisma Migrate from Alberto Perdomo and Tom Houlé who have been deeply involved building it.

  • When? December 09, 2020 6pm CET
  • Where? Youtube

Fixes and improvements

prisma

migrate

language-tools

studio

prisma-engines

Credits

Huge thanks to @qsona for helping!

prisma - 2.12.1

Published by timsuchanek almost 4 years ago

prisma - 2.12.0

Published by timsuchanek almost 4 years ago

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

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

Major improvements

Standalone Prisma Studio app for macOS

We have repackaged Prisma Studio to work also as a standalone macOS application. This should help you run Studio with just a double click and without opening your terminal, just in case you quickly want to browse or edit your data.

Download the installation files from the Studio release page. Support for more platforms (Windows and Linux) will come soon. Let us know if which one you would want first!

Prisma codemods help upgrading your codebase

With today's release, we took the opportunity to cleanup some rough edges in the Prisma Client API which partially results in breaking changes. To help you with upgrading your codebase to 2.12.0, we're introducing @prisma/codemods.

The @prisma/codemods package provides a powerful CLI that scans your codebase and automatically updates the code to the new API calls from the provided version.

The upgrade workflow looks like this:

cd my-app
npm install @prisma/cli @prisma/client
npx @prisma/codemods update-2.12 ./

Microsoft SQL Server now supports native database types (Preview)

Hot off the presses: You can now use database native types with Microsoft SQL Server! You'll need to specify both previewFeatures = ["microsoftSqlServer", "nativeTypes"] to get started:

generator js {
  provider        = "prisma-client-js"
  previewFeatures = ["microsoftSqlServer", "nativeTypes"]
}

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

model User {
  id   BigInt  @id @default(autoincrement()) @ms.BigInt
  name String? @ms.VarChar(255)
}

model Post {
  id        BigInt @id @default(autoincrement()) @ms.BigInt
  title     String @ms.VarChar(100)
  views     BigInt @default(0) @ms.BigInt
  wordCount Int    @default(0) @ms.SmallInt
}

Note that Prisma Migrate does not yet work with Microsoft SQL Server, nor does Prisma Client Go.

Upcoming Prisma Migrate Preview Release

We’ve got a Preview release of Prisma Migrate nearing up with a large set of changes. You can test it in Early Access, see the upcoming changes, and provide feedback! Get started with the Early Access version here.

To join the conversation, join the #product-feedback channel on our Slack.

Breaking changes

As mentioned before, we're cleaning up the Prisma Client API which partially results in breaking changes. You can upgrade to the latest version using the new @prisma/codemods package as explained above.

Remove non-$ methods

A few months back, we began prefixing our top-level Prisma methods with $. For example, prisma.transaction became prisma.$transaction. We did this to avoid clashes with your application's model names.

The non-$ methods were deprecated but continued to work until this release. In this release, we removed the deprecated methods.

This means if you are still using calls like prisma.transaction or prisma.disconnect instead of prisma.$transaction or prisma.$disconnect in your code, your app is going to break after upgrading to 2.12.0.

The @prisma/codemods workflow describe above will automatically fix any remaining non-$ methods in your codebase.

You can read more about this change in on Github.

1-1-relations must now have an optional side

In this version, we're adding a new requirement for 1-1-relations that you define in your Prisma schema. In previous versions, it used to be allowed to have both sides of the relation required. As of this release, the virtual side of the relation (i.e. the side that does not store the foreign key in the underlying database) must be optional.

Before

model User {
  id      Int      @id @default(autoincrement())
  name    String?
  profile Profile  // ❌ this is not allowed as of 2.12.0
}

model Profile {
  id     Int    @id @default(autoincrement())
  user   User   @relation(fields: [userId], references: [id])
  userId Int
}

After

model User {
  id      Int      @id @default(autoincrement())
  profile Profile? // ✅ the virtual side of the relation needs to be optional
}

model Profile {
  id     Int    @id @default(autoincrement())
  user   User   @relation(fields: [userId], references: [id])
  userId Int
}

The easiest way to adjust your schema to these new requirements is by running the introspect command which will automatically make the virtual relation fields optional on 1-1-relations:

npx prisma introspect

Fix how data for Json[] fields is stored

We fixed how the Json[] type is stored in 2.12.0. Previously, we were storing JSON arrays as a string inside a your database's JSON column. Now, we properly encode JSON arrays as JSON in the database. This fix will allow us to add database native JSON operations down the line.

If you are using the Json[] type in your schema, you'll need to migrate your data. We anticipate this breaking change will only affect a handful of folks. Please reach out to us in this issue and we'll help you with the migration.

Here is an overview of how the behaviour changes in 2.12.0:

Given 2.11.0 2.12.0
[] [[]] []
[{test:"test"}] ["{\"test\":\"test\"}"] [{"test":"test"}]
[{ test: "test" }, { test: "test2" }] ["[{\"test\": \"test\"}, {\"test\": \"test2\"}]"] [{"test": "test"},{"test": "test2"}]
[3] 3 [3]

Deprecations

Rename findOne to findUnique

This release renames findOne to findUnique and deprecates findOne.

We made this change to reduce confusion. Many people expected findOne to be more loose, e.g: "Find the first record that matches my conditions.".

The @prisma/codemods workflow describe above will automatically rename findOne to findUnique across your codebase.

Move most types under the Prisma namespace

We moved most of the generated types under a new Prisma namespace and are deprecating the top-level exports. This change also resolves some existing namespace clashes.

Before

import { PrismaClient, User, UserCreateInput } from '@prisma/client'

async function createUser(input: UserCreateInput): Promise<User> {
  return prisma.user.create(input)
}

After

import { PrismaClient, User, Prisma } from '@prisma/client'

async function createUser(input: Prisma.UserCreateInput): Promise<User> {
  return prisma.user.create(input)
}

This means that with this release, there are exactly three kinds of exports in @prisma/client:

  1. PrismaClient is the constructor your Prisma Client instance
  2. Model types, e.g. User and Post
  3. Prisma as the new namespace under which you can now access the remaining generarted types

The @prisma/codemods workflow describe above will automatically fix the type names in your code!

With this change, we've greatly reduced the number of reserved words that could clash with your application's names. Go forth and add models with names like Transaction or Aggregate!

Fixes and improvements

prisma

prisma-client-js

migrate

language-tools

studio

prisma-engines

Credits

Huge thanks to @matt-eric, @muxahuk for helping!

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