Database Seeding
Seeding allows you to populate your database with initial data effectively. The Prisma PHP package includes a default template at prisma/seed.ts.
Prerequisite: Generate Client
Before running the seed script, you must generate the Prisma Client. The seed file relies on the generated client definitions to interact with your database.
npx prisma generate
1. Setup Connection Adapter
Copy the connection code that corresponds to your database provider. Paste this at the top of your seed.ts file.
Option A: SQLite
import { PrismaClient } from "@prisma/client";
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL!,
});
const prisma = new PrismaClient({ adapter });
Option B: PostgreSQL
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
const connectionString = process.env.DATABASE_URL!;
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
Option C: MySQL / MariaDB
import { PrismaClient } from "@prisma/client";
import { PrismaMariaDb } from "@prisma/adapter-mariadb";
import { createPool } from "mariadb";
const connectionUrl = new URL(process.env.DATABASE_URL!);
const pool = createPool({
host: connectionUrl.hostname,
port: Number(connectionUrl.port) || 3306,
user: connectionUrl.username,
password: connectionUrl.password,
database: connectionUrl.pathname.slice(1),
connectionLimit: 5,
});
const adapter = new PrismaMariaDb(pool);
const prisma = new PrismaClient({ adapter });
2. Data & Execution Logic
Paste this code below your connection configuration. This handles defining the data and running the seed transaction.
// ============================================================
// DATA DEFINITION
// ============================================================
const userRoleData = [
{ id: 1, name: "Admin" },
{ id: 2, name: "User" },
];
const userData = [
{
name: "Juan",
email: "j@gmail.com",
password: "$2b$10$mgjotYzIXwrK1MCWmu4tgeUVnLcb.qzvqwxOq4FXEL8k2obwXivDi", // bcrypt: 1234
roleId: 1,
},
];
// ============================================================
// EXECUTION LOGIC
// ============================================================
async function main() {
console.log(`Start seeding ...`);
// 1. Clean up existing data (Optional)
// await prisma.user.deleteMany();
// await prisma.userRole.deleteMany();
// 2. Reset Auto-Increment (Optional - DB Specific)
// PostgreSQL:
// await prisma.$executeRaw`ALTER SEQUENCE "UserRole_id_seq" RESTART WITH 1`;
// MySQL:
// await prisma.$executeRaw`ALTER TABLE UserRole AUTO_INCREMENT = 1`;
// 3. Insert Data
await prisma.userRole.createMany({ data: userRoleData });
await prisma.user.createMany({ data: userData });
console.log(`Seeding finished.`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});