DEV Community

Cover image for Seeding Database With Drizzle ORM

Seeding Database With Drizzle ORM

anasrin on September 24, 2023

Database This post assume using PostgreSQL for database, check orm.drizzle.team/docs/overview for more information how to connnect to yo...
Collapse
 
chanidog profile image
chanidog

wouldnt mass updating the db like this mess up with its primary key sequence?

Collapse
 
chanidog profile image
chanidog

my bad, it wouldnt since you are not setting the primary key thus its auto incrementing on every user you insert. in my case tho i was passing the primary key manually so the sequence was not auto incrementing and was never updated and stayed at the last id in my case 1. so when i went and added a record without an id i got this error:
⨯ NeonDbError: duplicate key value violates unique constraint "users_pkey"

because it was trying to insert the record with an id of 1 but i already added a record with an id of 1.

to fix this i ran a query to update the primary key sequence like this after my seed script

await db.execute(
      sql`SELECT setval(pg_get_serial_sequence('courses', 'id'), (SELECT COALESCE(MAX(id), 0) + 1 FROM courses));`,
    );
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dennisk profile image
Dennis Keirsgieter

Or you can use uuid's (generated with something like crypto.randomUUID) to not even care about this anymore

Collapse
 
ryanleecode profile image
Ryan Lee

WRONG!

Collapse
 
anasrin profile image
anasrin

Which one is wrong ?

Collapse
 
spiffgreen profile image
Spiff Jekey-Green

Nice, I like that you did not do the db updates in the loop, something many will fail at.

Collapse
 
manish_chetwani_197c4027a profile image
Manish Chetwani

Can you share why does this happen?

I am using this approach and failing.

Collapse
 
mdapu profile image
Md A. Apu

Nice write-up. I think tsx package is better suited for the task. Here's an example.

Collapse
 
mohsincode profile image
Mohsin • Edited

I dont see your scripts