Skip to main content
Prisma Documentation Docs
current

Search documentation

Type to search this documentation.

On this pageOverview

From the CLI (Prisma ORM v7)

Start building a Prisma application with a Prisma Postgres database from the CLI

This page provides a step-by-step guide for Prisma Postgres after setting it up with prisma init and npx create-db:

  1. Set up a TypeScript app with Prisma ORM
  2. Migrate the schema of your database
  3. Query your database from TypeScript

This guide assumes you initialized Prisma with prisma init and created a Prisma Postgres database with npx create-db:

bun
bunx --bun prisma@prev init
bunx create-db
pnpm
pnpm dlx prisma@prev init
pnpm dlx create-db
yarn
yarn dlx prisma@prev init
yarn dlx create-db
npm
npx prisma@prev init
npx create-db

Once these commands have terminated:

  • The prisma/ folder was created with an empty schema.prisma file.
  • The DATABASE_URL env var was set in a .env file.
  • The prisma7.config.ts file was created with the default configuration.
  • You have a Prisma Postgres connection string to paste into .env.

If you ran the command outside your intended project directory (e.g., in your home folder or another location), you need to move the generated prisma folder and the .env file into a dedicated project directory.

Create a new folder (e.g. hello-prisma) where you want your project to live and move the necessary files into it:

Bash
mkdir hello-prisma
mv .env ./hello-prisma/
mv prisma ./hello-prisma/

Navigate into your project folder:

Bash
cd ./hello-prisma

Now that your project is in the correct location, continue with the setup.

Initialize a TypeScript project and add the Prisma CLI as a development dependency:

bun
bun init
pnpm
pnpm init
yarn
yarn init
npm
npm init
bun
bun add typescript tsx @types/node @types/pg --dev
pnpm
pnpm add typescript tsx @types/node @types/pg -D
yarn
yarn add typescript tsx @types/node @types/pg --dev
npm
npm install typescript tsx @types/node @types/pg -D

This creates a package.json file with an initial setup for your TypeScript app.

Next, initialize TypeScript with a tsconfig.json file in the project:

bun
bunx tsc --init
pnpm
pnpm tsc --init
yarn
yarn tsc --init
npm
npx tsc --init

Update tsconfig.json for ESM compatibility:

tsconfig.json
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2023",
    "strict": true,
    "esModuleInterop": true,
    "ignoreDeprecations": "6.0"
  }
}

Update package.json to enable ESM:

package.json
{  "type": "module"}

Install the required dependencies to use Prisma Postgres:

bun
bun add prisma@prev --dev
bun add @prisma/client@7 @prisma/adapter-pg pg dotenv
pnpm
pnpm add prisma@prev --save-dev
pnpm add @prisma/client@7 @prisma/adapter-pg pg dotenv
yarn
yarn add prisma@prev --dev
yarn add @prisma/client@7 @prisma/adapter-pg pg dotenv
npm
npm install prisma@prev --save-dev
npm install @prisma/client@7 @prisma/adapter-pg pg dotenv

Here's what each package does:

  • prisma - The Prisma CLI for running commands like prisma migrate and prisma generate
  • @prisma/client - The Prisma Client library for querying your database
  • @prisma/adapter-pg - The node-postgres driver adapter that connects Prisma Client to your database
  • pg - The node-postgres database driver
  • @types/pg - TypeScript type definitions for node-postgres
  • dotenv - Loads environment variables from your .env file

The prisma init command automatically created a prisma7.config.ts file that looks like this:

prisma7.config.ts
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});

Create an index.ts file in the root directory, this will be used to query your application with Prisma ORM:

Bash
touch index.ts

Update your prisma/schema.prisma file to include the User and Post models:

prisma/schema.prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql"
}

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

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

After adding the models, migrate your database using Prisma Migrate:

bun
bunx prisma migrate dev --name init
pnpm
pnpm prisma migrate dev --name init
yarn
yarn prisma migrate dev --name init
npm
npx prisma migrate dev --name init

This command creates the database tables based on your schema.

Now run the following command to generate the Prisma Client:

bun
bunx prisma generate
pnpm
pnpm prisma generate
yarn
yarn prisma generate
npm
npx prisma generate

Create a lib/prisma.ts file to instantiate Prisma Client with the driver adapter:

lib/prisma.ts
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../generated/prisma/client";

const connectionString = `${process.env.DATABASE_URL}`;

const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });

export { prisma };

Paste the following boilerplate into index.ts:

index.ts
import { prisma } from "./lib/prisma";

async function main() {
  // ... you will write your Prisma ORM queries here
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });

