Mysql
 sql >> Datenbank >  >> RDS >> Mysql

So erstellen Sie eine gespeicherte Prozedur in MySQL mit Knex Raw

Dies sollte helfen. Hier habe ich ein von knex-migrate erwartetes Modul geschrieben. Es sollte kein Problem sein, sich an Ihre Bedürfnisse anzupassen.

const mysql = require('mysql2');

const {
  database: {
    connection: {
      host, user, password, database, port
    }
  }
} = require('./settings.js');

exports.up = async () => {
  const script = `
    CREATE DEFINER=\`<YOUR_DB_USER>\`@\`%\` PROCEDURE \`fill_date_dimension\`(IN startdate DATE,IN stopdate DATE)
    BEGIN
        DECLARE currentdate DATE;
        SET currentdate = startdate;
        WHILE currentdate < stopdate DO
        INSERT INTO time_dimension VALUES (
                        YEAR(currentdate)*10000+MONTH(currentdate)*100 + DAY(currentdate),
                        currentdate,
                        YEAR(currentdate),
                        MONTH(currentdate),
                        DAY(currentdate),
                        QUARTER(currentdate),
                        WEEKOFYEAR(currentdate),
                        DATE_FORMAT(currentdate,'%W'),
                        DATE_FORMAT(currentdate,'%M'),
                        'f',
                        CASE DAYOFWEEK(currentdate) WHEN 1 THEN 't' WHEN 7 then 't' ELSE 'f' END,
                        NULL);
        SET currentdate = ADDDATE(currentdate,INTERVAL 1 DAY);
        END WHILE;
    END`

  const connection = mysql.createConnection({
    host,
    user,
    database,
    password,
    port
  });

  return new Promise(function (resolve, reject) {
    connection.query(
      script,
      function (err) {
        if (err) {
          return reject(err);
        }

        return resolve();
      }
    );
  });
};

exports.down = async knex => knex.raw('DROP PROCEDURE IF EXISTS fill_date_dimension');