Documentation
Database
Prisma Setup

Prisma Setup

Learn about Prisma configuration and usage in Dirstarter

Prisma is a modern database toolkit that serves as the ORM for Dirstarter. This guide explains how Prisma is configured and used in the project.

Prisma provides several key components:

  • Prisma Client: Auto-generated type-safe query builder
  • Prisma Schema: Defines your database models and relationships
  • Prisma Migrate: Handles database migrations
  • Prisma Studio: GUI to view and edit data

Dirstarter comes with Prisma pre-configured with PostgreSQL. The main Prisma-related files are:

  • prisma/schema.prisma: Defines your database schema
  • prisma/seed.ts: Contains seed data for development
  • services/db.ts: Configures and exports the Prisma client

Setup

  1. Set up your PostgreSQL database
  2. Add your database URL to .env:
    .env
    DATABASE_URL="postgresql://user:password@host:5432/dirstarter"

Database Management Commands

The following commands are available in package.json:

npm run db:generate # Generate Prisma Client
npm run db:migrate # Create and apply migrations
npm run db:studio # Open Prisma Studio (GUI)
npm run db:push # Push schema changes directly to database
npm run db:reset # Reset database and apply migrations
npm run db:seed # Seed database with initial data

Updating Database Schema

To update your database schema, edit the prisma/schema.prisma file. Here's how to manage schema changes:

Edit Schema

Add or modify models in prisma/schema.prisma. For example, to add a new model:

model Post {
  id        String   @id @default(cuid())
  title     String
  content   String
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

Create Migration (Optional)

To track schema changes in version control:

bun run db:migrate

This creates a new migration file in prisma/migrations.

Push Changes

Apply schema changes to your database:

bun run db:push

Generate Client

After pushing changes, regenerate the Prisma client:

bun run db:generate

Note: This runs automatically when starting the development server.

Seeding the Database

The project includes a comprehensive seed file (prisma/seed.ts) that creates demo data:

  1. Default users (admin and regular user)
  2. Common categories (Frontend, Backend, etc.)
  3. Popular tags (React, Vue, TypeScript, etc.)
  4. Sample tools with relationships

Feel free to modify the seed data as needed. You can also clear the database and start fresh with npm run db:reset once you start to feel comfortable with the data in your database.

Customizing Seed Data

To modify the seed data:

  1. Edit prisma/seed.ts
  2. Run npm run db:reset to apply changes

Seeding from CSV

To seed from a CSV file, modify prisma/seed.ts and adjust the code to your needs.

prisma/seed.ts
import { parse } from 'csv-parse/sync'
import { readFileSync } from 'fs'
 
async function main() {
  const csvContent = readFileSync('./data/tools.csv', 'utf-8')
  const records = parse(csvContent, {
    columns: true,
    skip_empty_lines: true
  })
 
  for (const record of records) {
    await prisma.tool.create({
      data: {
        name: record.name,
        slug: record.slug,
        websiteUrl: record.websiteUrl,
        // ... map other fields
        categories: {
          connect: record.categories.split(',').map(slug => ({ slug }))
        },
        tags: {
          connect: record.tags.split(',').map(slug => ({ slug }))
        }
      }
    })
  }
}

Prisma Client Usage

The Prisma client is initialized as a singleton in services/db.ts:

services/db.ts
import { PrismaClient } from "@prisma/client"
 
const prismaClientSingleton = () => {
  return new PrismaClient()
}
 
declare const globalThis: {
  dbGlobal: ReturnType<typeof prismaClientSingleton>
} & typeof global
 
const db = globalThis.dbGlobal ?? prismaClientSingleton()
 
export { db }
 
if (process.env.NODE_ENV !== "production") globalThis.dbGlobal = db

Use it in your code:

import { db } from "~/services/db"
 
// Example query
const tools = await db.tool.findMany({
  where: { status: "Published" },
  include: { categories: true, tags: true }
})

To learn more about the Prisma client, check out the official documentation.

Prisma Studio

Prisma Studio is a GUI to view and edit data in your database. You can open it by running the following command in the terminal:

Terminal
npm run db:studio

This will start the Prisma Studio in your browser. You can use it to view and edit data in your database.

Prisma Studio

VS Code Integration

The project includes Prisma VS Code extension recommendations for:

  • Syntax highlighting
  • Auto-completion
  • Schema validation
  • Quick fixes

Install the recommended extensions for the best development experience.

Edit on GitHub

Last updated on

On this page