This code contains a main function that's invoked at the end of the script. It also instantiates PrismaClient which you'll use to send queries to your database.

Start with a small query that creates a new User record in the database and logs the resulting object to the console. Add the following code to your index.ts file:

index.ts
import { prisma } from "./lib/prisma";async function main() {  const user = await prisma.user.create({    data: {      name: "Alice",      email: "alice@prisma.io",    },  });  console.log(user);}main()  .then(async () => {    await prisma.$disconnect();  })  .catch(async (e) => {    console.error(e);    await prisma.$disconnect();    process.exit(1);  });

Next, execute the script with the following command:

bun
bunx tsx index.ts
pnpm
pnpm dlx tsx index.ts
yarn
yarn dlx tsx index.ts
npm
npx tsx index.ts
no-copy
{ id: 1, email: 'alice@prisma.io', name: 'Alice' }

You have created your first database record with Prisma Postgres.

Prisma ORM offers several queries to read data from your database. Next, use the findMany query, which returns all the records in the database for a given model.

Delete the previous Prisma ORM query and add the new findMany query instead:

index.ts
import { prisma } from "./lib/prisma";async function main() {  const users = await prisma.user.findMany();  console.log(users);}main()  .then(async () => {    await prisma.$disconnect();  })  .catch(async (e) => {    console.error(e);    await prisma.$disconnect();    process.exit(1);  });

Execute the script again:

bun
bunx tsx index.ts
pnpm
pnpm dlx tsx index.ts
yarn
yarn dlx tsx index.ts
npm
npx tsx index.ts
no-copy
[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }]

Notice how the single User object is now enclosed with square brackets in the console. That's because the findMany returned an array with a single object inside.

Prisma ORM reads and writes relations through the same query API. Next, create a User and a Post record in one nested write query, then retrieve the relation from the database with the include option.

First, adjust your script to include the nested query:

index.ts
import { prisma } from "./lib/prisma";async function main() {  const user = await prisma.user.create({    data: {      name: "Bob",      email: "bob@prisma.io",      posts: {        create: [          {            title: "Hello World",            published: true,          },          {            title: "My second post",            content: "This is still a draft",          },        ],      },    },  });  console.log(user);}main()  .then(async () => {    await prisma.$disconnect();  })  .catch(async (e) => {    console.error(e);    await prisma.$disconnect();    process.exit(1);  });

Run the query by executing the script again:

bun
bunx tsx index.ts
pnpm
pnpm dlx tsx index.ts
yarn
yarn dlx tsx index.ts
npm
npx tsx index.ts
no-copy
{ id: 2, email: 'bob@prisma.io', name: 'Bob' }

In order to also retrieve the Post records that belong to a User, you can use the include option via the posts relation field:

index.ts
import { prisma } from "./lib/prisma";async function main() {  const usersWithPosts = await prisma.user.findMany({    include: {      posts: true,    },  });  console.dir(usersWithPosts, { depth: null });}main()  .then(async () => {    await prisma.$disconnect();  })  .catch(async (e) => {    console.error(e);    await prisma.$disconnect();    process.exit(1);  });

Run the script again to see the results of the nested read query:

bun
bunx tsx index.ts
pnpm
pnpm dlx tsx index.ts
yarn
yarn dlx tsx index.ts
npm
npx tsx index.ts
no-copy
[
  { id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] },
  {
    id: 2,
    email: 'bob@prisma.io',
    name: 'Bob',
    posts: [
      {
        id: 1,
        title: 'Hello World',
        content: null,
        published: true,
        authorId: 2
      },
      {
        id: 2,
        title: 'My second post',
        content: 'This is still a draft',
        published: false,
        authorId: 2
      }
    ]
  }
]

This time, you're seeing two User objects being printed. Both of them have a posts field (which is empty for "Alice" and populated with two Post objects for "Bob") that represents the Post records associated with them.

This page covered a basic Prisma Postgres setup. The Quickstart covers the full setup.

Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command:

bun
bunx prisma studio --config ./prisma7.config.ts
pnpm
pnpm prisma studio --config ./prisma7.config.ts
yarn
yarn prisma studio --config ./prisma7.config.ts
npm
npx prisma studio --config ./prisma7.config.ts

With Prisma Postgres, you can also directly use Prisma Studio inside the Console by selecting the Studio tab in your project.

Learn how to use Prisma Postgres in a fullstack app:

Check out the prisma-examples repository on GitHub to see how Prisma ORM can be used with the library you work with. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more.

These examples use SQLite by default; the project README explains how to switch them to Prisma Postgres.

Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu