fastify-typescript
fastify-typescript copied to clipboard
chore(deps): update prisma monorepo
This PR contains the following updates:
| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| @prisma/cli (source) | 2.14.0 -> 2.20.1 |
||||
| prisma (source) | 2.17.0 -> 2.21.2 |
Release Notes
prisma/prisma
v2.20.1
Today, we are issuing the 2.20.1 patch release.
Fix
v2.20.0
Today, we are excited to share the 2.20.0 stable release :tada:
:star2: Help us spread the word about Prisma by starring the repo or tweeting about the release. :star2:
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.
napi is now in Preview
N-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 N-API will not affect your workflows in any way, the experience of using Prisma will remain exactly the same.
The N-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
- Unclear Introspection error message: Error parsing attribute "@id": Fields that are marked as id must be required.
- [Introspection] Defaults set as expressions (as required in MySQL on some column types) not picked up
- Introspection: More information in
Schema is inconsistenterror message - prisma introspect overrides generator fields
- Tests: add tests for
prisma formatcli command - prisma migrate gives: Error querying the database: db error: ERROR: syntax error at or near "NOT"
- Introspection does not recognize Default Expressions
- Failing describer on MySQL with empty view definition
- Introspection failed: Getting definition from Resultrow ResultRow { columns: [\"name\", \"definition\"], values: [Text(Some(\"sp_helpdiagrams\")), Text(None)] } as String failed
prisma migrateset field as unique automatically
Prisma Client
- Add a
pushmethod to scalar list update input in addition to set - $transaction doesn't roll back in NestJS when we pass method from external service
- when case-insensitive mode enabled in where clause, unnecessarily LOWER() function and ILIKE operator is used at the same time
- Invalid response data: the query result was required, but an empty Object((Weak)) was returned instead.
- regression: Running multiple findUnique's in parallel causes both to return null
- PANIC in query-engine/core/src/interpreter/query_interpreters/inmemory_record_processor.rs:111:80called
Result::unwrap()on anErrvalue: FieldNotFound { name: "origin", model: "Field not found in record Record { values: [Int(1011), String(\"https://woman.mynavi.jp/article/190924-7/\")], parent_id: None }. Field names are: [\"id\", \"link\"], looking for: \"origin\"" } - Internal: Setup Renovate for https://github.com/prisma/engines-wrapper
- Rename
SKIP_GENERATEfrom Client postinstall script toPRISMA_SKIP_POSTINSTALL_GENERATE
Language tools (e.g. VS Code)
Security Fixes
We fixed two security issues:
- Command injection vulnerability in @prisma/sdk in getPackedPackage function This is a low-severity issue and no users have been affected
- Visual Studio Code Prisma Extension Remote Code Execution Vulnerability This is a high-severity issue and we recommend all Prisma VS Code extension users verify that they have automatically been upgraded to the latest version. There is no evidence that this vulnerability has been exploited.
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!
:tv: 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.
v2.19.0
Today, we are excited to share the 2.19.0 stable release :tada:
:star2: Help us spread the word about Prisma by starring the repo or tweeting about the release. :star2:
Major improvements & new features
Prisma Migrate is now ready for General Availability :rocket:
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 resetanddb 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 devproduces 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)
:books: 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
- Order by relation aggregate (like count)
- when quering, passing string to DateTime field results runtime error
- Log streaming interface for n-api
- Add TypeScript version check
- Do not know how to serialize a BigInt in executeRaw
- TypeError when using
npx prisma generatewith custom engine binaries - MICROSOFT SQL CONNECTOR - CONNECTION LIMIT
- Default
pool_timeoutvalue hides connect timeouts
Prisma Migrate
- Error: [introspection-engine/connectors/sql-introspection-connector/src/misc_helpers.rs:417:72] called
Option::unwrap()on aNonevalue - Environment is “non-interactive” when using
prisma migrate dev - Unclear error message when using prisma-level default functions (cuid, uuid) as default for non-nullable fields
- Change enum values when there is a default enum value fails migration
- Error: Error in migration engine. Reason: [libs/sql-schema-describer/src/walkers.rs:329:18] foreign key references unknown table: "Game"
- Prisma
migrate devprompts for migration name when running after --create-only - Error: Error in migration engine. Reason: [migration-engine/connectors/sql-migration-connector/src/sql_renderer/sqlite_renderer.rs:229:45] not implemented: text
- Unformatted error message from
introspectwhen env var contains wrong connection string protocol - SQL Server: recursive error message "Error querying the database"
- Prisma migrate - always reporting Data loss / migration file changed even with simple field addition
- Detect usage of supported types in Unsupported("..")
- Feedback on migrate command names
- Migration fails creating new database on Managed DO Postgres
- "Database error: Error querying the database: db error: ERROR: type "citext" does not exist" but citext extension enabled
- ME crash: foreign key references unknown table
- Migrate does not recognize changes made to a field of type String to ENUM
- Postgres Introspection occasionally removes "Unique" Constraint
- Docs: Migrate advisory locking mechanism
- Write test repro for "We assume an internally valid datamodel before mutating." from example schema
- Can't convert
Stringfield toEnumin a migration - Postgres - Review CLI help outputs / flags
- Error: Error in migration engine. Reason: [libs\datamodel\core\src\transform\attributes\unique_and_index.rs:149:46] called
Result::unwrap()on anErrvalue: TypeMismatchError { expected_type: "constant literal", received_type: "string", raw: "tenantId", span: Span { start: 6221, end: 6231 } } - error report id: 13104
- Ensure we run generate after
db pushandmigrate deveven if the changes result in no database schema changes - Improve readability of data loss warnings when running
migrate dev
Language tools (e.g. VS Code)
Prisma Studio
Credits
Huge thanks to @endor, @iBluemind, @meeq for their help in this release! :sparkles:
:briefcase: 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
:tv: 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.
v2.18.0
Today, we are excited to share the 2.18.0 stable release :tada:
:star2: Help us spread the word about Prisma by starring the repo or tweeting about the release. :star2:
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:
- In this release, we are introducing a new command
prisma db pull, which behaves exactly the same asprisma introspect. - We will at some point in the near future add a deprecation warning to the
prisma introspectCLI command. - Eventually,
prisma introspectwill 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
- Error connecting to GCP cloud sql using ssl connection
- Error opening a TLS connection: unknown Cert Authority
- Filter based on number / count of relations
- Issue with not closing DB connections
- Errors at nested writes
- Add update of non-existent node to known errors
- Handle illegal parameters in raw SQL queries gracefully
- Upsert not creating all entries
- uncheckedScalarInputs: XOR not working?
- Query produces
WHEREclause with 1=0 as condition - User ID type instead of int to enable database transparency
- Internal: Send Slack message for each CLI release
- Improve on autogenerated bug report urls
- $transaction should fallback to union if it can't give unwrap a proper output
- Some exported types no longer available in Prisma namespace in 2.17
Prisma Migrate
- Error: [libs/datamodel/connectors/dml/src/datamodel.rs:175:14] Every RelationInfo should have a complementary RelationInfo on the opposite relation field.
- Empty index name:
ERROR: zero-length delimited identifier at or near """" - Prisma Migrate: Better UX when referencing migrations in resolve command
- Introspection crash when relation name is only used on one side.
- Annotated relation field doesn't appear to be required for 1-n relations
- No validation error on 1:m ambiguous relation
- Improve handling of unexecutable migrations in Prisma Migrate
- Error: [libs/datamodel/connectors/dml/src/datamodel.rs:162:14] Every RelationInfo should have a complementary RelationInfo on the opposite relation field.
- Error using totvs database:
Couldn\'t parse default value - Prisma format and issues with implicit relations
- Migration Script Created With Foreign Key Fields in Wrong Order
- Prisma seed incompatible with Nextjs et al. projects
- Prisma Migrate - Drift detected error on each migrate run even when nothing changes in DB/Schema
- When configuring
ShadowDatabaseUrlto use Prisma Migrate in the cloud, a valid URL is always enforced across every environment, even though it's only needed in development. - Add
prisma db pullcommand for introspection - ENUM in prisma migration
Prisma Studio
- Hiding a field, refreshing, then showing the field again is problematic
- Add ability to unlink optional relation
- Should be able to scroll filter column selection
- Unable to reset
DateTimefield tonull - Feature request: Being able to select entries to download/export as JSON
- optional Int fields show NaN even if no values were entered
- Argument id for data.id must not be null
- Prisma Studio prevents saving changes when nullable values
- Unable to deselect all relations
Language tools (e.g. VS Code extension)
Prisma engines
- executeRaw does not work with updateMany mutation in transaction
- Migrate: catch soft reset errors in CLI
:pencil: 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.
:tv: 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.
v2.17.0
Today, we are excited to share the 2.17.0 stable release :tada:
:star2: Help us spread the word about Prisma by starring the repo or tweeting about the release. :star2:
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 seednow 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 :tada:
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.
Expand to learn more about the benefits of native types
##### Rich column type mapping for Prisma typesEach 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.BooleanforBooleanwhereas MySQL uses@db.TinyInt - Written in PascalCase (for example,
VarCharorText) - Prefixed by
@db, wheredbis the name of thedatasourceblock in your Prisma schema
Type attributes give you:
- Exact control over what native type Prisma Migrate creates in the database - for example, a
Stringcan be@db.VarChar(200)or@db.Char(50) - An enriched schema when you introspect - you can see if
Stringisvarchar(200)or justtext.
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.
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 useprisma migrate deployinstead. - Improved error handling when Prisma Migrate finds empty migration directories, e.g.
prisma/migrations/20210119114009_init(missingmigration.sqlfile). - 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 pushnow 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
—-forcehas been renamed to--accept-data-lossto 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-resetwhich 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).
- The flag
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
--schemaoption when running the command - Define a default schema location in your
package.jsonwhich 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_namefix: 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 returnServer name cannot be determined. Additionally, when running a shared Azure SQL database, if the firewall setting was set toredirect(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 errorServer 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/NCharlength and a maximum of 4000 forVarChar/Char/VarBinary/Binarylength. The actual maximums are4000for first and8000for the latter types. - PostgreSQL numeric type fix: In certain cases, when using
executeRawto insert number values to anumerictype in PostgreSQL, sometimes the stored value would be zero instead of the user input. An example value of12345.0is 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 tonumericwithout any trouble.
Bug fixes in Prisma Studio
- Studio can now display fields that are of type
ByteandBigInt. - Usage of the
createManypreview 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 fromFloattoDecimal. Alternatively, you can also runprisma introspectwhich will automatically remap the previousFloatfields toDecimal. Note that this will also change the type that Prisma Client returns fromNumbertoDecimal.js. - If you would like to change the column's type in the database from
Decimal(65,30)toDouble, leave the Prisma schema as is and create a new migration. Prisma Migrate will alter the column's type toDouble. Note that if you have rows with data for the column, they will be cast fromDecimal(65,30)toDouble.
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
- postgresql column type date error
- Fixed-size column types as part of identifiers do not work on MySQL
- Query engine panics when the ID used to create a record and the actual ID in the database are different
- [Native Types] Ensure that fields of unsupported types aren't dropped
- Concurrent updates that don't interfere with each other
- [MySQL] Throw a better error message when connection is rejected due to self signed ssl certificate
- $executeRaw throws PostgreSQL ERROR: invalid scale in external "numeric" value or inserts 0.0
- Change parameter type of prisma.$transaction
- Weird required array typing
- Passing null to a string some filter crashes the engine
- PANIC: index out of bounds: the len is 1 but the index is 1
- Request URL is too long
- findFirst with
undefinedvalue shouldn't return data - Prisma not combining queries for GraphQL server, leading to N+1 issues
- Inconsistent PascalCasing for DMMF type names
- @map not carried over to
makeEnum - @ignore and @@ignore support in the client
- Stabilize
nativeTypes - Prisma can not connect to
localhostfor MySQL, MariaDB and SQL Server (mostly when running those via Docker) - Invalid client generation when use model named "Record"
- Negative number cannot be entered as string to Decimal input
- @prisma/client version 2.16.x spams [dotnev][DEBUG] logs
- Add
PRISMA_DISABLE_WARNINGS - $transaction doesn't rollback in case any transaction fails
- Prisma client looks in root directory (C:) for engine binary when used with Next.js
- UUID values are not automatically converted to their binary form on write on mysql and sqlite
- 2.8.0 and above: MySQL, 'tinyint unsigned' field considered as 'boolean'
Prisma Migrate
- Ignoring table during introspection
- Prisma Migrate cannot reset the database when the user has insufficient privileges - this makes Prisma Migrate incompatible with some hosted cloud providers
- Error when migration directory exists but migration script is missing
- Error: Error in migration engine. Reason: [libs/datamodel/core/src/transform/ast_to_dml/validate.rs:226:34] called
Option::unwrap()on aNonevalue - Schema notation to not surface specific models in the Prisma Client API
- Migrate creates unnecessary migrations
- Migrate renames my indexes & throws Drift detected error even when nothing changes in DB/Schema
- Argument M is out of range for Native type NVarChar(4000) of SQL Server
ALTER TYPEenum migrations fail in PostgreSQL- prisma migrate dev: schema validation happens late in the process
- Implement @ignore on the field level
- Keep @@ignore and @ignore during Re-Introspection
- Preserve
@@​ignoreand@ignoreon re-introspection - Migrate: Postgres connection string without port prints
undefined db seednot documented in help output forprisma db --help- DB seed does not work with custom schema location from package.json
- Mention
prisma migrate deployinmigrate devnon interactive error message for better discoverability. prisma migrate dev --create-only- if there are data loss warnings, the CLI prompts suggest the new migration will be applied when it is (rightfully)not
Language tools
- Ensure
@ignorecode completion is supported in VS code extension - Remove the feature flag for nativeTypes for stabilization, so the native types logic is always active.
Prisma Studio
Prisma Engines
- Implement database locking in the migration engine
- Apply
clippytomigration-engine - Apply
clippytointrospection-engine - Apply
clippytolibs/datamodel - Apply
clippyto alllibs/*(except datamodel) - Run clippy on CI
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!
v2.16.1
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
v2.16.0
Today, we are excited to share the 2.16.0 stable release :tada:
:star2: Help us spread the word about Prisma by starring the repo or tweeting about the release. :star2:
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"]
}
:books: 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 pr</details>
---
### Configuration
:date: **Schedule**: At any time (no schedule defined).
:vertical_traffic_light: **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
:recycle: **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
:ghost: **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://togithub.com/renovatebot/renovate/discussions) if that's undesired.
---
- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box.
---
This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/hmake98/fastify-typescript).