{"id":16341,"library":"drizzle-seed","title":"Drizzle Seed","description":"Drizzle Seed is a TypeScript library designed for generating deterministic, yet realistic, fake data to populate databases in conjunction with Drizzle ORM. It leverages a seedable pseudorandom number generator (pRNG) to ensure that generated data is consistent and reproducible across different runs, which is crucial for reliable testing, development, and debugging workflows. The library currently stands at version 0.3.1 (within the Drizzle ecosystem's 0.x series for utilities), with ongoing active development that typically follows the release cadence and advancements of Drizzle ORM. Key differentiators include its tight integration with Drizzle ORM's type safety, its focus on reproducible data sets via pRNG, and a flexible API for refining data generation at column and table levels, including handling complex relationships. It enables developers to easily reset and re-seed their databases with predictable data.","status":"active","version":"0.3.1","language":"javascript","source_language":"en","source_url":"https://github.com/drizzle-team/drizzle-orm","tags":["javascript","drizzle","orm","pg","mysql","postgresql","postgres","sqlite","database","typescript"],"install":[{"cmd":"npm install drizzle-seed","lang":"bash","label":"npm"},{"cmd":"yarn add drizzle-seed","lang":"bash","label":"yarn"},{"cmd":"pnpm add drizzle-seed","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core ORM functionality is required for schema definition and database interaction.","package":"drizzle-orm","optional":false}],"imports":[{"note":"The primary function for initiating the seeding process. Always a named import.","wrong":"import seed from 'drizzle-seed'; // Not a default export","symbol":"seed","correct":"import { seed } from 'drizzle-seed';"},{"note":"Used to clear tables before seeding, typically imported alongside `seed`.","wrong":"const reset = require('drizzle-seed').reset; // CommonJS is supported but ESM is preferred.","symbol":"reset","correct":"import { reset } from 'drizzle-seed';"},{"note":"Though not exported directly as `Fake`, the `refine` callback receives a 'faker' object, often conceptually referred to as the 'Fake' data generator. For direct column value generation, the `refine` function provides helper methods rather than a top-level `Fake` export. The `f` argument in `refine((f) => ...)` is an instance of the internal faker.","symbol":"Fake","correct":"import { seed, Fake } from 'drizzle-seed';"}],"quickstart":{"code":"import 'dotenv/config';\nimport { pgTable, serial, text, timestamp, integer } from 'drizzle-orm/pg-core';\nimport { drizzle } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\nimport { seed, reset } from 'drizzle-seed';\n\nexport const users = pgTable('users', {\n  id: serial('id').primaryKey(),\n  name: text('name').notNull(),\n  email: text('email').notNull().unique(),\n  age: integer('age').notNull(),\n  createdAt: timestamp('created_at').notNull().defaultNow(),\n});\n\nexport const posts = pgTable('posts', {\n  id: serial('id').primaryKey(),\n  title: text('title').notNull(),\n  content: text('content'),\n  userId: integer('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),\n  createdAt: timestamp('created_at').notNull().defaultNow(),\n});\n\nconst pool = new Pool({\n  connectionString: process.env.DATABASE_URL ?? 'postgresql://user:password@localhost:5432/drizzle_test_db',\n});\n\nconst db = drizzle(pool, { schema: { users, posts } });\n\nasync function runSeed() {\n  try {\n    console.log('Starting database reset...');\n    // Clears all specified tables, respecting foreign key constraints.\n    await reset(db, { users, posts });\n    console.log('Database reset complete.');\n\n    console.log('Starting database seeding...');\n    await seed(db, { users, posts }).refine((f) => ({\n      users: {\n        count: 5, // Create 5 users\n        columns: {\n          name: () => f.fullName(),\n          email: () => f.email(),\n          age: () => f.number.int({ min: 18, max: 80 }),\n        },\n        with: {\n          posts: 3, // Each user gets 3 posts\n        },\n      },\n      posts: {\n        columns: {\n          title: () => f.lorem.sentence(),\n          content: () => f.lorem.paragraph(),\n        },\n      },\n    }));\n    console.log('Database seeding complete.');\n  } catch (error) {\n    console.error('Seeding failed:', error);\n    process.exit(1);\n  } finally {\n    await pool.end();\n    process.exit(0);\n  }\n}\n\nrunSeed();","lang":"typescript","description":"This quickstart demonstrates how to define a Drizzle schema, connect to a PostgreSQL database, then use `reset` to clear tables and `seed` to populate them with deterministic fake data, including related entities. It shows column-level data generation and `with` for relations."},"warnings":[{"fix":"Upgrade to `drizzle-seed@0.3.0` or higher. If upgrading is not immediately possible, a manual workaround is to run `SELECT setval('your_table_id_seq', (SELECT MAX(id) FROM your_table));` after seeding to update the sequence.","message":"Older versions of `drizzle-seed` (prior to 0.3.0) did not correctly synchronize PostgreSQL serial sequences after seeding. This could lead to `duplicate key value violates unique constraint` errors when inserting new records after a seed operation.","severity":"breaking","affected_versions":"<0.3.0"},{"fix":"Ensure that your Drizzle schema column definitions match the actual casing in your database when using `drizzle-seed`, or manually specify column names in `refine` to align with the database's expected casing. This issue can be subtle as `drizzle-orm` itself handles casing, but `drizzle-seed` has had reports of not respecting it.","message":"When using Drizzle ORM's casing configuration (e.g., `snake_case`), `drizzle-seed` might not correctly apply this casing to column names during insertion. This can lead to `column \"columnName\" does not exist` errors if the schema definition uses a different casing than the actual database.","severity":"gotcha","affected_versions":">=0.3.0"},{"fix":"Execute your seed script directly using `node your-seed-script.js`, `ts-node your-seed-script.ts`, or similar runtime commands. For example: `bun run ./src/db/seed.ts`.","message":"`drizzle-seed` is a library, not a standalone executable. Attempting to run it directly via `npx drizzle-seed` will result in an error indicating it cannot determine an executable. Seed scripts must be run via Node.js (or `tsx`/`bun`/`deno` for TypeScript files).","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure `drizzle-orm` is updated to version `0.36.4` or higher in your project dependencies.","message":"`drizzle-seed` has a peer dependency on `drizzle-orm` version `>=0.36.4`. Using older versions of `drizzle-orm` may lead to type mismatches, runtime errors related to identity columns, or other unexpected behavior due to API changes.","severity":"breaking","affected_versions":"<0.3.0"},{"fix":"Always include all related tables in the schema argument of the `seed` function. Ensure `not-null` foreign key columns are either populated by `with` for related entities or have an explicit generator defined in `refine`. For complex or circular relations, manually provide `references` definitions in your Drizzle schema.","message":"Seeding tables with foreign key relationships requires careful setup. If a foreign key column has a `not-null` constraint and the referenced table is not exposed to the `seed` function or the column generator is not refined, `drizzle-seed` cannot populate the column, leading to errors. TypeScript limitations can also hinder proper inference of relations, especially with circular dependencies.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify your `drizzle.config.ts` casing settings and ensure your Drizzle schema column names precisely match the database, or explicitly define column names in the `refine` callback of `drizzle-seed` to override.","cause":"Drizzle-seed attempted to insert data with a column name from the Drizzle schema that does not match the actual database column name, often due to casing configuration mismatches (e.g., camelCase in schema vs. snake_case in DB).","error":"PostgresError: column \"userTable\" does not exist"},{"fix":"Upgrade `drizzle-seed` to version 0.3.0 or newer. As a temporary workaround for older versions, manually reset the sequence after seeding: `await db.execute(sql`SELECT setval('users_id_seq', (SELECT MAX(id) FROM users));`);`.","cause":"After seeding a table with a `serial` primary key, the PostgreSQL sequence generator was not updated, causing subsequent inserts to attempt to use an already existing ID.","error":"duplicate key value violates unique constraint \"users_pkey\""},{"fix":"Run your TypeScript seed file directly using a runtime like `ts-node`, `bun`, or `node` (after transpilation). Example: `ts-node src/seed.ts`.","cause":"`drizzle-seed` is a library, not a CLI tool. This error occurs when trying to execute it directly via `npx`.","error":"npm error could not determine executable to run"},{"fix":"Ensure all tables involved in a `with` relationship are included in the schema argument of the `seed` function, and that explicit foreign key `references` are correctly defined in your Drizzle schema (e.g., `userId: integer('user_id').references(() => users.id)`).","cause":"Attempting to use the `with` option for related entities in `drizzle-seed` when the foreign key relationship is not correctly defined in the Drizzle schema, or the related tables are not all passed to the `seed` function.","error":"Error: \"posts\" table doesn't have a reference to \"users\" table or you didn't include your one-to-many relation in the seed function schema. You can't specify \"posts\" as parameter in users.with object."}],"ecosystem":"npm"}