76 lines
1.8 KiB
JavaScript
Raw Normal View History

2021-09-20 19:15:50 +02:00
'use strict';
const path = require('path');
const fse = require('fs-extra');
2022-05-09 14:35:48 +02:00
const { Umzug } = require('umzug');
2021-09-20 19:15:50 +02:00
const createStorage = require('./storage');
2022-05-09 14:35:48 +02:00
const wrapTransaction = db => fn => () =>
db.getConnection().transaction(trx => Promise.resolve(fn(trx)));
2021-09-20 19:15:50 +02:00
// TODO: check multiple commands in one sql statement
2022-05-09 14:35:48 +02:00
const migrationResolver = ({ name, path, context }) => {
2022-05-14 09:23:20 +02:00
const { db } = context;
2021-09-20 19:15:50 +02:00
// if sql file run with knex raw
if (path.match(/\.sql$/)) {
const sql = fse.readFileSync(path, 'utf8');
return {
2022-05-09 14:35:48 +02:00
name,
2022-05-14 09:23:20 +02:00
up: wrapTransaction(db)(knex => knex.raw(sql)),
2021-09-20 19:15:50 +02:00
down() {},
};
}
// NOTE: we can add some ts register if we want to handle ts migration files at some point
2022-05-09 14:35:48 +02:00
const migration = require(path);
return {
name,
2022-05-14 09:23:20 +02:00
up: wrapTransaction(db)(migration.up),
down: wrapTransaction(db)(migration.down),
2022-05-09 14:35:48 +02:00
};
2021-09-20 19:15:50 +02:00
};
const createUmzugProvider = db => {
2021-09-21 15:32:49 +02:00
const migrationDir = path.join(strapi.dirs.root, 'database/migrations');
2021-09-20 19:15:50 +02:00
fse.ensureDirSync(migrationDir);
return new Umzug({
2022-05-09 14:35:48 +02:00
storage: createStorage({ db, tableName: 'strapi_migrations' }),
context: { db },
2021-09-20 19:15:50 +02:00
migrations: {
2022-05-14 09:23:20 +02:00
glob: ['*.{js,sql}', { cwd: migrationDir }],
2022-05-09 14:35:48 +02:00
resolve: migrationResolver,
2021-09-20 19:15:50 +02:00
},
});
};
// NOTE: when needed => add internal migrations for core & plugins. How do we overlap them with users migrations ?
/**
* Creates migrations provider
* @type {import('.').createMigrationsProvider}
*/
const createMigrationsProvider = db => {
const migrations = createUmzugProvider(db);
return {
async shouldRun() {
const pending = await migrations.pending();
return pending.length > 0;
},
async up() {
await migrations.up();
},
async down() {
await migrations.down();
},
};
};
module.exports = { createMigrationsProvider };