prisma-seeder
v1.0.2
Published
Adds seeding support to Prisma ORM for populating your database with initial data.
Downloads
199
Maintainers
Readme
Prisma-Seeder
Take control of your Prisma seeds.
Write seeds with familiar up and down functions——just like classic migrations.
Usage
- Install with npm
npm install prisma-seeder- Add
PrismaSeedsmodel. We use it to keep track of already executed seeds.
// schema.prisma
model PrismaSeeds {
name String @id()
@@map("_prisma_seeds")
@@ignore
}- Run migrations
prisma migrate dev- Create a new file named
seed.ts. This can be placed anywhere within your project's folder structure. The example below places it in the/prismafolder. This script is a runnable CLI program. Check the available options under CLI
// seed.ts
import { PrismaSeeder } from 'prisma-seeder'
import { PrismaClient } from '@prisma/client'
import path from 'path'
// Required if using ESM
const __dirname = import.meta.dirname
const db = new PrismaClient()
async function main() {
const seeder = new PrismaSeeder({
client: db,
seeds: path.join(__dirname, './seeds/*.{ts,js}') // Glob pattern to match your seeds
})
await seeder.run()
process.exit()
}
main()- Add this command in the
"seed"key in the"prisma"key of yourpackage.jsonfile. Prisma executes the seeds manually withprisma db seedand automatically inprisma migrate resetand (in some scenarios)prisma migrate dev
"prisma": {
"seed": "tsx prisma/seed.ts up"
},NOTE: you can use any execution engine of your choice to run the script, such as
ts-nodefor TypeScript or simplynodefor JavaScript files. For the rest of the docs we are going to usetsx
Command Line Interface Usage
You can run tsx prisma/seed.ts --help to see how to use it. It will print something like:
Usage: seed [options] [command] ...
Options:
-h, --help display help for command
Commands:
up Applies pending seeds
down Revert seeds
refresh Re-applies seeds skipping rollback
reset Rollback and re-applies seeds
For detailed help about a specific command, use: seed [command] -hRunning seeds: up
Run tsx prisma/seed.ts up to apply pending seeds. Use tsx prisma/seed.ts --help to see all available options.
Usage: seed up [options]
Applies pending seeds
Options:
-n, --name <names...> Specify seed names
-s, --steps <number> Specify number of steps
-h, --help display help for commandRunning seeds: down
Run tsx prisma/seed.ts down to revert seeds. You should provide one of the options --name or --steps to select the seeds to revert.
Use tsx prisma/seed.ts --help to see all available options.
Usage: seed down [options]
Revert seeds
Options:
-n, --name <names...> Specify seed names
-s, --steps <number> Specify number of steps
-h, --help display help for commandRefresh seeds: refresh
Run tsx prisma/seed.ts refresh to re-applies seeds skipping any rollback process. The --name option is required; otherwise, no seeds will be refreshed.
Use tsx prisma/seed.ts refresh --help to see all available options.
Usage: seed refresh [options]
Re-applies seeds skipping rollback
Options:
-n, --name <names...> Specify seed names
-h, --help display help for commandNote: For this command to work, the seed must be idempotent—meaning it should be able to run multiple times without failing. For example, use
upsertinstead ofcreate.
Reset seeds: reset
Run tsx prisma/seed.ts reset to rollback and re-apply seeds. It's equivalent to running down and up.
Usage: seed reset [options]
Rollback and re-applies seeds
Options:
-n, --name <names...> Specify seed names
-h, --help display help for commandGenerate seeds: generate
Run tsx prisma/seed.ts generate to create a new seed file. By default, it uses the path defined in your script at PrismaSeeder.seeds, but you can specify a custom path using the --dir option. You can also provide a seed name with the --name option, or enter it later when prompted.
Use tsx prisma/seed.ts generate --help to see all available options.
Usage: seed generate [options]
Generate a new seed file
Options:
-n, --name <name...> Name of the seed file
-d, --dir <dir> Directory to save the seed file
-h, --help display help for commandExamples
Seeding your database
We are going to seed our Category model
model Category {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String @unique()
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}- Create a new file with seed data
// categories.ts
interface Category {
id: string
name: string
}
export const categories: Category[] = [
{
// Use a constant id to make the seed idempotent
id: '61ba3e3b-2fbe-4ede-b4d4-d39cbf9e7c4c',
name: 'Elf'
},
{
id: 'e9620577-af7f-4eaa-abea-1724ce95aa84',
name: 'Dryad'
},
{
id: 'cb1e2ec1-a5b5-4330-ae85-4e0a046f50e9',
name: 'Gnome'
}
]
- Generate the new seed with
up&downfunctions
tsx prisma/seed.ts generate --name add_categories- Update the generated seed
import { PrismaClient } from '@prisma/client'
import { categories } from './data/categories.js'
type Db = PrismaClient
export const up = async (db: Db) => {
// Use transaction to make sure all operation succeed
await db.$transaction(
categories.map((category) =>
/**
* Use upsert to be able to run this seed multiple times by using "refresh" command
* We can create/update categories and use "refresh" command to update table with new data
*/
db.category.upsert({
where: { id: category.id },
create: category,
update: { name: category.name }
})
)
)
}
export const down = async (db: Db) => {
await db.category.deleteMany({
where: {
id: {
in: categories.map((category) => category.id)
}
}
})
}
- To seed the database, run the
seed upCLI command:
tsx prisma/seed.ts up