最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to programatically run sequelize seeders? - Stack Overflow

programmeradmin0浏览0评论

I am new to NodeJS and Sequelize and am trying to execute the sequelize seeders on project startup.

Here is an example of one of my seed functions.

filePath: src/database/seeders/20220402125658-default-filters.js

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.bulkInsert('Filters', [
      {
        id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()
        name: 'Amount Filter',
        maxAmount: 200.0,
        minAmount: 0.2,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);
  },
};

In my index.js file I am executing sequelize.sync() which synchronizes my database model. This is working great, but I want to also execute the seed code above when the sync is plete.

filePath: src/database/index.js

db.sequelize.sync().then(() => {
// execute seeders here ...
});

Do you have any idea how can I do that ? The seeding is working correctly when I use it through npx mand: npx sequelize-cli db:seed:all, but I want to do it automatically on project start.

I am new to NodeJS and Sequelize and am trying to execute the sequelize seeders on project startup.

Here is an example of one of my seed functions.

filePath: src/database/seeders/20220402125658-default-filters.js

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.bulkInsert('Filters', [
      {
        id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()
        name: 'Amount Filter',
        maxAmount: 200.0,
        minAmount: 0.2,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);
  },
};

In my index.js file I am executing sequelize.sync() which synchronizes my database model. This is working great, but I want to also execute the seed code above when the sync is plete.

filePath: src/database/index.js

db.sequelize.sync().then(() => {
// execute seeders here ...
});

Do you have any idea how can I do that ? The seeding is working correctly when I use it through npx mand: npx sequelize-cli db:seed:all, but I want to do it automatically on project start.

Share Improve this question asked Apr 3, 2022 at 22:36 Dobromir IvanovDobromir Ivanov 4397 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

A simple approach may be to write a script that runs the migrations/seeds via the Sequelize CLI and add in your package.json a start script that calls it, e.g. ./run-migrations.sh && node . (or maybe just sequelize-cli db:migrate && sequelize-cli db:seed:all && node .). Then just run npm run start to start the application.


Otherwise, from the looks of it, Sequelize has the umzug library for programmatically applying migrations/seeds. See the ment in this issue for how you might do this.

I'll copy the code here in case it's lost:

/* <PROJECT_ROOT>/migrations.js */
var Umzug = require("umzug");
var models = require("./models");

var migrationsConfig = {
  storage: "sequelize",
  storageOptions: {
    sequelize: models.sequelize
    // modelName: 'SequelizeMeta' // No need to specify, because this is default behaviour
  },
  migrations: {
    params: [
      models.sequelize.getQueryInterface(),
      models.sequelize.constructor
    ],
    path: "./migrations", // path to folder containing migrations
    pattern: /\.js$/
  }
};

var seedsConfig = {
  storage: "sequelize",
  storageOptions: {
    sequelize: models.sequelize,
    modelName: 'SequelizeData' // Or whatever you want to name the seeder storage table
  },
  migrations: {
    params: [
      models.sequelize.getQueryInterface(),
      models.sequelize.constructor
    ],
    path: "./seeds", // path to folder containing seeds
    pattern: /\.js$/
  }
};

var migrator = new Umzug(migrationsConfig);
var seeder = new Umzug(seedsConfig);

module.exports = () => migrator.up().then(() => seeder.up());

/* <PROJECT_ROOT>/index.js */
var migrations = require("./migrations");

// Run migrations & seeds
migrations().then(function() {
  console.log("Migrations pleted");
});

Here is an example that puts data in database. Postgres:15.6, Sequelize 6, Umzug.

Sequelize and Umzug setup:

// db.ts
import {Sequelize} from 'sequelize';

import {DB} from '../types/db';
import pg from 'pg';
import ClickhouseStatisticsModel from './models/ClickhouseStatistics.model';
import VisitedUsersModel from './models/VisitedUsers.model';
import ExampleModel from './models/Example.model';
import SharedStatesModel from './models/SharedStates.model';
import ClickhouseCacheModel from './models/ClickhouseCache.model';
import SharedLogsModel from './models/SharedLogs.model';
import {Umzug, SequelizeStorage} from 'umzug';

const sequelize: Sequelize = new Sequelize(
  process.env.DB_NAME as string,
  process.env.DB_USERNAME as string,
  process.env.DB_PASSWORD as string,
  {
    host: process.env.DB_HOSTNAME,
    port: Number(process.env.DB_PORT),
    dialect: 'postgres',
    dialectModule: pg,
    ssl: true,
    dialectOptions: process.env.DB_SSL === 'false' ? {} : {ssl: {require: true}},
    // logging: (msg: string) => console.log(msg),
    logging: false,
    define: {
      freezeTableName: true,
    },
  },
);

const db: DB = {
  sequelize,
  models: {
    clickhouseStatistics: ClickhouseStatisticsModel(sequelize),
    clickhouseCache: ClickhouseCacheModel(sequelize),
    visitedUser: VisitedUsersModel(sequelize),
    example: ExampleModel(sequelize),
    sharedStates: SharedStatesModel(sequelize),
    sharedLogs: SharedLogsModel(sequelize),
  },
};

const umzug: Umzug = new Umzug({
  migrations: {glob: ['migrations/*.{js,ts}', {cwd: __dirname}]},
  context: sequelize.getQueryInterface(),
  storage: new SequelizeStorage({sequelize}),
  logger: console,
});

export {db, umzug};

Migration file:

// 20_add_data.ts
import {Migration, MigrationParams} from '../../../types/db.migrations';
import {SharedLogRecord} from '../../../types/db';
import fs from 'fs';

type SharedLogRecordFromSqlite = SharedLogRecord & {
  updatedAt: string;
  deletedAt: string;
};

export const up: Migration = async ({context: queryInterface}: MigrationParams) => {
  // 20_shared_logs.json
  const data: SharedLogRecordFromSqlite[] = JSON.parse(
      fs.readFileSync(__dirname + '/20_shared_logs.json', 'utf8'),
  );

  let maxId: number = 0;
  data.forEach((record: SharedLogRecordFromSqlite) => {
    delete record.updatedAt;
    delete record.deletedAt;

    if (record.id > maxId) maxId = record.id;
  });
  maxId++;

  await queryInterface.bulkInsert('SharedLogs', data);

  // https://stackoverflow./a/78306713/10099510
  await queryInterface.sequelize.query(`ALTER SEQUENCE "SharedLogs_id_seq" RESTART WITH ${maxId};`);
};

export const down: Migration = async () => {};

module.exports = {up, down};
发布评论

评论列表(0)

  1. 暂无评论