apps/blog/content/blog/whats-new-in-prisma-q1-2021-spjyqp0e2rk1/index.mdx
Learn about everything that has happened in the Prisma ecosystem and community from January to March 2021.
Our engineers have been hard at work issuing new releases with many improvements and new features every two weeks. Here is an overview of the most exciting features that we have launched in the last three months.
You can stay up-to-date about all upcoming features on our roadmap.
The biggest news in this quarter certainly was the launch of Prisma Migrate for General Availability. This means, you can now use Prisma Migrate without the --preview-feature option:
Before v2.19.0
npx prisma migrate <COMMAND> --preview-feature
# for example:
npx prisma migrate dev --preview-feature
Now
npx prisma migrate <COMMAND>
# for example:
npx prisma migrate dev
You can learn more about this in the release notes, the announcement article and the video demo by Daniel and Tom.
In this quarter, we made it possible to use a much broader range of native database types in the Prisma schema.
For example, you can now define VARCHAR types of a specific length or use other database-specific types like (in this case for PostgreSQL) MONEY, variations of date/time types like TIME, TIMETZ or TIMESTAMPTZ and a lot more.
Here's an example:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement()) @db.Integer
email String @unique @db.VarChar(191)
birthday DateTime? @db.Timestamptz
wealth Decimal @db.Money
}
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
"email" VARCHAR(191) NOT NULL,
"birthday" TIMESTAMPTZ,
"wealth" MONEY NOT NULL,
PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "User.email_unique" ON "User"("email");
For a full overview of available types, check out the type mapping sections in the docs:
The new prisma db seed command enables you to automatically invoke a seed script to feed your database with some initial data.
The command expects a file called seed with the respective file extension inside your main prisma directory:
prisma/seed.jsprisma/seed.tsprisma/seed.shAlternatively you can pass the --schema option to the CLI command in order to point to the location of the seed script or define a default schema location in your package.json which will be picked up every time you run the command.
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// A main function so that we can use async/await
async function main() {
const newUser = await prisma.user.create({
data: {
email: '[email protected]',
},
})
console.log(New user created, newUser.id)
}
main() .catch(e => { console.error(e) process.exit(1) }) .finally(async () => { await prisma.$disconnect() })
</Accordion>
</Accordions>
### New features for the Prisma Client API
We regularly add new features to the Prisma Client API to enable more powerful database queries that were previously only possible via plain SQL and the [`$queryRaw`](https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access#queryraw) escape hatch .
#### Order by relations (Preview)
Since [2.16.0](https://github.com/prisma/prisma/releases/tag/2.16.0), you can order the results of `findMany` queries by properties of [related](https://www.prisma.io/docs/concepts/components/prisma-schema/relations) models. For example, you can order a list of posts alphabetically by the names of their authors:
```ts
cons posts = await prisma.post.findMany({
orderBy: [
{
author: {
name: 'asc',
},
},
],
})
model Post {
id Int @id @default(autoincrement())
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
model User {
id Int @id @default(autoincrement())
nam String
posts Post[]
}
Additionaly, the 2.19.0 release makes it possible to order by the aggregates (e.g. count) of relations as well. Here's is an example that orders a list of users by the number of the posts they created:
const users = await prisma.user.findMany({
orderBy: {
posts: {
count: 'asc',
},
},
})
model Post {
id Int @id @default(autoincrement())
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
model User {
id Int @id @default(autoincrement())
nam String
posts Post[]
}
This highly requested feature is now Preview since 2.20.0. You can now count the number of related records by passing _count to the select or include options and then specifying which relation counts should be included in the resulting objects via another select.
For example, counting the number of posts that an user has written:
const users = await prisma.user.findMany({
include: {
_count: {
select: { posts: true },
},
},
})
{
id: 1,
email: '[email protected]',
name: 'Alice',
_count: { posts: 2 }
}
createManyThe new createMany operation (introduced in 2.16.0) enables you to insert data a whole lot faster:
const result = await prisma.user.createMany({
data: [
{ email: '[email protected]' },
{ email: '[email protected]' },
{ email: '[email protected]' },
{ email: '[email protected]' },
],
})
console.log(`Created ${result.count} users!`)
Since 2.15.0, it is possible to dirctly set foreign keys instead of wiring up relations via the connect API:
// 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
},
},
})
Since 2.14.0, Prisma Client supports group by queries:
const locations = await client.agent.groupBy({
by: ['location'],
min: {
rate: true,
},
})
[
{ location: "Los Angeles", min: { rate: 10.00 } },
{ location: "London", min: { rate: 20.00 } },
{ location: "Tokyo", min: { rate: 30.00 } }
]
model Agent {
id String @id
name String
location String
rate Float
}
Additionally, you can further filter the result by using the having option:
const locations = await client.agent.groupBy({
by: ['location', 'rate'],
min: {
rate: true,
},
having: {
rate: {
gte: 20,
},
},
})
[
{ location: "London", rate: 20.00, min: { rate: 20.00 } },
{ location: "Tokyo", rate: 30.00, min: { rate: 30.00 } }
]
model Agent {
id String @id
name String
location String
rate Float
}
You can learn more about these queries in the docs.
N-API is a new technique for binding Prisma's Rust-based query engine directly to Prisma Client that was introduced in 2.20.0. This reduces the communication overhead between the Node.js and Rust layers when resolving Prisma Client's database queries.
Enabling the N-API will not affect your workflows in any way, the experience of using Prisma will remain exactly the same.
The N-API has different runtime characteristics than the current communication layer between Node.js and Rust. There may be some rough edges during the Preview period.
In case you're not aware, Prisma Client also is available for Golang in an Early Access version.
You can learn more about Prisma Client Go in the documentation. Also note that we are actively looking for feedback for Prisma Client Go!
You can help us accelerate the release process by creating issues and sharing your feedback in the #prisma-client-go channel on the Prisma Slack.
Upserts
post, _ := client.Post.UpsertOne(
// query
Post.ID.Equals("upsert"),
).Create(
// set these fields if document doesn't exist already
Post.Title.Set("title"),
Post.Views.Set(0),
Post.ID.Set("upsert"),
).Update(
// update these fields if document already exists
Post.Title.Set("new-title"),
Post.Views.Increment(1),
).Exec(ctx)
Dynamic filters
func CreateUser(w http.ResponseWriter, r *http.Request) {
var params []db.UserSetParam
email := r.PostFormValue("email")
kind := r.PostFormValue("kind")
if kind == "customer" {
// Set the referrer for users of type customer only
params = append(params, db.User.Referer.Set(r.Header.Get("Referer"))
}
user, err := client.User.CreateOne(
db.User.Kind.Set(kind),
db.User.Email.Set(email),
params...,
).Exec(r.Context())
// ... Handle the response
}
Transactions
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
}
New types: BigInt, Decimal and Bytes
var views db.BigInt = 1
bytes := []byte("abc")
dec := decimal.NewFromFloat(1.23456789)
created, err := client.User.CreateOne(
db.User.Picture.Set(bytes),
db.User.Balance.Set(dec),
db.User.Views.Set(views),
).Exec(ctx)
We are excited for the Blitz community to see them launch an official beta version of their framework, including a new website and documentation:
<TweetEmbedComp tweets={["1362048912476016642"]} />
Blitz is a batteries-included framework that's inspired by Ruby on Rails, is built on Next.js, and features a "Zero-API" data layer abstraction that eliminates the need for REST/GraphQL. It uses Prisma as its default ORM layer.
While it's already possible to use KeystoneJS with Prisma as the ORM, the upcoming version of KeystoneJS will use Prisma as its default database adapter.
KeystoneJS founder Jed Watson recently was a guest on the What's new in Prisma livestream where he gave a demo of KeystoneJS with Prisma.
<TweetEmbedComp tweets={["1362717932078383109"]} />
Backed by YCombinator, the twin brothers Martin and Matija Šošić are building Wasp, a DSL for building fullstack web applications. They recently launched Wasp on Hacker News.
To learn more about Wasp, be sure to check out Matija's talk at our recent Prisma Meetup:
<Youtube videoId="p3PNKJKsSuU" />Amplication is another exciting tool that promises to make web developers more productive, is built on Prisma and recently launched on Hacker News.
It allows to instantly generate fully-fledged REST and GraphQL APIs. The projects are configured via a web UI but can be fully customized as the underlying NestJS app can be downloaded and edited by the developer.
prisma-appsync generatorSylvain Simao recentely released a first version of prisma-appsync, a custom generator for the Prisma schema that enables developer to generate a full-blown GraphQL CRUD API via AWS AppSync and deployable with single command of the AWS CDK.
To learn more, check out the documentation and watch our recent What's new in Prisma episode.
<Accordions type="single"> <Accordion title="Expand to learn about other community generators"> Our community has built custom generators for the following use cases:prisma-docs-generator: Individual Prisma Client API referenceprisma-dbml-generator: DBML diagrams to visualize the Prisma schematypegraphql-prisma: CRUD resolvers for TypeGraphQLprisma-json-schema-generator: Prisma schema into JSON schema
</Accordion>
Max Stoiber is well-known in the JavaScript community for his popular open source work, like styled-components and react-boilerplate.
He recently announced Bedrock, a modern full-stack boilerplate with user authentication, subscription payments, teams, invitations, emails and everything else you need to build a SaaS product. We are excited that Max chooses Prisma as his ORM for this project!
<TweetEmbedComp tweets={["1372483017722187776"]} />
We wouldn't be where we are today without our amazing community of developers. Our Slack has more than 40k members and is a great place to ask questions, share feedback and initiate discussions all around Prisma.
The Prisma Enterprise Event 2021 has been a huge success and we want to thank everyone who attended and helped making it a great experience!
We've been excited to see fantastic speakers like Pete Hunt (Twitter), Natalie Vais (Amplify Partners), James Governor (Redmonk) and DeVaris Brown (Meroxa).
The event covered a broad range of topics about the challenges large companies and enterprises face with the management of application data, such as:
You can get access to all the talk recordings here.
<MeetupList><Meetup title="Prisma Enterprise Event 2021" meetupLink="https://www.prisma.io/enterprise-event-2021" talks={[ { title: 'Opening Keynote', author: 'Søren Bramer Schmidt', }, { title: 'Cloud Native Data: The Emergence of Enterprise Data Fabrics', author: 'James Governor', }, { title: 'Prisma at Rapha', author: 'Tom Hutchinson', }, { title: 'Prisma Enterprise Demo', author: 'Chris Matteson', }, { title: 'Prisma Fireside Chat', author: 'Hervé Labas, Chris Mateson, Søren Bramer Schmidt', }, { title: 'Building Products That Scale', author: 'Natalie Vais', }, { title: 'Developer Experience Matters', author: 'DeVaris Brown', }, { title: 'Tearing Down Data Silos', author: 'Hervé Labas', }, { title: 'Evolution of Application Data Platforms – From Facebook to Twitter', author: 'Pete Hunt', }, ]} imagePath="/blog/posts/meetup-prisma.png" />
</MeetupList>We love seeing laptops that are decorated with Prisma stickers, so we're shipping sticker packs for free to our community members! In this quarter, we've sent out over 300 sticker packs to developers that are excited about Prisma!
Every other Thursday, Nikolas Burk and Ryan Chenkie discuss the latest Prisma release and other news from the Prisma ecosystem and community. If you want to travel back in time and learn about a past release, you can find all the shows from this quarter here:
<Youtube videoId="2CDHn-Maij0" />This quarter, several Prisma folks have appeared on external channels and livestreams. Here's the overview of all of them:
Here's an overview of the awesome new Prismates we have hired this quarter:
<Employee name="Vladi Stevanovic" title="Sr. Customer Success Manager" imgURL="/blog/whats-new-in-prisma-q1-2021-spjyqp0e2rk1/imgs/XAUJcsA.png" joinDate="February 2021" funFact="I can cook the most amazing veggie Lasagna." whyPrisma="I'm very excited about the product and the mission - helping developers work more efficiently with data. I'm also very interested in developing the Customer Success program and empowering Prisma users." socialLinkedIn="https://www.linkedin.com/in/vladislava-stevanovic/" />
<Employee name="Chloé Votteler" title="Organisational Psychologist" imgURL="/blog/whats-new-in-prisma-q1-2021-spjyqp0e2rk1/imgs/tIGqo0V.png" joinDate="February 2021" funFact="I am not the biggest fan of ice cream and the only ice cream I would get is Pistachio 😆" whyPrisma="Prisma excites me as I realised I am going to find myself in a world of new challenges and possibilities. Working for a company like Prisma is an adventure and I am able to help create processes from scratch and develop workflows that best fit Prisma. The entrepreneurial nature undoubtably creates a lot of passion and I feel honoured to be a part of an unique experience to help build something." socialLinkedIn="https://www.linkedin.com/in/chloevotteler/" />
<Employee name="Chris Matteson" title="Head of Solutions Engineering" imgURL="/blog/posts/chris-matteson.jpeg" joinDate="February 2021" funFact="I only felt my first earthquake last year, despite living in California. Always managed to be out of town." whyPrisma="I joined Prisma for the same reason I joined HashiCorp in the early days, this is an enabling technology which unlocks workflows which were previously impossible. I’m honored to have a part in helping shepherd this along, as the team has already started us on a breakout path." socialLinkedIn="https://www.linkedin.com/in/chris-matteson-09a66b61?lipi=urn%3Ali%3Apage%3Ad_flagship3_search_srp_people%3B62Kmp00BSj%2BkRUdQx6wI%2FA%3D%3D" socialTwitter="https://twitter.com/MattesonChris" socialGithub="https://github.com/chrismatteson" />
<Employee name="Julieta Curdi" title=" Sr. Product Designer" imgURL="/blog/posts/julieta-curdi.jpeg" joinDate="March 2021" funFact="I'm a huge Harry Potter fan, in fact I own a wand 💫" whyPrisma="I'm excited about the product, the vision and the culture. I'm also excited about the opportunity to help build the Product Design practice at Prisma." socialLinkedIn="https://www.linkedin.com/in/julietacurdi/" socialTwitter="https://twitter.com/seriesofblurs" socialURL="https://julietacurdi.com/" />
<Employee name="Rich Haines" title="Tech Writer" imgURL="/blog/posts/rich-haines.jpeg" joinDate="March 2021" funFact="I majored in script writing at university and wrote a feature length film script about the greek gods in a godfather like setting" whyPrisma="The role aligned perfectly with what I want to do with my career, learn new stuff and write about it! Plus Prisma is cool, everyone knows that." socialTwitter="https://twitter.com/studio_hungry" socialGithub="https://github.com/molebox" socialURL="https://richardhaines.dev" />
Also, we are hiring for various roles! If you're interested in joining us and becoming a Prismate, check out our jobs page.
The best places to stay up-to-date about what we are currently working on are GitHub issues and our public roadmap.
We are currently working on a connector for MongoDB and are hoping to have an Early Access version of it ready in the next three months.
Another major area we are focusing on is the development of a cloud product that will make it easier for teams and larger organizations to collaborate on Prisma projects. To get an initial impression of what we are planning, you can watch the talks from the Prisma Enterprise Event. Stay tuned and keep an eye out for more articles on this blog in the next few weeks 👀