|
1 | 1 | const MSTATE = '__dbmigrate_state__';
|
2 | 2 | const SSTATE = '__dbmigrate_schema__';
|
3 | 3 | const log = require('db-migrate-shared').log;
|
| 4 | +const fs = require('fs').promises; |
| 5 | +const path = require('path'); |
4 | 6 |
|
5 | 7 | module.exports = {
|
6 | 8 | lockState: async function (driver, state, internals) {
|
@@ -29,9 +31,26 @@ module.exports = {
|
29 | 31 | }
|
30 | 32 | },
|
31 | 33 |
|
32 |
| - init: async function (driver, internals, { emptyState }) { |
| 34 | + init: async function (driver, internals, { emptyState, backupState }) { |
33 | 35 | await driver._createKV(internals.migrationState);
|
34 |
| - const schema = emptyState !== true ? await driver._getKV(internals.migrationState, SSTATE) : null; |
| 36 | + const _schema = await driver._getKV(internals.migrationState, SSTATE); |
| 37 | + |
| 38 | + if (_schema && backupState) { |
| 39 | + const newName = `${internals.migrationState}_b_${Math.floor((new Date() - 0) / 1000)}`; |
| 40 | + log.info(`[state] Created a backup of ${internals.migrationState} by writing to file ${newName}.dbmigrate`); |
| 41 | + |
| 42 | + await fs.writeFile(path.resolve(`${newName}.dbmigrate`), JSON.stringify(_schema), 'utf8'); |
| 43 | + |
| 44 | + if (emptyState) { |
| 45 | + await driver.renameTable(internals.migrationState, |
| 46 | + newName); |
| 47 | + |
| 48 | + log.info(`[state] Created a backup of ${internals.migrationState} by renaming table to ${newName}`); |
| 49 | + await driver._createKV(internals.migrationState); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + const schema = emptyState !== true ? _schema : null; |
35 | 54 | if (schema) {
|
36 | 55 | internals.schema = JSON.parse(schema.value);
|
37 | 56 | } else if (!emptyState) {
|
|
0 commit comments