projeye veritabanı işlemleri için nasıl prisma kurulur ve çalıştırılır. temel komutları nelerdir

How to Install, Configure, and Run Prisma for Your Project: A Complete Starter Guide

Learn how to install, configure, and run Prisma for your project with this complete starter guide. Step-by-step instructions to get started quickly and efficiently.

11/25/2025 · 09:03 AM

Why Prisma?

If you’ve ever wrestled with handwritten SQL, inconsistent migrations, or cryptic ORM documentation, Prisma feels like a breath of fresh air. It gives you a type-safe database client, declarative schema syntax, and a built-in migration engine—all without hiding the raw power of SQL when you need it. In this guide you’ll learn how to bolt Prisma onto an existing Node/TypeScript project, run your first migration, and master the everyday CLI commands you’ll use in real life.

Prerequisites

  • Node.js ≥ 16
  • npm, yarn, or pnpm
  • A running PostgreSQL, MySQL, SQLite, SQL Server, or MongoDB instance (we’ll use PostgreSQL for examples)
  • Basic familiarity with TypeScript or JavaScript

Step 1: Add Prisma to Your Project

Open a terminal in your project root and install the CLI and client:

npm install prisma @prisma/client --save-dev --save

Initialize Prisma to scaffold the default structure:

npx prisma init

The command creates a prisma folder containing schema.prisma and a .env file. The schema file is your single source of truth for tables, relations, and client configuration.

Fresh Prisma setup inside VS Code
Fresh Prisma setup inside VS Code

Step 2: Point Prisma at Your Database

Edit .env and replace the placeholder with your real connection string:

DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/mydb?schema=public"

If you’re on SQLite, simply provide a file path:

DATABASE_URL="file:./dev.db"

Step 3: Design Your First Schema

Open prisma/schema.prisma. The default content looks like this:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

Let’s add two tables: User and Post.

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?
  author   User    @relation(fields: [authorId], references: [id])
  authorId Int
}

Save the file. Prisma’s VS Code extension will underline syntax errors in real time, so you’ll know immediately if something is off.

Step 4: Create and Apply Your First Migration

Run:

npx prisma migrate dev --name init

Prisma compares your schema to the target database (currently empty), generates the SQL needed, writes it to a prisma/migrations folder, and applies it. You should see:

✔ Your database is now in sync with your schema.
Successful initial migration
Successful initial migration

Step 5: Generate the Type-Safe Client

Whenever the schema changes you must regenerate the client:

npx prisma generate

This command creates a tailored Node module inside node_modules/@prisma/client that mirrors your tables and relations. Because the types are generated from your real schema, misspelled fields or wrong types become compile-time errors instead of runtime surprises.

Step 6: Use Prisma Client in Your Code

Create src/db.ts (or any filename you prefer):

import { PrismaClient } from '@prisma/client'

export const prisma = new PrismaClient()

Now you can import prisma anywhere and start querying:

const user = await prisma.user.create({
  data: {
    email: '[email protected]',
    name: 'Ada Lovelace',
    posts: {
      create: { title: 'Notes on Babbage’s Engine' }
    }
  },
  include: { posts: true }
})

All CRUD operations—create, findMany, update, delete, upsert, aggregate, groupBy—are strongly typed and auto-completed.

Type-safe autocomplete in action
Type-safe autocomplete in action

Everyday Prisma CLI Commands Cheat-Sheet

CommandPurpose
prisma migrate devCreate and apply migrations during development
prisma migrate resetDrop DB, recreate, and re-seed (handy for tests)
prisma migrate deployApply pending migrations in production
prisma db pushPrototype quickly—sync schema without creating a migration file
prisma db seedRun the seed script defined in package.json
prisma generateRegenerate the Prisma Client
prisma studioOpen a local web UI to browse and edit data
prisma formatAuto-format your schema.prisma file
prisma validateCheck for schema errors without generating code

Seeding: Fill Your Database with Sample Data

Add a prisma/seed.ts file:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

async function main() {
  await prisma.user.createMany({
    data: [
      { email: '[email protected]', name: 'Grace Hopper' },
      { email: '[email protected]', name: 'Tim Berners-Lee' }
    ]
  })
}

main()
  .catch(e => { throw e })
  .finally(async () => { await prisma.$disconnect() })

Tell Prisma how to run the seed by adding this entry to package.json:

"prisma": {
  "seed": "ts-node prisma/seed.ts"
}

Now npx prisma db seed will populate your database anytime you need fresh sample data.

Production Workflow Tips

  1. Always check migrations into version control; treat them like locked SQL contracts.
  2. Run prisma migrate deploy in CI/CD instead of migrate dev to avoid accidental schema drift.
  3. Use $transaction or interactive transactions for multi-statement workflows that must roll back together.
  4. Enable query logging with log: ['query'] during early production days to spot N+1 issues quickly.
  5. Back up your database before any migrate deploy in production; migrations are generally safe, but paranoia pays.

Common Gotchas & Quick Fixes

Client not updated?
Run npx prisma generate after every schema change. CI should do this automatically.

Migration fails with “P3005”?
Your database already contains data that conflicts with the new constraint. Resolve data first, or use --create-only to tweak the generated SQL.

Environment variables not loading?
Ensure your .env file is in the same folder where you run the Prisma CLI, or use dotenv/config explicitly.

Next Steps

Congratulations—Prisma is installed, migrations are flowing, and your code is type-safe. From here you can explore advanced filters, raw SQL escapes, connection pooling with prisma-data-proxy, or plug Prisma into GraphQL resolvers. Whatever direction you choose, the commands and patterns above will remain the reliable foundation of your database workflow.

Article Details

Primary Category
How to Do It
Content Type
BLOG
Published at

share