Skip to content

Create seed data #16

@b-at-neu

Description

@b-at-neu

Database Seeding Spec

Overview

Add idempotent seed data to populate local and dev databases with 4-5 rows per table using predefined lists and simple patterns. Never runs in production.

Implementation

Create prisma/seed.ts

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// Predefined data arrays
const FIRST_NAMES = ['Alex', 'Jordan', 'Taylor', 'Morgan', 'Casey']
const LAST_NAMES = ['Smith', 'Johnson', 'Williams', 'Brown', 'Davis']

const randomItem = <T>(arr: T[]): T => arr[Math.floor(Math.random() * arr.length)]

async function main() {
  if (process.env.NODE_ENV === 'production') {
    console.log('Seeding disabled in production')
    return
  }

  const existingData = await prisma.[model].findFirst()
  if (existingData) {
    console.log('Already seeded, skipping...')
    return
  }

  console.log('Seeding database...')
  
  // Create 4-5 rows per table using predefined lists
  // Example: Sequential emails, random names from arrays, simple date offsets
  
  console.log('Seeding complete!')
}

main()
  .catch((e) => {
    console.error('Seeding error:', e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

Update package.json

{
  "scripts": {
    "db:reset": "docker compose down -v && docker compose up -d && npm run prisma:migrate && npm run prisma:seed",
    "prisma:migrate": "prisma migrate dev",
    "prisma:seed": "prisma db seed",
    "prisma:studio": "prisma studio"
  },
  "prisma": {
    "seed": "tsx prisma/seed.ts"
  },
  "devDependencies": {
    "tsx": "^latest"
  }
}

Update GitHub Workflow

Add after migration step (dev branch only):

- name: Seed database
  if: github.ref == 'refs/heads/dev'
  run: npm run prisma:seed
  env:
    NODE_ENV: development

Data Patterns

  • Strings: Random selection from predefined arrays
  • Emails: Sequential (user1@example.com, user2@example.com)
  • Numbers: Sequential or simple ranges
  • Dates: new Date() with day offsets
  • Booleans: Alternating pattern

Key Requirements

  • Check if data exists before seeding (idempotent)
  • 4-5 rows per table minimum
  • Include at least one predictable record (e.g., admin user)
  • Production safety check via NODE_ENV

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions