-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for database seeding #9
Comments
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Thanks. For development, |
Would you want |
For my development needs, resetting the data is probably enough (the schema is work in progress, and every now and then it makes sense to just start with the an empty database [seeded with some basic seed data] based on the current schema). |
Hi. I see that there is seed command (removed from CLI since it's not implemented yet) and that's really great. It was always a pain in the ass for me to write custom seeding scripts for various databases for different projects. I just want to make a few suggestions for the functionality. I don't know what you guys have in mind for this, but this is what I would like to have with prisma2.
Something like this:
Those are the use cases that I had with every project (seeding from code for integration testing, and from version controlled files for development and production). What do others think? I would like to contribute on this subject if you accept contributions :) |
Just wanted to share my use-case with this. For dev, seeds are used to fill in all kinds of data so that other developers don't have to manually enter the data. In production we use seeds to fill in static values such as default categories, etc. All of these insertions are actually |
So I ended up just creating this file under EDIT: Instead of using import { prisma } from "../../prisma";
import { Category } from "@prisma/client";
const seed = async () => {
const categories: CategoryCreateInput[] = [
{
id: 'c3121e0b-9f78-4c99-8f16-18c10ea6ada0',
name: 'category1'
},
{
id: '32288e9e-ff04-4f91-8117-db85bf6cdf29',
name: 'category2'
},
];
for (const category of categories) {
await prisma.category.upsert({
create: category,
update: category,
where: {
id: category.id
}
})
}
}
seed().catch(err => {
throw err;
}).finally(() => {
prisma.disconnect();
}); |
@nahtnam and you can reset your tables previously with (#742 (comment)) import { PrismaClient } from '@prisma/client';
const tableNames = [
'User',
'Store'
];
export default async () => {
const prisma = new PrismaClient();
try {
for (const tableName of tableNames) {
await prisma.raw(`DELETE FROM "${tableName}";`);
if (!['Store'].includes(tableName)) {
await prisma.raw(
`ALTER SEQUENCE "${tableName}_id_seq" RESTART WITH 1;`
);
}
}
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
} finally {
await prisma.disconnect();
}
}; |
I noticed the above code samples use await in for loops. For seeding, this might be fine but it's not taking full advantage of parallelization: https://eslint.org/docs/rules/no-await-in-loop This should be faster when you get lots of migrations:
|
Is there a third party library that I can use? Something that integrate directly to the work flow? |
Why is this vital feature not part of prisma cli? |
In case it helps, somewhat related. We’ve created comprehensive seed scripts that test the environment prior to seed execution. We also use a secrets manager DopplerHQ, which helps keep things clean and tidy as it relates to environment variables. /scripts/prisma/seed/create/index.mjs// Packages
import shell from 'shelljs'
// Scripts
import setEnv from '../../../utils/setEnv.mjs'
const ScriptPrismaSeedCreate = async () => {
// Get and manually set environment, each time; we want to make sure we’re using the right environment
const env = await setEnv()
// Development, including staging and features
if (env.startsWith('feature') || env === 'develop' || env === 'staging') {
shell.exec('doppler run -- node --experimental-modules ./scripts/prisma/seed/create/dev/index.mjs')
}
// Production
else if (env === 'production') {
shell.exec('doppler run -- node --experimental-modules ./scripts/prisma/seed/create/prd/index.mjs')
}
}
ScriptPrismaSeedCreate() /scripts/prisma/seed/create/dev/index.mjs// Prisma
import pkg from '@prisma/client'
const { PrismaClient } = pkg
const prisma = new PrismaClient()
// Data
import users from './users.mjs'
import venues from './venues.mjs'
import venueRegions from './venueRegions.mjs'
const batch = [
...users.map(data => prisma.user.create({ data })),
...venueRegions.map(data => prisma.venueRegion.create({ data })),
...venues.map(data => prisma.venue.create({ data })),
]
async function start() {
for await (let item of batch) {
console.log(`\n☑️️ Added: ${JSON.stringify(item)}`)
}
}
start()
.catch(e => console.error(e))
.finally(() => process.exit(0)) /scripts/utils/setEnv.mjs// Packages
import inquirer from 'inquirer'
import shell from 'shelljs'
// Utilities
import colors from './colors.mjs'
const ScriptUtilsSetEnv = async () => {
console.log(
`\n${colors.green}The following environment is currently being used:${colors.yellow}\n`
)
const currentEnv = await shell.exec('doppler run -- printenv DOPPLER_CONFIG')
console.log(`${colors.end}`)
const res = await inquirer.prompt([
{
type: 'list',
name: 'env',
message: 'Please select the environment you’d like to use for this operation:',
// List your various environments here
choices: ['feature', 'develop', 'staging', 'production']
}
])
if (currentEnv.stdout.includes(res.env)) {
console.log(
`\n${colors.green}The environment was left as-is:${colors.yellow}\n\n${res.env}\n${colors.end}`
)
return res.env
}
shell.exec(`\ndoppler configure set enclave.config=${res.env}\n`)
console.log(
`\n${colors.green}The environment has been set to:\n\n${colors.yellow}${res.env}${colors.end}\n`
)
return res.env
}
export default ScriptUtilsSetEnv |
How exactly are you calling
or I can't import the singleton prisma client variable. |
this is my example repo, hope it would be helpful. |
prisma/prisma#9 Might want to look into versioning the seeds just like the migrations with dates, but dunno why the reason for that is though.
Just dropping a note to inform everyone that this is currently being worked on. We are adding a This will also be triggered after database resets when using Prisma Migrate (sometimes triggered interactively via |
@albertoperdomo Will there be a way to differentiate between |
Whether they implement this or not, these things should be trivial using environment variables. |
@nahtnam Not out of the box, no. These are currently designed for use in development. It should be fairly trivial however, to either create a separate seed script for production or to write your seed implementation in a way that lets you conditionally do stuff based on the environment, as @Bram-Zijp suggested. |
In 2.15.0 (released today, release notes here), we've introduced a new This functionality is currently in Preview. |
Problem
Seeding a database is a process in which a database (usually empty) is populated with an initial set of data. This is often an automated process that is executed upon the initial setup of an application. The data can be dummy data or necessary data such as an initial administrator account.
Use cases:
Considerations:
Prior art
Prisma1 has a CLI command seed, which reads the configuration from the prisma.yml file. It can execute a seed script written JS.
Possible Solutions
The text was updated successfully, but these errors were encountered: