npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

prisma-seeder-custom

v0.2.5

Published

A CLI tool to generate Prisma seed files automatically.

Downloads

509

Readme

Prisma Seeder Custom

A command line tool to generate and manage seed files in Prisma projects. It facilitates the creation and management of initial or example data in your database, ensuring efficient management and avoiding duplication.


Characteristics

  • Automatic generation of seed files:

    • Automate the creation of seed scripts for your models in Prisma.
    • The files are generated with unique and ordered names, using the current date as a prefix.
  • Prevention of duplicates:

    • Avoid re-executing previously applied seeds by logging each execution in the SeedExecution table.
  • Seed reversal: Removes the data inserted by the seeds in the reverse order of their execution.

  • Migration support:

    • Integrates the creation and execution of seeds within the Prisma migration flow.

Installation

Install this tool with npm:

npm install prisma-seeder-custom

Initial setup

Before you begin, be sure to follow these steps to set up your project:

  1. Define the SeedExecution model in your schema.prisma file Add the following model to your schema.prisma file to record the executed seeds:
model SeedExecution {
  id         Int      @id @default(autoincrement())
  seedName   String   @unique
  executedAt DateTime @default(now())
}
  1. Apply changes to the database schema
npx prisma migrate dev --name add-seed-execution-model

Uso

1. Generate a seed file

Run the following command to generate a seed file:

npx prisma-seeder-custom generate <model_name>

-<model_name>: Name of the model in your schema.prisma file (for example: User, Post, etc.).

-The tool will generate a file in the prisma/seeders directory with a name like 01_ModelName.js.

Example:

npx prisma-seeder-custom generate user

This will generate a prisma/seeders/01_User.js file with the following basic structure:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export async function main() {
  const user = await prisma.user.upsert({
    where: { id: 1 }, // Change depending on the model
    update: {},
    create: {
      name: 'Example Name',
      email: '[email protected]',
      posts: {
        create: [
          {
            title: 'First Post',
            content: 'Content of the first post',
            published: true,
          },
        ],
      },
    },
  });
  console.log('user: ',user)
  console.log('✅ Data successfully inserted into user');
}

export async function down() {
  try {
    const deleted = await prisma.user.deleteMany({
      where: {
        email: '[email protected]', // Condition that identifies the data created by the seed
      },
    });
    console.log(`↩️ Rollback completed: ${deleted.count} records deleted.`);
  } catch (e) {
    console.error('❌ Error while performing rollback:', e.message);
    throw e;
  }
}
;

2. Run seeds

To run all the seeds in the prisma/seeders directory, use:

npx prisma-seeder-custom run

This will do the following:

  1. It will check if the 'SeedExecution' table exists. If not, it will offer to create it automatically.
  2. Will skip seeds that have already been registered in the 'SeedExecution' table.
  3. It will run the seed scripts in ascending order based on their file name.
  4. It will record each successfully executed seed in the 'SeedExecution' table.

Output example:

📁 Seeds folder: /project/prisma/seeders
🗂️ Sorted seed files: [ '20241027163726_User.js', '20241027163729_Post.js' ]
⚙️ Loading and running module from: /project/prisma/seeders/01_User.js
✅ Seed "01_User.js" executed successfully.
⚙️ Loading and running module from: /project/prisma/seeders/02_Post.js
✅ Seed "02_Post.js" executed successfully.
✅ Seeds executed correctly.

3. Reverse seeds

To revert all executed seeds, use:

npx prisma-seeder-custom rollback

Details about the rollback:

The seeds are reverted in the reverse order of their execution.

If a seed has dependencies, these must be handled manually in the seed file's down function, or you can configure onDelete: Cascade in your Prisma schema.

Example of a 'down' function in a seed file:

export async function down() {
  try {
    const deleted = await prisma.user.deleteMany({
      where: {
        email: '[email protected]', // Condition that identifies the data created by the seed
      },
    });
    console.log(`↩️ Rollback completado: ${deleted.count} registros eliminados.`);
  } catch (e) {
    console.error('❌ Error al realizar el rollback:', e.message);
    throw e;
  }
}

Contributions

If you have ideas to improve this tool, contribute to the repository on GitHub! I would appreciate your collaboration.

License

This project is licensed under the MIT License.