Releases: prisma/prisma
2.0.0-beta.9
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!
2.0.0-beta.8
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!
2.0.0-beta.7
Today, we are issuing the seventh Beta release: 2.0.0-beta.7
(short: beta.7
).
New Pagination
Prisma Client's pagination has been simplified a lot!
- Removed
first
,last
,before
,after
arguments. - Added
cursor
andtake
arguments. skip
argument unchanged.
The take
argument replaces first
and last
.
Examples
first
prisma.user.findMany({
first: 10
})
// becomes
prisma.user.findMany({
take: 10
})
last
prisma.user.findMany({
last: 10
})
// becomes
prisma.user.findMany({
take: -10
})
before
prisma.user.findMany({
before: "someid"
first: 10
})
// becomes
prisma.user.findMany({
cursor: "someid"
take: -10
skip: 1
})
after
prisma.user.findMany({
after: "someid"
first: 10
})
// becomes
prisma.user.findMany({
cursor: "someid"
take: 10
skip: 1
})
The record specified with cursor
is now included in the results, making skip: 1
necessary if you want to preserve the previous before
/ after
semantics.
This diagram illustrates how the pagination works:
cursor: 5
skip: 0 or undefined
│
│
│
▼
┌───┐┌───┐┌───┐┏━━━┓┏━━━┓┌───┐┌───┐┌───┐┌───┐┌───┐
│ 1 ││ 2 ││ 3 │┃ 4 ┃┃ 5 ┃│ 6 ││ 7 ││ 8 ││ 9 ││10 │
└───┘└───┘└───┘┗━━━┛┗━━━┛└───┘└───┘└───┘└───┘└───┘
◀────────
take: -2
cursor: 5
skip: 1
│
│
│
▼
┌───┐┌───┐┏━━━┓┏━━━┓┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐
│ 1 ││ 2 │┃ 3 ┃┃ 4 ┃│ 5 ││ 6 ││ 7 ││ 8 ││ 9 ││10 │
└───┘└───┘┗━━━┛┗━━━┛└───┘└───┘└───┘└───┘└───┘└───┘
◀────────
take: -2
cursor: 5
skip: 2
│
│
│
▼
┌───┐┏━━━┓┏━━━┓┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐
│ 1 │┃ 2 ┃┃ 3 ┃│ 4 ││ 5 ││ 6 ││ 7 ││ 8 ││ 9 ││10 │
└───┘┗━━━┛┗━━━┛└───┘└───┘└───┘└───┘└───┘└───┘└───┘
◀────────
take: -2
cursor: 5
skip: 0 or undefined
│
│
│
▼
┌───┐┌───┐┌───┐┌───┐┏━━━┓┏━━━┓┏━━━┓┌───┐┌───┐┌───┐
│ 1 ││ 2 ││ 3 ││ 4 │┃ 5 ┃┃ 6 ┃┃ 7 ┃│ 8 ││ 9 ││10 │
└───┘└───┘└───┘└───┘┗━━━┛┗━━━┛┗━━━┛└───┘└───┘└───┘
──────────▶
take: 3
cursor: 5
skip: 1
│
│
│
▼
┌───┐┌───┐┌───┐┌───┐┌───┐┏━━━┓┏━━━┓┏━━━┓┌───┐┌───┐
│ 1 ││ 2 ││ 3 ││ 4 ││ 5 │┃ 6 ┃┃ 7 ┃┃ 8 ┃│ 9 ││10 │
└───┘└───┘└───┘└───┘└───┘┗━━━┛┗━━━┛┗━━━┛└───┘└───┘
──────────▶
take: 3
cursor: 5
skip: 2
│
│
│
▼
┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┏━━━┓┏━━━┓┏━━━┓┌───┐
│ 1 ││ 2 ││ 3 ││ 4 ││ 5 ││ 6 │┃ 7 ┃┃ 8 ┃┃ 9 ┃│10 │
└───┘└───┘└───┘└───┘└───┘└───┘┗━━━┛┗━━━┛┗━━━┛└───┘
──────────▶
take: 3
Auto restart on panic
The Query Engine now automatically restarts with an exponential backoff with jitter, if it exits for some reason, for example in the case of a panic. That helps a lot to make Prisma Client more resilient in production!
#2100
Introspection now recognizes @default(cuid / uuid)
If you introspect a Prisma 1 schema, the introspection now correctly recognizes cuid
or uuid
usage
#2499
Fixes and improvements
prisma
- Prisma should check for generator binaries in $PATH
- A generator provider should accept arbitrary commands
generate
does not work in folders with spaces- Restart engine on panic
- Unable to save arrays in a Json type field
findMany
with aselect
argument errors out with models with self-relations (sometimes)- [Introspection] Identify Prisma 1 Id defaults
- Prisma Client mixes up DateTimes and IDs when they are
select
ed in queries findMany
fails toselect
an enum list & a relation scalar at the same time- [Prisma Client] Duplicate identifier with models "X" and "XClient"
- Output notice about Prisma1->Prisma2 upgrade documentation and tool
- New raw functions not exported from @prisma/client
- Generated GitHub link too long
prisma-client-js
vscode
- Message: Request textDocument/definition failed with message: Schema parsing
- Show linter snippet in formatting error
- Using svg breaks markeplace publish
- Not possible to use backslash in string field
- Run CI tests every time a release gets published
- Include CLI version in startup output
- Startup output does not include binary hash any more
- Using autocompletion for
@default()
puts curcor after)
instead of inside()
- Ctrl+Space does not suggest current model for self relation
@unique @unique
- Formatter adds new lines on every format call
- Move out anything unimportant to users from README to CONTRUBUTING.md
- Update README preview image
- Improving README
- vscode plugin formatting bug
- Auto-completion for relation directive shows wrong suggestions
- Format incorrectly deletes invalid lines
- Format deletes new lines in invalid block and removes any whitespaces in the beginning
- Format moves lines on every format call in an invalid schema
prisma-engines
Credits
2.0.0-beta.6
Today, we are issuing the sixth Beta release: 2.0.0-beta.6
(short: beta.6
).
More powerful raw
queries with Prisma Client
Thanks to @zachasme and @Sytten, the prisma.raw
command became more powerful in #2311. There are two changes we introduce for raw
:
Expose sql-template-tag
helpers
Prisma Client's raw
mode utilizes the sql-template-tag
library. In order to construct raw SQL queries programmatically, Prisma Client now exposes a few helper functions:
import { sql, empty, join, raw, PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const rawQueryTemplateFromSqlTemplate = await prisma.raw(
sql`
SELECT ${join([raw('email'), raw('id'), raw('name')])}
FROM ${raw('User')}
${sql`WHERE name = ${'Alice'}`}
${empty}
`
)
Allowing programmatic positional parameters
Sometimes, a static template string is not enough. Then constructing a string dynamically is the right choice. For this situation, we added support for arbitrary positional parameters:
const result = await prisma.raw(
'SELECT * FROM User WHERE id = $1 OR email = $2;',
1,
'e@ma.il'
)
Other improvements
- You can now enable pgBouncer in your connection URL by adding the
?pgbouncer=true
parameter (forceTransactions
from thePrismaClient
is now deprecated and will be removed in an upcoming release) - Improved handling of comments in
prisma format
- Various improvements to Prisma's VS Code extension (e.g. better error messages and debug information)
Fixes and improvements
prisma
- [Introspection] Better
introspect
success message - DigitalOcean Postgres + PGBouncer Issues
&sslcert=server-ca.pem
in PostgreSQL connection url throwError opening a TLS connection: One or more parameters passed to a function were not valid.
- Prisma generate --watch errors
- Introspect default value with backslashes causes problem when generating client
- Prisma DMMF parses comments as fields docs
- Cascade delete does not work unless relation is optional
- Special-case syntax error for multiple unnamed arguments in directive in the schema parser
- Error on table update using a mapped field in where clause
- Add renovate bot for dependencies
- Prisma Schema: Add .prisma syntax highlighting for Sublime Text
- Simple filtering for JSON
- Panic calling findOne with mapped unique key fields
- Validation issue for schemas with compound foreign keys
- [introspect] Expose database classification feature
- If a comment is the last line in a model,
prisma format
will move it out of the model - Investigate alternatives to required PgBouncer configuration
- Overwriting database connection string in
Prisma Client
does not work - PgBouncer mode
- Documentation parsed from doc comment is missing for enums
prisma-client-js
- Document
forceTransactions
/ pgBouncer - Better instructions on Query Engine panic
- Ability to use Heroku's pgbouncer
- Prisma Client failing with PgBouncer Transaction Mode
- Basic reporting capability for runtime errors in Client
- Prisma Client Beta 4 broken with Netlify
- PANIC error on upsert query
- Cannot use prisma.create() with nullable field set to null
vscode
- Trailing comments are broken to the next line when formatting
- Recognize Prisma1 schemas and tell user to install the other extension and rename file
- Allow inline comment
- Formatting moves comment from inside model to above model
- Preserve newlines / whitespaces inside models
- Extension deletes unused commented out models
- Use same versioning scheme & release cadence as Prisma itself
- prisma-fmt: add newline in the end of the file
- Triple slash comments in prisma schema file not working
- Versioning scheme
- Add badges and repo explanation to README
- VSCode extension errors when linting .prisma file
- Also output extension name / package and version on startup
- Configuring Git to handle line endings
- Remove Prisma as Icon Theme
prisma-engines
Credits
2.0.0-beta.5
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!
2.0.0-beta.4
Today, we are issuing the fourth Beta release: 2.0.0-beta.4
(short: beta.4
).
Major improvements
Support for JSON types in PostgreSQL and MySQL
Prisma now supports working with JSON data with the new Json
type in the Prisma data model.
Here's an overview of how it works with different Prisma tools/workflows:
Introspection
The prisma introspect
command maps the following column types to Json
:
- Postgres:
JSON
andJSONB
- MySQL:
JSON
Prisma Migrate
prisma migrate
uses the following data type when creating a column for a field of type Json
:
- Postgres:
JSONB
- MySQL:
JSON
Prisma Client
Fields of type Json
will be exposed as plain JavaScript objects in the Prisma Client API.
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
- Data type JSON
- 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!
2.0.0-beta.3
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
2.0.0-beta.2
Today, we are issuing the second Beta release: 2.0.0-beta.2
(short: beta.2
).
We want to give a huge shoutout to @Sytten who helped us fix some issues in the Rust codebase 🎊
Major improvements
Parametrized count
queries in Prisma Client
In previous versions of Prisma Client, it was not possible to provide any filter arguments when using .count
. With this release, you can provide the same filter arguments from findMany
:
const numberOfUsersCalledBob = await prisma.user.count({ where: { name: 'Bob' }})
Lots of bug fixes and improvements
With this release, we were able to fix a lot of nasty bugs like some schema validation issues in VS Code (#1989 and #1970) as well as a Prisma Migrate bug with 1-n self-relations.
Fixes and improvements per Prisma 2.0 repository
prisma
- Provide log output when
.env
file is used - Closes #1155 - Add MariaDB integration tests closes #1791
- Fix "because" typo in README
- Add a --json flag to
version
command - Running prisma version fails
- Schemas with incomplete @relation annotations should be rejected during Client generation
- Fix
prisma2 generate --watch
exits when no models are defined in schema.prisma - Fix link to Prisma documentation
- fix typo in README
- Fix "Getting started" links
- Prisma generate script throws error
- Running a built binary fails with weird error
- Validation error message for schema with missing relation scalar field (old syntax)
- Validation Error: error: Error validating: The relation field
Teams
uses the scalar fields tmID. The arity of those fields must be the same. The relation field is required but the scalar fields are optional. - Add integration test for introspection warnings
- Error format for enum field declaration broken
- Error format for missing type on field is broken
- Error when disconnecting m:n relation with string-id-model
- Getting error on deeper includes
- ENV-based binary variables broken on preview022
- Proposal: Rename prisma binary to query-engine
prisma2 generate --watch
exits when no models are defined in schema.prisma- Provide log output when
.env
file is used
prisma-client-js
- adjust README
- Fix a typo in the generated docs
- Error message "Error: Query engine binary for current platform "..." could not be found" could list other file from that directory to help debugging
- Fix batching. Closes #562
- Invalid include query results in unexpected output
- Query batching sends queries with different selection set
- Super long output on error in
create
prisma-engines
- Adapt test-cli to new query engine binary name
- Unify duplicated test assertion code paths
- Remove Unused Dependencies
- Upgrade quaint and adjust tests after mysql floats fix
- Fix Self Relation Rendering
- Minor opportunistic simplifications in sql schema calculator
- Fix detection of 1:1 relations for self-relations
- Datamodel parser/relation arguments validation
- Downgrade tokio to 0.2.13
- Fix for unexpected additional records during deeply nested reads.
- Bug: subquery has too many columns
- Update crates (incl. faster tokio)
- cargo fmt
- adapt arity validation for relation fields to match introspection logic
- Datamodel Parser: allow dbgenerated function for enum fields
- add readonly flag to dmmf field
- Drop relations that are referring to unsupported types
- Add dmmf subcommand to test-cli
- Ignore env errors when reformatting
- Test column types with dubious nullability properties (pg/mysql)
- improve relation validations
- prisma-fmt formatting regression
- Add support for newline in the source and generator blocks
- Investigate weirdness around nullability of timestamp fields
- Proposal: Tighten datamodel parser rules for @relation
- Reenable error code and message assertions in scala tests
migrate
2.0.0-beta.1
We are extremely excited to launch the first official Beta of Prisma 2.0 today! 🎉 Along with this release, we have also published a new website and an updated Prisma 2.0 documentation. This makes Prisma 2.0 the default for developers who are getting started with Prisma.
Upgrading to the new relation syntax
If you have been using Prisma Migrate before to create your models and their relations, the new relation syntax can seem a bit counterintuitive at first. Here's a quick overview of the most important things to consider when upgrading.
Note that this only covers one-to-one and one-to-many relations. Prisma's implicit many-to-many relations are adjusted by manually adding the @relation
attribute with a single field reference to both sides of the relation (most often this looks as follows: @relation(references: [id])
).
Consider this sample schema from preview025
:
model User {
id Int @id @default(autoincrement())
profile Profile?
posts Post[]
}
model Profile {
id Int @id @default(autoincrement())
user User // backed up by a foreign key called `user` in the DB
}
model Post {
id Int @id @default(autoincrement())
author User // backed up by a foreign key called `author` in the DB
}
Expand for the corresponding SQL
CREATE TABLE "User" (
id integer PRIMARY KEY,
name text NOT NULL DEFAULT ''::text
);
CREATE TABLE "Profile" (
bio text NOT NULL DEFAULT ''::text,
id integer PRIMARY KEY,
user integer NOT NULL,
FOREIGN KEY ("user") REFERENCES "User"(id)
);
CREATE TABLE "Post" (
id integer PRIMARY KEY,
title text NOT NULL
author integer NOT NULL,
FOREIGN KEY ("author") REFERENCES "User"(id)
);
Note that in this case, the foreign keys in the underlying database are located on the Profile
and Post
tables. The User
table does not have any foreign keys (which means the profile
and posts
relation fields on the User
model are virtually maintained by Prisma).
The new syntax requires you to make the foreign key explicit in the Prisma schema (so you need to add another field in addition to the already existing relation field). This new field is your relation scalar field and directly represents the foreign key in the underlying database.
Assume you're now upgrading to 2.0.0-beta.1
:
npm install @prisma/client@2.0.0-beta.1
npm install @prisma/cli@2.0.0-beta.1 --save-dev
Without touching the database, one way to adjust your Prisma schema to adhere to the new syntax would be as follows:
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 @map("user") // relation scalar field (used in the `@relation` attribute above)
}
model Post {
id Int @id @default(autoincrement())
author User @relation(fields: [authorId], references: [id])
+ authorId Int @map("author") // relation scalar field (used in the `@relation` attribute above)
}
In this code, you introduced the userId
and authorId
fields on Profile
and Post
. These fields are your relation scalar fields and represent the foreign key in your database. But because the current foreign keys in the database are called user
and author
and therefore don't map directly to the model fields, you need to annotate the fields with @map
to "map" them to a differently named database column.
You can then re-generate Prisma Client. Note that the prisma2
command has been renamed to prisma
in 2.0.0-beta.1
, so you need to invoke the generate
command as follows:
npx prisma generate
Note that the new relation scalar field is currently read-only in the generated Prisma Client API. To modify the connections in youe database, you can keep using Prisma Client's nested write queries.
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:
2.0.0-preview025
Today, we are issuing the twenty-fifth Preview release: 2.0.0-preview025
(short: preview025
).
Breaking changes
Renaming the prisma2
npm package
With this release, we're renaming the Prisma 2 CLI npm package from prisma2
to @prisma/cli
. Note that you can still invoke the CLI using the prisma2
command!
To upgrade, you first should uninstall the current prisma2
version and then install the @prisma/cli
package.
Local installation (recommended)
The local installation is generally preferred since it prevents conflicting versions of the same package.
# Uninstall current `prisma2` CLI (`preview024` or earlier)
npm uninstall prisma2
# Install new `prisma2` CLI via `@prisma/cli` npm package
npm install @prisma/cli --save-dev
# Invoke the CLI via `npx`
npx prisma2
Global installation
# Uninstall current `prisma2` CLI (`preview024` or earlier)
npm uninstall -g prisma2
# Install new `prisma2` CLI via `@prisma/cli` npm package
npm install -g @prisma/cli
# Invoke the CLI via `npx`
npx prisma2
Other
- The
prisma2 --version
output changed - Virtual relation fields (aka “back-relation fields”) follow the same name as the model they relate to during introspection
- The default for
errorFormat
in thePrismaClient
constructor now iscolorless
Fixes and improvements per Prisma 2 repository
prisma2
- feat(prisma2/cli): allow arbitrary generator commands with flags
- Update docs to reflect existing examples
- Comments in schema's
datasource
block fail withError: Schema parsing error: Unexpected token. Expected one of: End of block ("}"), alphanumeric identifier
- get-config gets the datamodel from the env vars
- Relation table for implicit m:n-relation not recognized by introspection
- update postgres integration tests
- [Introspection]
error: Argument 'value' is missing in attribute '@default'.
- add instructions for adding bug reports
- Investigate if we can hide GraphQL Playground on CSB
- Remove AUMFIDARR guardrails
- Failed to validate the query
Error occurred during query validation & transformation
: - PostgreSQL: "incorrect binary data format in bind parameter x"
- [Introspection] Comment out all unsupported column types
- MySQL: "DateTime value not stored as DateTime, Int or string"
- sqlite/chinook returns
PANIC: Could not parse stored DateTime string: 2009-01-01 00:00:00: ParseError(Invalid)
on findMany() - AWS Lambda timed out
- Don't expose GraphQL Playground
- [Introspection] Guardrail: Remove default values we do not support
- [Introspection] Relation guardrail creates duplicate fields
- [Introspection] Decide on a way forward for introspection of types our internal type system currently cannot represent
- Schema Validation fails with panic
thread 'main' panicked at 'Expected ID field ... to be present on the model'
- Remove opinionated casing for back relation field names
- Unclear rust error PANIC
- "Oops. We could not send the error report."
- [Introspection] "The model 'x' cannot be defined because a model with that name already exists."
- [Introspection] Crashes when default value contains line breaks
- Expand --version command
- [Introspection] "created_at timestamp with time zone not null default now()" doesn't work
- [Introspection] ID = (Scalar, RelationField)
- Explicit many to many relationships with/without extra columns
@default
doesnt work for enum
prisma-client-js
- Fix .raw with parameters for PostgreSQL
- Using raw queries with tagged template literals doesn't include parameters
- Fix downloading HTTPS file with HTTP proxy
- Change default error formatting from
pretty
tocolorless
- Some models return
Error parsing GraphQL query: query parse error: Parse error at 4:3 Unexpected
}[Punctuator]Expected
Name fromfindMany({})
after introspection - Can't query models without scalar fields
- prisma2 generate always uses yarn even if you're using NPM in your project
- Cannot find module '@prisma/client' after installing a new package via NPM
- Mutating a
Float
sometimes results on sightly different value written to Postgres - Export the current Prisma version
- Using a relation as @id or in @@unique doesn't work
- Some models return
undefined
fromfindMany({})
after introspection - 3 way join with @@id failing when querying
- find by composite primary keys API is super weird
- Can't findOne, update, delete on composite primary keys
- Find by a null time doesn't work
- Find with exact DateTime input doesn't work with findMany or findOne
- Gracefully handle incorrect id column type
- Nested writes don't work on 3rd level with required relation
prisma-engines
- [WIP] new @relation validations
- Fix unused value warning in test
- Set the pool constraints in QE
- Health check fixes
- Test unique fields as ID on postgres
- New relations in the migration engine
- [WIP] IE Changes
- Unify dml error handling
- Test postgres array defaults
- Make dmmf dm errors more beautiful
- Schema validation errors broken since alpha 940
- Citext
- The dmmf cli cmd should not crash for env vars
- Test and fix postgres default handling
- Remove the camelcasing for backrelation fields
- Set all datamodel-related flags in structopt
- Add an introspect subcommand to test-cli
- Test mysql defaults
- Adjust legacy M:N Relation Inference
- Test all identifier types on mysql
- Disable playground by default, flag for enabling
- Test postgres exotic filters
- Discriminate between unsupported types and those that cast to string
- Comment out Unsupported Datatypes
- Avoid unecessary allocation in quaint query building
- Recognize all Prisma 1.0 relations as Implicit Many2Many relations
- [Postgres exotic filters](https://github.com/prisma/pri...