Prisma - 用于数据库查询,迁移和建模的现代数据库工具包
Prisma - 用于数据库查询,迁移和建模的现代数据库工具包 pimeys released this
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
Assets
2
timsuchanek released this
Today, we are excited to share the 2.15.0
stable release
Major improvements
Prisma Migrate now supports native database types (Preview)
In 2.11.0, we introduced support for native database types in the Prisma schema that allow you to map Prisma's scalar types to more specific types in the underlying database. However, these have not been compatible with the current Preview version of Prisma Migrate yet.
This release makes it possible to use Prisma Migrate with the native type annotations in your Prisma schema!
Expand for an example usage of Prisma Migrate with native types
Here's an example that uses several type annotations:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Post {
id Int @id @default(autoincrement()) @db.Integer
published Boolean @default(false)
content String? @db.VarChar(1000)
title String @db.VarChar(191)
buffer Bytes?
}
Running a migration using the prisma migrate
command, the following SQL is created:
CREATE TABLE "Post" (
"id" SERIAL,
"published" BOOLEAN NOT NULL DEFAULT false,
"content" VARCHAR(1000),
"title" VARCHAR(191) NOT NULL,
"buffer" BYTEA,
PRIMARY KEY ("id")
);
Integrated database seeding (Preview)
A common requirement, especially for local development, is the ability to quickly seed your database with initial data. This is now possible with Prisma using the new prisma db seed
command which is introduced in Preview in this release. Seeding is currently supported via scripts written in TypeScript, JavaScript, Go and Shell.
The command expects a file called seed
with the respective file extension inside your main prisma
directory.
- JavaScript:
prisma/seed.js
- TypeScript:
prisma/seed.ts
- Go:
prisma/seed.go
- Shell:
prisma/seed.sh
Expand for an example seeding workflow using TypeScript
For example, this prisma/seed.ts
file could be invoked using the new command:
// prisma/seed.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// A `main` function so that we can use async/await
async function main() {
const newUser = await prisma.user.create({
data: {
email: "sarah@prisma.io"
}
})
console.log(`new user created`, newUser.id)
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
To execute the seeding, run the new command with the --preview-feature
flag:
prisma db seed --preview-feature
Please provide feedback for the new prisma db seed
command here.
Throw exceptions in findFirst
and findUnique
queries if no record is found
With the new rejectOnNotFound
option, you can now tell Prisma Client to throw an exception when findFirst
or findUnique
does not find any records.
Here's an example:
const user = await client.user.findUnique({
where: {
id: 10,
},
rejectOnNotFound: true
})
// Throws "NotFoundError: No User found" if the
// user with id = 10 does not exist.
If you omit rejectOnNotFound
, these calls continue to return undefined
.
Improved API for filtering arrays in PostgreSQL
We've added some new capabilities to your where
condition for filtering arrays in PostgreSQL:
has
: a value is contained within the arrayhasEvery
: all values are contained within the arrayhasSome
: at least one values is contained in the arrayisEmpty
: 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 yourdatasource
block, for example when the migrations have been created withsqlite
but theprovider
is now set topostgresql
. 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 callingprisma 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 forDecimal
on PostgreSQL, MySQL and Microsoft SQL Server. Replace anyNumeric
types withDecimal
when you upgrade. - Removed the
Serial
,SmallSerial
, andBigSerial
aliases forINT AUTOINCREMENT
,SMALLINT AUTOINCREMENT
, andBIGINT AUTOINCREMENT
on PostgreSQL. You can useInt @default(autoincrement())
,Int @db.SmallInt @default(autoincrement())
orInt @db.BigInt @default(autoincrement())
when you upgrade. - Renamed
JSON
toJson
on MySQL. - Renamed
Datetime
toDateTime
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
andFindManyModelArgs
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 thePrisma
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
- Stabilize
uncheckedScalarInputs
- No warning is printed when
@prisma/cli
and@prisma/client
have different versions inpackage.json
- Connected fields do not get an updated by @updatedAt
- Error: Provided String, expected DateTime or DateTimeFieldUpdateOperationsInput
- $connect doesn't throw error on mysql connector if database is not reachable
- New count functionality
- Enable strict mode across the codebase
- Add types for
$on('beforeExit')
- Error due to sockets file getting deleted
- Sqlite client: ConversionError(cannot parse integer from empty string)
- Array relation unpack error
- OR operator behaving like AND
- Remove deprecated features
- Slow Nested Queries - taking 2 seconds plus
- Querying a relation field with include or select returns the wrong type
- Cannot read property 'isCanceled' of undefined
- Grouping by required fields should be not have nullable output type
- Enforce mutual exclusivity of
select
&include
(in Client requests) through types - PostgreSQL: "PANIC: column on null constraint violation error in /root/.cargo/git/checkouts/quaint-9f01e008b9a89c14/a1decce/src/connector/postgres/error.rs:67:35"
- Fails inside node cluster - Address already in use
- Rename FindOneModelArgs & FindManyModelArgs to ModelFindOneArgs and ModelFindManyArgs
Prisma Migrate
- Prisma Migrate: Improve UX when switching providers
- Ability to use
prisma migrate reset
in non-interactive environments prisma migrate reset
fails if the db is not already initialized
Prisma Studio
- Allow filtering of JSON fields
- Allow filtering by relation fields
- Linux app icon is incorrect
- Cannot open intended Model using Prisma Studio's search window with keyboard shortcut
Prisma Engines
Credits
Huge thanks to @qsona, @mikebobadilla, @cyrus-za for helping!
Assets
2
timsuchanek released this
We hope everyone enjoyed their holidays and recharged for 2021! Today, we are excited to share the 2.14.0
stable 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
- Support number is an input for BigInt fields
- Deploying to Heroku does not generate Prisma Client by default
- Create fail with multiple connectOrCreate and connect
- Sequential $transaction with $executeRaw
- Transaction items run outside Postgres transaction (breaks) with random order
- Add more jsdoc to Prisma Client
- Rename findOne in dmmf.schema.outputObjectTypes.prisma Query
- Errors with setting foreigns keys directly
- multiple identical compound unique fields with different types not generating multiple types
- The target table of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause.
- Prisma Migrate: Error creating shadow database
- Integrate Linux ARM in TypeScript
- Reintrospection Bug on Relations
- Prisma Migrate: Omit schema name when creating enum types?
- Tearing down MSSQL schema returns "Cannot read property 'split' of null"
- prisma introspect drops some @relation custom names in existing schema
- Implement
react-prisma
prototype - unable to run migrations in an empty PostGIS db
prisma-client-js
- Group By
- Generated Github issue creation links do often not include helpful information
- PANIC: expected 0 parameters but got 1 (when running $executeRaw
...
)
migrate
language-tools
- While Prisma extension is enabled, typescript server keeps crashing on each save
- Transition open-vsx extension to Eclipse Cloud Development Tools working group
- Renaming models in schema.prisma may break whole file
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.
Assets
2
timsuchanek released this
Today, we are issuing the 2.13.1
patch release.
Fixes
- Introspection: Reintrospection Bug on Relations #4582
- Prisma Client: Limitation when using
INSERT..OUTPUT
if the table has triggers on MSSQL - Prisma Migrate: Removing a model with a foreign key fails on MSSQL
- Prisma Migrate: Schema name in CREATE statements leads to errors when using enums
Improvements
Assets
2
timsuchanek released this
Today, we are excited to share the 2.13.0
stable 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
- Expand --version command
- Generating client to custom location with Next.js is broken
- Expose types to the frontend for Next.js
- Adjust
prisma init
to write to .env instead of prisma/.env - Native Types Postgres: Introspecting timestamp[] and time[] break client generation
- Understand Prisma $connect behavior
deleteMany
should be valid without parameters- sqlserver Introspection Fails With "No such table: information_schema.columns" Based on Case Sensitive Database Collation
- Allow
deleteMany
without args in TypeScript - Make Prisma Client (usage + generation) ASAR compatible
- Add
Symbol.toStringTag
to Prisma Client - Breaking change: Error classes are exported as types
- Deprecated types are not seen as such
- Adjust wording of comment when
dbgenerated()
is added via introspection - Hint for codemod should highlight command in backticks and/or colored
- XOR introduces regression in type safety
migrate
language-tools
- Connection to server got closed. Server will restart
- VC Code extension stopped working
- Rename doesn't rename multiple models of the same relation
- Syntax highlighting broken for Json and Float field
studio
- Editing of enum & boolean lists is sub-par
- Opened a non-existing project from the history and can't restart Studio
- Zoom in/out with keyboard shortcuts
prisma-engines
- Supporting SQL Server in Migration Engine
- Return a user-facing error for database URL parsing errors.
- CI: Find a reliable way to shut down docker after the tests have finished
Credits
Huge thanks to @qsona for helping!
Assets
2
timsuchanek released this
Today, we are issuing the 2.12.1
patch release.
Fixes
Client
Assets
2
timsuchanek released this
Today, we are excited to share the 2.11.0
stable release
Major Improvements
Native database types in the Prisma schema (Preview)
We are super excited to share that this release brings you one of the most requested features since we released the initial version of Prisma: The representation of native database types in the Prisma schema.
Up to this release, the Prisma schema only allowed to represent a limited set of types: String
, Int
, Float
, Boolean
, DateTime
, Json
. Each of these types has a default mapping to an underlying database type that's specified for each connector (see the mappings for PostgreSQL and MySQL).
With this release, you can now add an attribute to a field definition in order to determine which specific database type it should be mapped to. Here is an example for a PostgreSQL database that specifies the underlying database types more specifically. Note that you also need to enable the feature via the the nativeTypes
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["nativeTypes"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String? @db.VarChar(255)
}
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(100)
createdAt DateTime @db.Timestamp(6)
wordCount Int @db.SmallInt
}
In the above code snippet, all fields of the two Prisma models are annotated with attributes to diverge from the default mapping and determine the exact type that is used in the underlying database. For example, the id
fields are represented as db.BigInt
which maps to the BIGINT
PostgreSQL type. You can find out more about which Prisma types can be annotated with which native type attributes in the docs for the PostgreSQL and MySQL connectors.
Please share your feedback on how this feature works for you. We are interested in both positive and negative feedback, so we know if this feature is already ready for production! (If encounter any problems, please open a new issue here).
New types in the Prisma schema: BigInt
, Bytes
and Decimal
(Preview)
With this release, we are further introducing three new scalar types in the Prisma schema: BigInt
, Bytes
and Decimal
. Here is an overview for how they map to the different databases that are supported by Prisma and how they're represented when queried with Prisma Client JS:
Prisma | PostgreSQL | MySQL | SQLite | JavaScript / TypeScript |
---|---|---|---|---|
Bytes |
BYTEA |
LONGBLOB |
n/a | Buffer |
Decimal |
DECIMAL(65,30) |
DECIMAL(65,30) |
n/a | Decimal.js |
BigInt |
BIGINT |
BIGINT |
n/a | BigInt |
To make use of these new types, you need to enable the nativeTypes
feature flag in your Prisma schema:
generator client {
provider = "prisma-client-js"
+ previewFeatures = ["nativeTypes"]
}
Once you added the feature flag, be sure to run prisma generate
again to update your local version of Prisma Client.
Set foreign keys directly (Preview)
We now support writing foreign keys (also known as relation scalars) directly with the uncheckedScalarInputs
preview feature.
Consider this sample Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["uncheckedScalarInputs"]
}
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
authorId Int
author User @relation(fields: [authorId], references: [id])
}
Instead of using connect
when creating a new Post
record to wire up a relation with a User
record, you can now directly set the authorId
value:
await prisma.post.create({
data: {
// You can now set the foreign key directly...
authorId: 1,
// ... or connect the relationship...
// author: {
// connect: {
// id: 1
// }
// }
// ... but not both at the same time
},
});
We'd love for you to give it a try. You can give us feedback in this issue.
The $transaction
API is now stable
You can now use $transaction
API without the transactionApi
feature flag.
generator client {
provider = "prisma-client-js"
- previewFeatures = ["transactionApi"]
}
The connectOrCreate
API is now stable
The connectOrCreate
API offers a convenient way to link or insert nested records.
You can now use it without the connectOrCreate
feature flag.
generator client {
provider = "prisma-client-js"
- previewFeatures = ["connectOrCreate"]
}
Middleware model parameter is now typed
This is a small quality-of-life improvement for developers using the Prisma middleware. The params.model
parameter that's passed into a middleware function is now typed to your model so you can now reliably tie middleware to models:
prisma.$use(async (params, next) => {
switch (params.model) {
case 'user':
// ...
case 'project:
// ...
}
})
If you need the old behavior you can cast params.model
back to a string
by wrapping it String(params.model)
.
Deprecation of multi-provider array
You will now see a warning if you have multiple providers in your datasource
. We recently realized that supporting an array of providers in the Prisma schema was premature, adding complexity in the process of improving the product, and causing some confusion about our intent.
You can read more about the decision and what to do about it in this issue.
Validate PrismaClient
inputs at runtime
We now validate the parameters
we accept in new PrismaClient(parameters)
. This is unlikely to affect you unless you were passing invalid parameters into PrismaClient
before.
Prisma Client Go is now Early Access
🎉
We're happy to announce that Prisma Client Go has graduated from experimental to Early Access.
You can get started here. We'd love to learn more about how you use the Go Client during Early Access. You can schedule a call with us or chat with us on Slack in the #prisma-client-go channel. We're looking forward to hearing from you!
📺
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, November 12 at 5pm Berlin | 8am San Francisco.
👀
Make your online talk recordings more accessible with subtitles
We'd love to help you make your talk recordings (no matter if Meetup or conference talk) more accessible by adding subtitles to it for free! Reach out to sponsorships@prisma.io if you are interested in getting subtitles for your videos!
Fixes and improvements
prisma
- Can't create a record with only the foreign key to another table
- Foreign key field is not being set when using a nested create for a one-to-one relation
- Prisma Client is unable to fetch DateTime lists
- Middleware params model should be an enum or union of strings.
- vercel/pkg broken on windows
- vercel/pkg errors on windows
- Introspection fails instantly MariaDB
- DATABASE_URL verification still attempted when datasource override provided in PrismaClient constructor
- Introspection should try to preserve custom Enum names on MySQL even without @map
- Mutliple 1-n self relations break migrations
- .transaction([]) fails with Request Timeout Error on large dataset
- JSON value truncate floating numbers
- Postgresql: Large double precision float values cause panic
- Error in prisma results in unhandled promise rejection
- Consolidate Undici error handling
- Internal: update our
pnpm
version used for development and CI - Internal: Create new milestone check GitHub Action
- Prisma and Netlify, binary is not downloaded automatically since 2.8.0
- Detect and enforce Node Version in
preinstall
hook so pnpm fails clearly - Package name reuse (.prisma/client) when generating multiple prisma clients causes issues with some other libraries (e.g. jest)
- Native Types: @db.BigInt should be BigInt
- Prisma generate or introspect don't work when nativeTypes preview is enabled
- Cannot update a model with composite keys through a referenced model
- RangeError: Invalid count value during create
- Prisma Client doesn't load root .env
- You are trying to load env variables which are already present in your project root .env
- Stabilize connectOrCreate
- Stabilize transactionApi
- Add integration test to trigger env var warning in Prisma Client
- Improve error when using prisma migrate --experimental with native types
prisma-client-js
language-tools
- Add Prisma icon to standard icon theme in VSCode
- Gitpod Support
- prisma.plugin.nextjs.addTypesOnSave broken
studio
- Unable to view / edit DateTime lists
- Case insensitive searching
- npx prisma studio doesn't work on WSL 1
- Cannot type "." in a float column
- Websockets fails when studio is behind a reverse proxy
- [design] Cell overflow
prisma-engines
Assets
2
timsuchanek released this
Today, we are excited to share the 2.9.0
stable release
Improvements
In today's release, we have many bug fixes, increased test coverage, and improved error messages. The release also lays the foundations for the upcoming native database types support.
Errors thrown by Prisma Client include the version
With this release, error objects thrown by Prisma Client include the clientVersion
field which contains the version of Prisma Client. This is useful for debugging and creating issues.
Improved error message of prisma.$transaction
When you use prisma.$transaction
to group multiple calls into a single transaction, you need to pass an array of promises. Passing calls that have been awaited will now trigger a more helpful error:
Error: All elements of the array need to be Prisma Client promises. Hint: Please make sure you are not awaiting the Prisma client calls you intended to pass in the $transaction function.
Already existing preview features from previous releases
Just a quick reminder:
- In version
2.6.0
we introduced one preview feature, namelyatomicNumberOperations
. - In version
2.1.0
we introduced two preview features, namelyconnectOrCreate
andtransactionApi
.
In case they're useful for you, please give them a try and share your feedback! These features remain in preview in this release.
Issues closed with the release
prisma
- Switch to stable actions/stale once my PR is merged
We can't release, as the e2e tests are not passing for the ${tag} npm tag!
checks wrong npm tag for passing e2e tests when promoting a patch-dev to latest- Client seems to ignore Custom Binary Specification
- Tests / GitHub Actions check why cached download test is really slow
- Merge
PrismaQueryEngineError
intoPrismaClientUnknownRequestError
- Incorrect SQL generated for Json field { equals: null } filter
- Any Client error message should include the Client version
prisma -v
should include Client version as well (if installed)- $executeRaw used in a transaction throws: All elements of the array need to be Prisma Client promises.
- Test forks
- Code coverage
- Consolidate integration tests
- Include possible block names on a wrong keyword
- Optional field is required in @@unique and where clause and doesn't accept null
prisma introspect
overwrites a 1:1 mapping as 1:many- Replace ncc with esbuild in cli
- cli/introspect tests should exit
- Implement env var
FORCE_PANIC_INTROSPECTION_ENGINE
- DMMF Enum value types are invalid in 2.8.0
findFirst
should have return typeModel | null
- Unexpected field not found (FieldNotFound) error
- Non unique index should not appear in findOne where clause
prisma-client-js
- PostgreSQL
<table>WhereUniqueInput
including a column which isn't unique when composite primary key is used - Improve error message when object is passed to
prisma.$transaction
instead of a Prisma promise - Export
Sql
from @prisma/client - Prisma and node 12.19.0
language-tools
- Quick fixes for typos in block names
- Include reason of publish CI in every workflow and slack notification
- Autocomplete stops showing after the first character
- Changing the datasource name doesn't break the schema
- Can we check for the presence of the other extension and disable one or warn the user clearly
- extract the possible keywords from prisma-fmt error message
- Remove vsce from renovate ignore list
- VS Code extension not formatting for v2.8.1
- Get preview features from prisma-fmt
- Enum @default() autocomplete putting comments as options
studio
- Navigating from relations table triggered
Error: Could not find appropriate InputType for this field type. This should never happen.
- t.toUpperCase is not a function - prisma 2.8.0
- Studio doesn't let me save the newly created record
- Studio sometimes gets stuck on
Saving Changes
prisma-engines
- Supporting SQL Server in Introspection Engine
- Datamodel validator capability to prevent a foreign key on pointing to a nullable field
- Remove explicit attached name from generated SQL on SQLite
- Remove explicit database name from generated SQL on MySQL
- Schema Parser should validate supplied feature flags
default()
does not work in conjunction with native types- Postgres: serial native type and
@default(autoincrement())
must not be possible at the same time - Implement a
debugPanic
RPC in introspection engine - Add arguments to Mysql native type TINYINT
- Schema validation rejects fields with native type TinyInt and Scalar Type Boolen
Credits
Huge thanks to @rahul3v for helping!
Interested in providing feedback for the upcoming version of Prisma Migrate?
We are seeking users interested in trying out upcoming versions of Prisma Migrate. This will involve trying it out, validating functionality, and sharing feedback with us.
If you're interested in participating, fill out the following form, it won't take longer than a minute!
🌍
Join us for the first Prisma Online Meetup on October 27, 2020
Join with engineers from all around the globe for the Prisma Online Meetup to learn about database best practices, the Prisma inside scoop, and examples of Prisma in production on October 27 at 6pm CET.
Featured in this Meetup:
- Tammy Bryant, Principal SRE of Gremlin: “Database horror stories”,
- Herve Labas, Prisma’s VP of Product, talking about the future of Prisma and its roadmap,
- Success story of an app built with Prisma told by its creator.
The event will be streamed on YouTube.
Assets
2
timsuchanek released this
Today, we are issuing the 2.8.1
patch release.
Fixes
Prisma Client
Studio
Assets
2
timsuchanek released this
Today, we are issuing the 2.7.1
patch release.
Fixes
Prisma Client JS
Prisma Studio
Assets
2
Today, we are issuing the 2.6.2
patch release.
Fixes
Prisma Client JS
Assets
2
Today, we are issuing the 2.5.1
patch release.
Fixes
Prisma Client JS
- List Relation Filter issue just in 2.5.0 #3342
- Filtering by null seems to be broken in 2.5 #3352
- New error after update to 2.5 for "not null" query #842
Studio
- Bug fixes
Assets
2
timsuchanek released this
Today, we are issuing the 2.4.1
patch release.
When we released the new "Order by multiple fields" feature, you gave us feedback, that the order of properties is not stable in JavaScript. Since ES2015 that is not a problem in the language itself anymore.
However, some teams use the eslint sort-keys plugin, which sorts the keys of objects by alphabet.
Therefore we decided to change the API in a patch release to minimize any problems this might cause to you.
Order by multiple fields in 2.4.0
// order by `age` descending and then by `name` ascending
const users = await prisma.user.findMany({
orderBy: {
age: 'desc',
name: 'asc'
}
})
Order by multiple fields in 2.4.1
// order by `age` descending and then by `name` ascending
const data = await client.user.findMany({
orderBy: [
{
age: 'desc',
},
{
name: 'asc',
},
],
})
Assets
2
Today, we are issuing the 2.4.0
stable release.
Major improvements
Order by multiple fields
A long-awaited feature - the ability to order by multiple fields in Prisma Client is finally here!
Until now you could only order by a single scalar field of a model. The API design however was already prepared for ordering multiple fields with the object syntax we have. Instead of just one property, that orderBy
object can now have as many fields as you want! The order of the fields hereby determines the order of the returned list (see example below).
Note: As this is an incremental change in the API, we introduce this feature without a feature flag.
You can use it like so:
// order by `age` descending and then by `name` ascending
const users = await prisma.user.findMany({
orderBy: {
age: 'desc',
name: 'asc'
}
})
As mentioned by the comment, the returned objects in users
are ordered first by age
(descending), and then by name
(ascending).
Top-level Client Methods: $
dollar prefix for top-level Prisma Client methods
In recent versions, we introduced a couple of top-level methods in Prisma Client (e.g. prisma.transaction()
and prisma.use()
) in preview mode. The immediate feedback was that the denylist for model names grew - which breaks Prisma schemas where a model is called Transaction
, transaction
, use
, or Use
. And the list goes on...
In order to have a future-proof API, that allows maximum expressibility in terms of model names, we decided to prefix all non-query methods with a dollar sign $
. That means Prisma Client will from now on ship with the following methods:
Pre-existing
$disconnect
$connect
$on
$queryRaw
$executeRaw
Still in preview
$use
$transaction
The preview methods have already been renamed, the pre-existing methods like connect
are still available, you just get a deprecation warning. They will be available for a few more releases with an alias, so no hurry to update them yet.
Updates in Prisma Studio
With this release, we shipped a number of improvements for Prisma Studio:
- Refreshed design
- Moved the Reload button from the right of the databrowser to the left
- Moved the Pending Actions bar from the bottom of the databrowser to the top right
- Removed the sidebar; to open a model, you can now press the New Tab button on the top
- Removed the code editor
- Removed the tree view
- Added ability to view and edit JSON fields
Try out Prisma Studio in the online demo or in your Prisma project by running:
npx prisma studio --experimental
Preview features
Changes to middlewares
and transactionApi
As mentioned above, we ar changing the names of some the top-level Prisma Client methods. This affects the two preview features middlewares
and transactionApi
.
middlewares
You still need to enable the preview feature via the generator
block in your Prisma schema to access it:
generator client {
provider = "prisma-client-js"
previewFeatures = ["middlewares"]
}
Before
prisma.on()
After
prisma.$on()
transactionApi
You still need to enable the preview feature via the generator
block in your Prisma schema to access it:
generator client {
provider = "prisma-client-js"
previewFeatures = ["transactionApi"]
}
Before
prisma.transaction()
After
prisma.$transaction()
Already existing preview features from 2.1.0
, 2.2.0
, and 2.3.0
Just a quick reminder:
- In version
2.1.0
we introduced two experimental features, namelyconnectOrCreate
andtransactionApi
. - In
2.2.0
we introducedaggregateApi
. - In
2.3.0
we introducedmiddlewares
and thedistinctApi
.
In case they're useful for you, please give them a try and share your feedback! These features remain in preview in this release.
🌟
Help us spread the word about Prisma
To help spread the word about Prisma, we'd very much appreciate if you would star this repo
Fixes and improvements
prisma
- [Introspection] Do not print
@default("")
for String fields - Prisma introspect: extra field for self-relations
- Prisma 1 CLI (for versions smaller than 1.34) and Prisma 2.0 CLI share the same command
- Clarify schema comments
CreateInput
andUpdateInput
have different typings for optional relations- Loss of precision on Float fields
- pgbouncer=true flag not working as expected with a relation and enums on both sides of the relations
- Relation + enums + pgbouncer fails with a ConnectorError
- Implicit m-n relations have an extra
@relation
field after introspection - Supported feature combination coverage (MySQL + SQLite)
- Support setting a timeout for SQLite
- CLI won't run in AWS Lambda
- Prisma Client is generated twice when
output
is specified ongenerator
- [Re-Introspection]
@@map
and@map
with argumentname
loses thename
after re-introspection - Surface schema validation errors during Re-Introspection and change flow
- Validate uniqueness of names of indexes on databases which doesn't allow two indexes with the same name
- [Re-Introspection] Enum with
@map
will get option commented if it invalid without map - optional one-to-many relationship: none/every filters: Incorrect SQL generated
- Problems with middleware for tracing
- Self-referential one-to-one relationship. Incorrect SQL for
{ where: { non_fk_field: null } }
prisma-client-js
- Ability to sort results by multiple attributes
- Upsert should allow where clause with only undefined
- AWS Lambda: Unknown error in Prisma Client
migrate
language-tools
- Add support for /* Prisma */ syntax highlighting
- Extension only release automation
- Publish Insider extension on every commit
- Extension only sub-patch release process
- A patch release for CLI should be based on a tag and not master
- Dev instructions for working with language server are outdated.
- Streamline debugging of language server before published to npm
- Implement workaround for hanging types in LSP
- Run e2e tests before publishing on mac, windows as well
- Blank lines removed in model one by one in VS Code
- Syntax highlighting broken when using map attribute inside enum
- Formatting does not add missing relation automatically
- Show previewFeatures in generator block as auto-completion suggestion
- @unique only gets suggested once per model block
- Recognize usage of experimentalFeatures and give warning and quick-fix
- Using F2 on relation field leads to broken schema
- Snapshot tests for change-readme script
studio
prisma-engines
Assets
2
Today, we are issuing the 2.3.0
stable release.
Major improvements
Rename Helper Tool in VSCode Extension
The Prisma VS Code extension now helps you rename models, fields and enums:
Introspection uses order of columns in table to order fields in model
prisma introspect
until recently ordered all fields in models alphabetically. Starting with 2.3.0 it now picks up the order from the columns in your database table and uses that same order for the fields in your models in your Prisma Schema file.
Preview Features
Renaming "Experimental features" to "Preview features"
With 2.1.0 we introduced feature flags for Prisma Client, called "Experimental Features". The property in the schema has been renamed from experimentalFeatures
to previewFeatures
to better communicate what they actually are.
generator client {
provider = "prisma-client-js"
- experimentalFeatures = ["..."]
+ previewFeatures = ["..."]
}
Already existing preview features from 2.1.0 and 2.2.0
Just a quick reminder: In version 2.1.0
we introduced two experimental features, namely connectOrCreate
and transactionApi
.
In 2.2.0
we introduced aggregateApi
.
In case they're useful for you, please give them a try and let us know! They stay in preview in this release.
New: Distinct API
In 2.3.0
we introduce distinct querying capabilities to Prisma Client.
It allows you to query for distinct (unique) rows of a model.
In other words: The fields you provide in the distinct
argument will be duplicate free.
Feature flag
Distinct querying needs to be enabled with the feature flag discintApi
like so:
generator client {
provider = "prisma-client-js"
previewFeatures = ["distinct"]
}
Usage
Distinct is only a filter and doesn't change the return type of the findMany
query.
const result = await prisma.user.findMany({
where: {},
distinct: ['name']
})
New: Middlewares API
In 2.3.0
we introduce a Middlewares API. It allows you to hook into the control flow of Prisma Client.
Feature flag
Middlewares need to be enabled with the feature flag middlewares
like so:
generator client {
provider = "prisma-client-js"
previewFeatures = ["middlewares"]
}
Usage
const client = new PrismaClient()
client.use(async (params, next) => {
console.log('params', params)
const before = Date.now()
const result = await next(params)
const after = Date.now()
console.log(`Query ${params.model}.${params.action} took ${after - before}ms`)
return result
})
const data = await client.user.findMany({})
This will log the following:
params {
args: {},
dataPath: [],
runInTransaction: false,
action: 'findMany',
model: 'User'
}
Query User.findMany took 2ms
Middlewares allow you to both manipulate the params
and the result.
They are called in an "onion" fashion. If you have multiple middlewares, this is the order of things being called:
const client = new PrismaClient()
client.use(async (params, next) => {
console.log('1')
const result = await next(params)
console.log('4')
return result
})
client.use(async (params, next) => {
console.log('2')
const result = await next(params)
console.log('3')
return result
})
Prints:
1
2
3
4
While Prisma Client's middlewares work a bit different, they're by inspired Koa's middlewares.
Fixes and improvements
prisma
- [Re-Introspection] Keep order of models of existing Prisma schema
- Sort fields by the user's defined order not alphanumerically
- Add minimal integration test for studio
- Default value for relations
- Supporting querying distinct rows
- Omit full path when running prisma --version
- (Re)Introspection does not respect variables in dotenv file when schema is located in a custom directory
- Use denylist in Introspection already
- Clarify usage of datasource url when using SQLite -
file:
is what works andsqlite:
sqlite://
should error - Postinstall hook fails with custom location for schema.prisma
- [Introspection] Pick up order of columns in database into schema
- Aggregate function is missing typing for
where
- [2.2] Not loading ./prisma/.env variables when ./.env exists
- Rename the following items: - "model Transaction" after upgrade from 2.1 to 2.2
- Output feature flags in
prisma -v
- Add
previewFeatures
as replacement forexperimentalFeatures
prisma-client-js
- Investigate Amazon RDS Proxy
- Improve automatically generated error reports
- The ID's/techinique used to looked up nest relationships differs and results in a PANIC error, depending on what fields are included or not included in a
select
- Middlewares
- Enum value 'false' breaks Prisma client create
migrate
- Add linebreak at the end of
migrate.lock
file to avoid git history mess - Using
env("DATABASE_URL")
freezes migrations - Changing IDs in explicit n-m relationship results in no change
- @prisma/migrate makes react types required
- Abort on unexecutable migrations
- Null constraint violation on the fields: (
id
) - @prisma/cli calling migrate save with a prisma schema error hangs indefinitely
language-tools
- "Error parsing attribute "@@relation": The relation field
post
on Modelfoo
must specify thefields
argument in the @relation directive." - Add Rename Helper Tool
- Try to execute the binary in the "is binary download needed?" check
- Keep root package.json version in sync with subfolders
- LSP should have its own test cases
- Separate vscode text/links from language server
- Check existing LSP version in CI before publishing
- CI fails if master changes during the run
- Validation for values of
@default
attributes when they are functions - Put caret into created model or enum after creating it via quick-fix
- Add quick-fix gif to README
- @updatedAt not showing up for auto-completion
- Auto-completion adds too many quotation marks
- Formatter not working: Cannpt execute binary file
studio
- How to navigate to related records?
- Loading state shows column titles later than actual empty table
- Console is full with ag-grid warnings
- Text editing operations shouldn't change based on data type
- Consider removing the delete button
- Can't select a related row in "add row" dialog
- Deleting required relation crashes
- Table view doesn’t show new field
- Adding relation in new record won’t load more than one record in other table
- Int fields are
0
instead ofnull
prisma-engines
- Check whether the ForeignKeyDefaultDrop destructive change check is still needed
- [Introspection] Comment out Models that do not have a strict unique criteria
- Rust cuid() implementation may output more than 25 characters
- Examine our implementation of CUIDs
- Forbid to update int fields that are
@default(autoincrement())
- Parser Refactoring: Split Field type into RelationField and ScalarField
Credits
Huge thanks to @RafaelKr for helping!
Assets
2
Today, we are issuing the 2.2.2
patch release.
With 2.2.1 the wrong binary was released, this new patch fixes it.
The new binary hash from npx @prisma/cli@2.2.2 -v
is a9e8c3d97ef2a0cf59256e6b26097f2a80f0a6a4
Assets
2
Today, we are issuing the 2.2.1
patch release.
Fixes and improvements
Prisma CLI
Prisma Client JS
- Aggregate function is missing typing for
where
#2959 - Unable to generate Prisma Client with aggregateApi enabled #772
Studio
- Bug fixes
Assets
2
Today, we are issuing the 2.2.0
stable release.
Major improvements
Next to a lot of bug fixes, this version includes a number of new features!
Quick fix suggestions in Prisma VSCode Extension
The Prisma VS Code extension now helps you fix any accidental typos and offers more convenient "Quick Fixes" right inside your editor.
Make datasource provider
dynamic via environment variables
The provider
field on the datasource
defininitions in your Prisma schema now also accepts an array of strings (instead of just a plain string). This can be helpful when you want to switch environments which point to different databases based on an environment variable. Learn more about this feature here.
datasource db {
provider = ["sqlite", "postgres"]
url = env("DATABASE_URL")
}
Experimental features
Already existing experimental features
Just a quick reminder: In v2.1.0
we introduced two experimental features, namely connectOrCreate
and transactionApi
. In case they're useful for you, please give them a try! They stay experimental in this release.
Re-Introspection
We were able to continue to improve the re-introspection flow based on your feedback. Thanks!
Aggregations API
While Prisma Client already provides a count
query for each model, we now introduce further aggregation functionality for number fields.
If your model has a field of type Int
or Float
, the following aggregations will be available:
sum
: Sum up all values of a field for the selected rows.min
: Get the minimum value for a field for the selected rows.max
: Get the maximum value for a field for the selected rows.avg
: Get the average value for a field for the selected rows.
Example
Note, that the count
API is always available, while sum
, min
, max
, and avg
are only available for a model if it has a number field.
Prisma Schema | Prisma Client Query | Result |
---|---|---|
model User {
id Int @id
age Int
name String
}
|
const result = await prisma.user.aggregate({
where: { age: { gt: 5 } }, // optional
count: true,
avg: {
age: true,
},
max: {
age: true,
},
min: {
age: true,
},
sum: {
age: true
}
})
|
{
"count": 10,
"avg": {
"age": 80
},
"max": {
"age": 163
},
"min": {
"age": 5
},
"sum": {
"age": 800
}
}
|
Feature flag
In order to enable this experimental feature, note that you need to set the feature flag aggregateApi
in the Prisma Client generator block in your schema:
generator client {
provider = "prisma-client-js"
experimentalFeatures = ["aggregateApi"]
}
Please share your feedback on how this feature works for you. We are interested in both positive and negative feedback, so we know if this feature is already ready for production! (If encounter any problems, please open a new issue here).
Fixes and improvements
prisma
- Make datasource provider dynamic via environment variables
- Introspection doesn't recognize enums in PostgreSQL
- [Introspection] Investigate if our Introspection queries (can) return the correct order of columns
- PrismaClient throw error on missing is env even when overwriting database connection
- Pagination: cursor is ignored when using negative take argument
- Generator error hidden
prisma generate
throws exit code 0 in case of error caused by denied keywords- .env not loaded when running
prisma migrate (save | up | down) --schema <file-path>
- MySQL: Unreachable database host leads to unknown error
- Prisma format ignores newlines at the end of files
- Prisma introspection should add a trailing newline
- Introspection: Use env vars to override introspection binary with --url --print
- @prisma/engine-core's package.json uses a github url for its version of undici
- Unify prisma introspect and prisma introspect --url wrt re-introspection
- Strange @@relation error message when running prisma generate
- Support selections using basic aggregations
- Re-introspection error for renamed relations when there are multiple relations to the same table
- Introspection doesn't add or loses trailing new line of schema file
- UUID Cursor Pagination
- Schema validation: @default(autoincrement()) on a String field should be rejected
- Switch to undici
- Introspect removes experimental features from schema
- Add new line checks to integration tests
prisma-client-js
- Add more integration tests for unhappy paths
- Better error message when generated Client and local Prisma schema are out of sync
- Multiple quick
count
requests result inInvalid prisma.web_hooks.count invocation
- Wrong jsDocs annotations for
create
anddelete
- Raw API concerns
- Improve sqlite error messages
- JSON Filter does not work
- Bulk Operations Naming Conflict
- Transaction API is not writing the transaction
- Expose debug mode to trigger a panic for reproductions
migrate
migrate up
tells me to read in./migrations/MIGRATION_ID/README.md
- Create new SQL Database missing first char on name
migrate save/up
hangs while creating databaseREADME.md
of migration folder includesquaint
in SQL- Validate
@default(now())
so that it only can be used in DateTime fields
vscode
- Publish lsp server to npm
- Quick Fix for fields with unknown types
- Remove test cases that point to a four digit versioning scheme
- Run integration tests on an extension release
- Add instructions for each feature in README
- Composite keys are not considered valid?
- README on marketplace does not show Prisma Logo
- Lerna bootstrap does not install all dependencies
- Connection to server got closed. Server will restart.
- Investigate
***
in GH action output
studio
- Allow for column resizing
- Table scroll area should start underneath table header
- Select range of records when holding shift key
- Table's loading illustration may overlap with the table content
- Tooltips for table header columns
- Type to edit Enums and Booleans with autocomplete
- Copy & paste from a cell does not seem to work
- A better databrowser table
- In the "connect to X" view I would like to connect when clicking on a row
- Loading state shows unexpected data
- Scrolling down in relation accordion does not show entries
- After editing relation only the number of unsaved changes is shown in main table
- Styling of editing Int is different from editing String
- Loading state is not really indicated
prisma-engines
Assets
2
timsuchanek released this
Today, we are issuing the 2.1.3
patch release.
Fixes and improvements
Studio
- Roll back new table view due to regressions
Assets
2
timsuchanek released this
Today, we are issuing the 2.1.1
patch release.
Fixes and improvements
prisma migrate
Assets
2
timsuchanek released this
Today we release the first patch release 2.0.1
.
This is the first time that we run our new patch process! And it looks like everything went well
Improvements
- The database detection in
prisma introspect
got improved so there are fewer false positives that tell users their database is Prisma 1.
Assets
2
nikolasburk released this
💡
What is Prisma 2.0?
Today's General Availability release features Prisma Client, a type-safe and auto-generated query builder for your database. Thanks to introspection, Prisma Client can be used for existing databases as well.
Note: Prisma Migrate and Prisma Studio are not part of today's release. They're still experimental.
🚀
Getting started
The easiest way to get started is by following the Quickstart (5 min). It is based on a SQLite demo database and doesn't require any setup!
You can also connect Prisma to your own PostgreSQL or MySQL database, either in an existing project or when starting from scratch.
✉️
Let us know what you think
As always, we very much appreciate your feedback! Please don't hesitate to reach out here on GitHub or on Slack if you have any questions, thoughts, or any other kind of feedback about Prisma!
⬆️
Upgrading from Prisma 1
If you're currently using Prisma 1 and want to upgrade to the new version, you can start by learning about the upgrade process in the docs: How to upgrade
If you have any questions or feedback about the upgrade process, please create a GitHub issue in our new feedback repo. You can also share your personal feedback path with us and we'll try to figure out the best way to upgrade with you!
We're also planning upgrade webinars, where we're demoing the upgrade process for different scenarios (e.g. using prisma-binding
, Prisma Client, Nexus, ...). The webinars are currently planned for July, we'll announce the dates soon!
🌎
Join us online for Prisma Day on June 25th and 26th
We're hosting another edition of Prisma Day this year and are going fully remote. Join us online for hands-on workshops on June 25th and great talks on June 26th. Some of the speakers include GitHub co-founder Tom Preston-Werner, Netlify CEO Mathias Biilmann Christensen and lots of Prisma folks to tell you the latest about Prisma 2.0.
Assets
2
timsuchanek released this
Today, we are issuing the ninth Beta release: 2.0.0-beta.9
(short: beta.9
).
Enforcing arrays in OR
We used to allow this syntax:
const orIncorrect = await prisma.post.findMany({
orderBy: {
id: 'asc'
},
where: {
OR: {
title: {
equals: "Prisma makes databases easy"
},
authorId: {
equals: 2
}
}
}
});
However, the thing that we want is this:
const orCorrect = await prisma.post.findMany({
orderBy: {
id: 'asc'
},
where: {
OR: [{
title: {
equals: "Prisma makes databases easy"
},
}, {
authorId: {
equals: 2
}
}]
}
})
So only the array syntax makes sense, therefore we also only allow that from now on.
Fixes and improvements
prisma
- Expose a logger interface
- Emit an error event when the database connection is interrupted
- Limit implicit m-n relations to primary keys only
- Rename pinnedPlatform to pinnedBinaryTarget
- @prisma/engine-core forces users to enable esModuleInterop
prisma-client-js
- findMany / OR accepts non-array value - should only accept arrays
- Queries and mutations stuck (runs forever?) if log option is ['query', 'warn']
vscode
prisma-engines
- Use exact id column type for the version check during introspection
- add
uniqueIndexes
to Model in DMMF - bring back
default
for Field in DMMF
Credits
Huge thanks to @Sytten for helping!
Assets
2
timsuchanek released this
Today, we are issuing the eighth Beta release: 2.0.0-beta.8
(short: beta.8
).
Breaking change: Splitting .raw
into .queryRaw
and .executeRaw
When dealing with raw SQL queries, there are two things we care about - the "return payload", which is being calculated by the SELECT
statement we use and the number of affected rows - if we for example do an UPDATE
query.
Until now, Prisma Client decided under the hood with a heuristic, when to return the number of affected rows and when to return the result data.
This heuristic broke if you wanted the opposite of what the heuristic returned.
That means that the decision has to be made by the developer using Prisma Client instead.
Therefore, we remove the raw
command and replace it with executeRaw
and queryRaw
.
So what does return what?
executeRaw
returns the number of affected rowsqueryRaw
returns the result data
The heuristic used to return the data for SELECT
statements. So if you upgrade to Beta 8, you need to use queryRaw
for your SELECT
statements and executeRaw
for all SQL queries, which mutate data.
The rule of thumb is: Do not use executeRaw
for queries that return rows.
In Postgres, it will work to use executeRaw('SELECT 1)
, however, SQLite will not allow that.
Fixes and improvements
prisma
- Make sure Netlify deployments are not listed with their .netlify.com domain in Google and Co
- .raw doesn't return data if query doesn't start with SELECT statement
- Prisma 2.0.0-beta.7
npx prisma generate
issue if working directory contains spaces - JSON type is broken for array. Array comes back as
string
. - Error: spawn node --max-old-space-size=8096 .\node_modules@prisma\client\generator-build\index.js ENOENT
- Add a test case for project paths with spaces
prisma-client-js
- Prisma Client removed on adding a new package: Error: @prisma/client did not initialize yet
- JSON types should return a JSON object and not a JavaScript object
- Datasource override from client constructor doesn't match the datasource block from the schema.prisma file
Credits
Huge thanks to @Sytten, @merelinguist for helping!
Assets
2
timsuchanek released this
Today, we are issuing the fifth Beta release: 2.0.0-beta.5
(short: beta.5
).
Major improvements
Support for Alpine Linux
From now on, you don't need to build your own binaries for Alpine Linux and all musl-based distros anymore. They're shipped by default with the Prisma CLI and Prisma Client.
Support for Node v14
The new Node v14 is from now on fully supported with the Prisma CLI and Prisma Client.
Fixed issues with JSON support in Prisma Client
You can now use the new Json
type that was introduced in the last release also in Prisma Client.
Fixes and improvements
prisma
- Provide binaries for Alpine Linux
- Prisma create failing with query interpretation errors
- Cannot update a column value to null?
- Add syntax highlighting to more tools
- Binary targets for FreeBSD in Beta4 no longer working
- Prisma CLI is throwing segmentation fault with node 14 (fs.writeFileSync arg)
prisma-client-js
- missing FROM-clause entry for table
- Automatically serialize a non ISO date string if it is serializable by javascript date object
- Can't create record with Json
migrate
vscode
prisma-engines
Credits
Huge thanks to @Sytten for helping!
Assets
2
Today, we are issuing the fourth Beta release: 2.0.0-beta.4
(short: beta.4
).
Major improvements
Introducing prisma format
From now on, you can run prisma format
in your project, to make your schema.prisma
pretty without the VSCode extension
Support for Yarn workspaces
Prisma now supports Yarn workspaces
Making Prisma Client generation more robust with .prisma
folder
The generation of Prisma Client into node_modules
sometimes caused problems with package managers (e.g. Yarn) which would occasionally delete the generated code.
In order to make the generation more robust, Prisma Client is now generated into a folder called node_modules/.prisma
. Because of the leading dot in the folder name, package managers do not touch the folder any more. This results in the following folder structure:
node_modules/
↪ .prisma
↪ client
↪ schema.prisma
↪ index.js
↪ index.d.ts
↪ query-engine-darwin
↪ @prisma/client (imports the generated code from `.prisma`)
Note that the generated Prisma Client code in .prisma
is now imported into @prisma/client
which means there is no change for how you import and use Prisma Client in your code! You can still import Prisma Client as before with:
import { PrismaClient} from '@prisma/client'
Open Prisma Studio in specific browser
The prisma studio --experimental
command now accepts a --browser
option to let you choose your preferred browser for Prisma Studio, e.g.:
prisma studio --browser "Google Chrome" --experimental
Here's an overview of the browser names you can use per platform (note that double quotes are required when the browser name contains space and the right capitalization is required too):
OS | Browser | Argument for --browser |
---|---|---|
Mac OS | Chrome | "Google Chrome" |
Firefox | "Firefox" |
|
Firefox (Developer) | "Firefox Developer Edition" |
|
Safari | "Safari" |
|
Windows | Chrome | "Google Chrome" |
Firefox | "Firefox" |
|
Firefox (Developer) | "Firefox Developer Edition" |
|
Brave | "Brave" |
|
Linux | Chrome | "google-chrome" |
Firefox | "firefox" |
|
Firefox (Developer) | "firefox-developer-edition" |
|
Brave | "brave" |
Fixes and improvements
prisma
- beta.3 (#1635) breaks custom binaries (on Alpine)
- Investigate GCR Panic
- RUST error, Did not find a relation for model UserDetail and field userid, Some details are omitted, run with
RUST_BACKTRACE=full
for a verbose backtrace. - Difficult to read error report
- Query by unique constraint missing included properties
- Update Prisma 1 docs to link to Prisma 2 docs
introspect
fails on SQLite
prisma-client-js
- Does not work with yarn workspace
- Type Generation : returned payload type on upsert not using include
- Providing
null
for a nullable relation results in error - Error when setting a relation field to
null
migrate
vscode
- Saving adds random fields to model
- Context-aware auto-completion
- Modelname being formatted as lowercase when auto-creating back relations
- Extension should report failure if formatting / binary execution fails
- Rename "Automatic Publish"
- Show error in VS Code extension when illegal model name is used
alpha
version of extension- Multiple versions (e.g. 0.0.21 and 0.0.22) are missing Git tags
- Clickable Schema (Relations)
- Automated testing
Credits
Huge thanks to @Sytten for helping!
Assets
2
timsuchanek released this
Today, we are issuing the third Beta release: 2.0.0-beta.3 (short: beta.3).
Major changes
- Enums are now disallowed for SQLite
- Required 1-1 self relations are forbidden now
- The
prisma2
command is now deprecated in favor ofprisma
Fixes and improvements
prisma
- Introspection Regression "Error validating: The argument
references
must refer to a unique criteria in the related modelpages_language
. But it is referencing the following fields that are not a unique criteria: page_id" - Engine freezes all requests/responses in 2.0.0-beta.2
- [Beta.2] Omission of relation field causes unclear rust error message at generate
- Custom type for id
- Document AWS lambda configuration to avoid timeouts
- raw: COALESCE/IFNULL returns
MA==
- Upserting Many-To-Many fails with unique index constraint
- Bad cli output
@relation
annotation'sfield
attribute should not be able to accept scalar lists- I am new to PRISMA /. i am not able to install via NPM .. can some body help ?
- Should we output introspection warnings to stderr when using
prisma introspect --print
? - Improve Introspection warnings output for invalid names
- Deprecation wrapper for
prisma2
executable generate
does not work in folders with spaces- Rename CLI folder
- Remove enum usage from docs where sqlite is used
- Required 1-1-self-relations should be forbidden?
prisma-client-js
- PrismaClientUnknownRequestError - InterpretationError on nested create
- Update Many in self-referencing relations
migrate
- Add ability to define schema path for prisma migrate cli to help output
--preview
is ignored when doingprisma migrate down --preview --experimental
- Migrate allows you to use enums in sqlite even though sqlite doesn't support them
vscode
Assets
2
nikolasburk released this
We are extremely excited to launch the first official Beta of Prisma 2.0 today!
Breaking changes
No more Preview releases
With this release the Preview period for Prisma 2.0 ends. This means that releases will not be tagged preview
any more, but with beta
. Today's release is called: 2.0.0-beta.1
.
Restructuring GitHub repositories
Since its initial release, the main repository for Prisma 2.0 has been called prisma2
.
Because Prisma 2.0 is now the default for developers getting started with Prisma, the Prisma repositories have been renamed as follows:
- The
prisma/prisma2
repository has been renamed toprisma/prisma
- The
prisma/prisma
repository has been renamed toprisma/prisma1
Renaming the prisma2
CLI
During the Preview period, the CLI for Prisma 2.0 was invoked using the prisma2
command. With Prisma 2.0 being the default for new developers getting started with Prisma, the command is changed to just prisma
. The exising prisma
command of Prisma 1 is renamed to prisma1
.
Also note that the installation of the npm packages changes:
Prisma version | Old CLI command | New CLI command | Old npm package name | New npm package name |
---|---|---|---|---|
2.0 | prisma2 |
prisma |
prisma2 |
@prisma/cli |
1.X | prisma |
prisma1 |
prisma |
prisma1 |
New syntax for defining relations
The Beta release introduces a new relation syntax which makes the @relation
attribute required in each relation in the Prisma schema. Note that it often is enough to only declare the attribute only on the side of the relation (the side that stores the foreign key in the underlying database).
Additionally, for one-to-one and one-to-many relations, you need add a relation scalar field to the model which is used in the @relation
attribute. This relation scalar field directly maps to the foreign key in the underlying database. Note that the foreign key is read-only in the Prisma Client API, to modify a relation you can keep using nested write queries as before.
Here's an overview for how relations need to be updated.
One-to-one
During the Preview period, a 1-1-relation could be defined as follows:
model User {
id Int @id @default(autoincrement())
profile Profile
}
model Profile {
id Int @id @default(autoincrement())
user User
}
With the new Beta, you now must determine which side should store the foreign key. You can do so by adding the @relation
attribute with its corresponding relation scalar field to the model:
model User {
id Int @id @default(autoincrement())
profile Profile
}
model Profile {
id Int @id @default(autoincrement())
+ user User @relation(fields: [userId], references: [id])
+ userId Int // relation scalar field (used in the `@relation` attribute above)
}
This Prisma schema is represented as follows in SQL (the foreign key is stored on Profile
):
CREATE TABLE "User" (
id SERIAL PRIMARY KEY
);
CREATE TABLE "Profile" (
id SERIAL PRIMARY KEY,
"userId" INTEGER NOT NULL UNIQUE,
FOREIGN KEY ("userId") REFERENCES "User"(id)
);
One-to-many
During the Preview period, a 1-n-relation could be defined as follows:
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
author User
}
With the new Beta, you now must add the @relation
attribute and its corresponding relation scalar field to the non-list field of the relation:
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
+ author User @relation(fields: [authorId], references: [id])
+ authorId Int
}
This Prisma schema is represented as follows in SQL:
CREATE TABLE "User" (
id SERIAL PRIMARY KEY
);
CREATE TABLE "Post" (
id SERIAL PRIMARY KEY,
"authorId" integer NOT NULL,
FOREIGN KEY ("authorId") REFERENCES "User"(id)
);
Many-to-many (implicit)
During the Preview period, a m-n-relation could be defined as follows:
model Post {
id Int @id @default(autoincrement())
categories Category[]
}
model Category {
id Int @id @default(autoincrement())
posts Post[]
}
With the new Beta, you now must add the @relation
attribute to both sides of the relation:
model Post {
id Int @id @default(autoincrement())
+ categories Category[] @relation(references: [id])
}
model Category {
id Int @id @default(autoincrement())
+ posts Post[] @relation(references: [id])
}
Prisma will maintain the relation with the following relation table:
CREATE TABLE "Category" (
id SERIAL PRIMARY KEY
);
CREATE TABLE "Post" (
id SERIAL PRIMARY KEY
);
-- Relation table + indexes -------------------------------------------------------
CREATE TABLE "_CategoryToPost" (
"A" integer NOT NULL REFERENCES "Category"(id),
"B" integer NOT NULL REFERENCES "Post"(id)
);
CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON "_CategoryToPost"("A" int4_ops,"B" int4_ops);
CREATE INDEX "_CategoryToPost_B_index" ON "_CategoryToPost"("B" int4_ops);
Why this change was introduced
The changes in the relation syntax were needed to enable more complex relation configurations, e.g. when using multi-field IDs.
Note that we aim to simplify the current syntax in the future again ("take one step backward, to be able to move two steps forward").
The prisma2
npm package is deprecated
The prisma2
npm package is now deprecated, the Prisma 2.0 CLI can now be installed via the @prisma/cli
npm package, e.g.:
npm @prisma/cli --save-dev
npx prisma
To prevent confusions during installation, it now outputs the following when you try to install it:
┌─────────────────────────────────────────────────────────────┐
│ │
│ The package prisma2 has been renamed to @prisma/cli. │
│ │
│ Please uninstall prisma2 from your project or globally. │
│ Then install @prisma/cli to continue using Prisma 2.0: │
│ │
│ # Uninstall old CLI │
│ npm uninstall prisma2 │
│ │
│ # Install new CLI │
│ npm install @prisma/cli --save-dev │
│ │
│ # Invoke via npx │
│ npx prisma --help │
│ │
│ Learn more here: https://pris.ly/preview025 │
│ │
└─────────────────────────────────────────────────────────────┘
Assets
2
Watchers:108 |
Star:8444 |
Fork:369 |
创建时间: 2019-06-20 21:33:47 |
最后Commits: 3天前 |
分类:其它杂项 / JavaScript开发 |
收录时间:2020-04-01 20:47:49 |
fdd8213
Compare
Verified
Today, we are excited to share the
🎉
2.17.0
stable releaseOverview
prisma db push
prisma db seed
now supports custom schema locationsNote 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 in2.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 AvailabilityNote 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 types
Each Prisma type can now map to one of multiple native database types. Native database type attributes are:
@db.Boolean
forBoolean
whereas MySQL uses@db.TinyInt
VarChar
orText
)@db
, wheredb
is the name of thedatasource
block in your Prisma schemaType attributes give you:
String
can be@db.VarChar(200)
or@db.Char(50)
String
isvarchar(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:dbgenerated()
in the@default
directive can now take a String argument that enables developers to reflect database-levelDEFAULT
constraints not yet supported by Prisma Migrate. These default values will be surfaced when introspecting withprisma 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 ashadowDatabaseUrl
variable: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
andCREATE 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
migrate dev
- if a non-interactive environment is detected, you'll be suggested to useprisma migrate deploy
instead.prisma/migrations/20210119114009_init
(missingmigration.sql
file).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.—-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.—-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 locationsYou can now point the
prisma db seed
command to a custom schema location using either of two approaches:--schema
option when running the commandpackage.json
which will be picked up every time you run the command.Improvements and bug fixes in Prisma Client
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 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).NVarChar
/NChar
length and a maximum of 4000 forVarChar
/Char
/VarBinary
/Binary
length. The actual maximums are4000
for first and8000
for the latter types.executeRaw
to insert number values to anumeric
type in PostgreSQL, sometimes the stored value would be zero instead of the user input. An example value of12345.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 tonumeric
without any trouble.Bug fixes in Prisma Studio
Byte
andBigInt
.createMany
preview feature doesn't crash Studio any moreBreaking changes
Type mapping from Prisma schema to the database for
Float
has changed fromDecimal
toDouble
in MySQL and PostgreSQLOverview
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 typeDECIMAL(65,30)
.For example, given the following Prisma schema:
Previous version of Prisma Migrate would generate the following migration:
As of
2.17.0
, the remapping of theFloat
type fromDecimal(65,30)
toDouble
will cause Migrate to attempt to alter the database type of thereward
column toDouble
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:Decimal(65,30)
, you need to change the type in the Prisma schema fromFloat
toDecimal
. Alternatively, you can also runprisma introspect
which will automatically remap the previousFloat
fields toDecimal
. Note that this will also change the type that Prisma Client returns fromNumber
toDecimal.js
.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 aTEXT
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 useVARCHAR(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., theString
Prisma scalar will map toTEXT
on PostgreSQL.Before
Given the following table in PostgreSQL:
Prisma would introspect the table as follows:
After
Because
VARCHAR(50)
can be expressed in native type notation. The matching Prisma schema for theUser
database table above on PostgreSQL is the following: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:
and this initial database schema:
On PostgreSQL, from this release on, Prisma will the columns for the fields
nickName
and name to be of typeTEXT
and will generate a migration to alter the type of thenickName
column: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
This would be the resulting Prisma schema after running prisma introspect
Fixes and improvements
Prisma Client
undefined
value shouldn't return datamakeEnum
nativeTypes
localhost
for MySQL, MariaDB and SQL Server (mostly when running those via Docker)PRISMA_DISABLE_WARNINGS
Prisma Migrate
Option::unwrap()
on aNone
valueALTER TYPE
enum migrations fail in PostgreSQL@@ignore
and@ignore
on re-introspectionundefined
db seed
not documented in help output forprisma db --help
prisma migrate deploy
inmigrate dev
non 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)notLanguage tools
@ignore
code completion is supported in VS code extensionPrisma Studio
Prisma Engines
clippy
tomigration-engine
clippy
tointrospection-engine
clippy
tolibs/datamodel
clippy
to alllibs/*
(except datamodel)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!