Dette burde hjælpe. Her skrev jeg et modul forventet af knex-migrate. Det burde ikke være nogen besvær at tilpasse sig dit behov.
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');