HomeToolsAbout

Prisma

Syntax

// Query public async getProfileName(id: string): Promise<string> { const profileName = await this.prisma.user.findFirst({ where: { id }, select: { name: true, }, }); if (!profileName) { throw new NotFoundError(); } return JSON.stringify(profileName); } // Mutations // create const newUser = await prisma.user.create({ data: { name: "Alice", email: "alice@example.com", }, }); // update const updatedUser = await prisma.user.update({ where: { id: 1 }, data: { name: "Updated Name", }, }); // delete const deletedUser = await prisma.user.delete({ where: { id: 1 }, });

where (filtering)

Source

findMany

findMany defaults to AND

Below where clause will return records that match both name and email field conditions

where: { name: { in: ['Sam', 'Clemens', 'Bob'], }, email: { contains: 'example.com', }, }

Override the default AND behavior by using OR[] field wrapping

where: { OR: [ { name: { in: ['Sam', 'Clemens', 'Bob'], }, }, { email: { contains: 'example.com' }, }, ], }

in

Find values that exist in the list

  • null values are not returned
    • For example, if you combine in and NOT to return user whose name is not in the list, users with null value names are not returned

Example: Get User records where the id can be found in the following list:

  • [22, 91, 14, 2, 5]
const getUser = await prisma.user.findMany({ where: { id: { in: [22, 91, 14, 2, 5] }, }, });

NOT

Exclude records from the result set using the NOT field

const getUser = await prisma.user.findMany({ where: { NOT: { name: { in: ['Saqui', 'Clementine', 'Bob'] }, }, }, })

Transactions

Create transactions

await prisma.$transaction([ prisma.user.create({ data: { name: "Bob" } }), prisma.post.create({ data: { title: "New Post", content: "Content" } }), ]);

Logging

Logging Prisma results need Json Stringify

console.log(JSON.stringify(result));

Model

Model Definitions

// Define a User model model User { id Int @id @default(autoincrement()) name String email String @unique posts Post[] }

Migration

Creating migration

Write your schema updates to the schema file

repo_name/prisma/schema.prisma

OR Create a new migration file using yarn

yarn workspace workspace_name db:makeMigration migration_name

This will create a new migration.sql containing the effective SQL changes based on the schema delta generated

Running migration

Running yarn db:migrate will apply the new changes to your local database

Raw Queries

$queryRaw

Accepts template literal string to execute as a SQL query

const result = await prisma.$queryRaw`SELECT * FROM User`

Because it accepts a template literal string, you can pass variables to the query

const email = 'emelie@prisma.io'; const result = await prisma.$queryRaw`SELECT * FROM User WHERE email = ${email}`;
AboutContact