Starchart: Seeding
cychu42
Posted on February 10, 2023
This week, my main focus is to work on seeding the database for Starchart project. (see PR)
I thought it would be more complicated, but it's actually just writing query with Prisma to insert rows of data into database tables, and there's a bit of script setup.
Setup (official documentation)
Requirement:
Make sure you have Prisma setup already. You need to first have a pakcage.json
generated from npm init
too.
-
Inside
pakcage.json
, add the following:
"prisma": { "seed": "ts-node prisma/seed.ts" }
If your project needs to use compile option, you should use this instead:
"prisma": { "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts" },
Add
seed.ts
underprisma
folder.Add code for "create" query inside the file to add rows of data.
Run
npx prisma db seed
.
There! If the steps are done correctly, you just seeded the database with some data for testing or whatever you need to do!
Experience
I realized there are a few things to consider as I worked on this.
You need to thing about cleaning existing data. Because there are some foreign keys in the schema, I need to think about the order I delete data from each table. Otherwise, it can run into errors. It would be easier if one sets up cascading delete, where a row is automatically deleted if the referenced row (usually from another table) for the row's foreign key is deleted.
Because of the foreign keys, another thing to consider is to create things in the correct order, so there's something to be referenced before referencing it.
Lastly, it would be intuitive to let index auto-increment and make index the thing to be referenced for foreign keys. However, doing both would present a problem when you are doing seeding. The referenced value need to stay consistent so that you can properly connect one row to a specific row. Therefore, you actually need to specify the index in such scenario, such as the id
here:
Posted on February 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.