Data factories

Is there a good way to add a data factory to Drizzle, so that I can add new users quickly for testing etc. (Ideally with being able to pass through relationship data as well).
1 Reply
Angelelz
Angelelz16mo ago
There is no seeding helper from drizzle. You have to create your own script to seed your database however you please I have a seed.ts file in my drizzle/ folder and it looks like this:
dotenv.config();

const { hash } = pkg;

// create the connection
const poolConnection = mysql.createPool({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
database: process.env.DATABASE_NAME,
password: process.env.DATABASE_PASSWORD,
timezone: "+00:00"
});
console.log(process.env.DATABASE_PASSWORD);

const db = drizzle(poolConnection, { schema, logger: true });
const COMPANY_NAME = "Test Company";
const USERS: NewUser[] = [
{
id: generateId(),
username: "userOwner",
firstName: "Fname",
lastName: "Lname",
password: await hash("fname", 12),
role: "owner"
},
...
];
await db.insert(company).values({name: COMPANY_NAME, id: generateId()});
await db.insert(users).values(USERS);
...
dotenv.config();

const { hash } = pkg;

// create the connection
const poolConnection = mysql.createPool({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
database: process.env.DATABASE_NAME,
password: process.env.DATABASE_PASSWORD,
timezone: "+00:00"
});
console.log(process.env.DATABASE_PASSWORD);

const db = drizzle(poolConnection, { schema, logger: true });
const COMPANY_NAME = "Test Company";
const USERS: NewUser[] = [
{
id: generateId(),
username: "userOwner",
firstName: "Fname",
lastName: "Lname",
password: await hash("fname", 12),
role: "owner"
},
...
];
await db.insert(company).values({name: COMPANY_NAME, id: generateId()});
await db.insert(users).values(USERS);
...
I have this entry in my package.json: "seed": "pnpm with-env ts-node --esm drizzle/run-seed.ts" And then I just run it with pnpm seed
Want results from more Discord servers?
Add your server