From 4d1e53c396352ac646ace5a39592d51e27782c66 Mon Sep 17 00:00:00 2001 From: Med Kadhem Date: Sun, 5 Jan 2020 14:31:18 +0100 Subject: [PATCH] fixing outdated property names --- bin/makemigration.js | 16 ++-- bin/runmigration.js | 12 +-- lib/migrate.js | 222 +++++++++++++++++++++---------------------- 3 files changed, 125 insertions(+), 125 deletions(-) diff --git a/bin/makemigration.js b/bin/makemigration.js index 046908d..31c09d6 100644 --- a/bin/makemigration.js +++ b/bin/makemigration.js @@ -29,7 +29,7 @@ if (options.help) let alias = (option.alias) ? ` (-${option.alias})` : '\t'; console.log(`\t --${option.name}${alias} \t${option.description}`); }); - process.exit(0); + process.exit(0); } // Windows support @@ -38,7 +38,7 @@ if(!process.env.PWD){ } const { - migrationsDir, + migrationsDir, modelsDir } = pathConfig(options); @@ -56,28 +56,28 @@ if (!fs.existsSync(migrationsDir)) { const currentState = { tables: {} }; - + // load last state let previousState = { revision: 0, version: 1, tables: {} }; - + try { previousState = JSON.parse(fs.readFileSync(path.join(migrationsDir, '_current.json') )); } catch (e) { } //console.log(path.join(migrationsDir, '_current.json'), JSON.parse(fs.readFileSync(path.join(migrationsDir, '_current.json') ))) -let sequelize = require(modelsDir).sequelize; +let sequelize = require(modelsDir).database; let models = sequelize.models; currentState.tables = migrate.reverseModels(sequelize, models); - + let actions = migrate.parseDifference(previousState.tables, currentState.tables); -// sort actions +// sort actions migrate.sortActions(actions); let migration = migrate.getMigration(actions); @@ -110,7 +110,7 @@ currentState.revision = previousState.revision + 1; fs.writeFileSync(path.join(migrationsDir, '_current.json'), JSON.stringify(currentState, null, 4) ); // write migration to file -let info = migrate.writeMigration(currentState.revision, +let info = migrate.writeMigration(currentState.revision, migration, migrationsDir, (options.name) ? options.name : 'noname', diff --git a/bin/runmigration.js b/bin/runmigration.js index 4a54e4e..863ab93 100644 --- a/bin/runmigration.js +++ b/bin/runmigration.js @@ -26,7 +26,7 @@ if(!process.env.PWD){ } let { - migrationsDir, + migrationsDir, modelsDir } = pathConfig(options); @@ -50,7 +50,7 @@ if (options.help) process.exit(0); } -const sequelize = require(modelsDir).sequelize; +const sequelize = require(modelsDir).database; const queryInterface = sequelize.getQueryInterface(); // execute all migration from @@ -76,8 +76,8 @@ let migrationFiles = fs.readdirSync(migrationsDir) let rev = parseInt( path.basename(file).split('-',2)[0]); return (rev >= fromRevision); }); - -console.log("Migrations to execute:"); + +console.log("Migrations to execute:"); migrationFiles.forEach((file) => { console.log("\t"+file); }); @@ -86,13 +86,13 @@ if (options.list) process.exit(0); -Async.eachSeries(migrationFiles, +Async.eachSeries(migrationFiles, function (file, cb) { console.log("Execute migration from file: "+file); migrate.executeMigration(queryInterface, path.join(migrationsDir, file), fromPos, (err) => { if (stop) return cb("Stopped"); - + cb(err); }); // set pos to 0 for next migration diff --git a/lib/migrate.js b/lib/migrate.js index a41fab8..62200fd 100644 --- a/lib/migrate.js +++ b/lib/migrate.js @@ -9,7 +9,7 @@ const path = require("path"); let log = console.log; -const reverseSequelizeColType = function(col, prefix = 'Sequelize.') +const reverseSequelizeColType = function(col, prefix = 'Sequelize.') { const attrName = col['type'].key const attrObj = col.type @@ -60,19 +60,19 @@ const reverseSequelizeColType = function(col, prefix = 'Sequelize.') ret += ', ' + options.scale; ret += ')'; } - + ret = [ ret ]; if (options.zerofill) ret.push('ZEROFILL'); - + if (options.unsigned) ret.push('UNSIGNED'); - - return prefix + ret.join('.'); + + return prefix + ret.join('.'); } - case DataTypes.ENUM.key: + case DataTypes.ENUM.key: return prefix + "ENUM('" +options.values.join("', '")+"')"; case DataTypes.BLOB.key: @@ -104,7 +104,7 @@ const reverseSequelizeColType = function(col, prefix = 'Sequelize.') arrayType = (col.seqType === 'Sequelize.ARRAY(Sequelize.INTEGER)') ? prefix + 'INTEGER' : prefix + 'STRING'; } return prefix + `ARRAY(${arrayType})`; - + case DataTypes.RANGE.key: console.warn(attrName + ' type not supported, you should make it by') return prefix + attrObj.toSql() @@ -126,13 +126,13 @@ const reverseSequelizeColType = function(col, prefix = 'Sequelize.') } }; -const reverseSequelizeDefValueType = function(defaultValue, prefix = 'Sequelize.') -{ +const reverseSequelizeDefValueType = function(defaultValue, prefix = 'Sequelize.') +{ if (typeof defaultValue === 'object') { if (defaultValue.constructor && defaultValue.constructor.name) { return { internal: true, value: prefix + defaultValue.constructor.name }; - } - } + } + } if (typeof defaultValue === 'function') return { notSupported: true, value: '' }; @@ -140,14 +140,14 @@ const reverseSequelizeDefValueType = function(defaultValue, prefix = 'Sequelize. return { value: defaultValue }; }; -const parseIndex = function(idx) +const parseIndex = function(idx) { delete idx.parser; if (idx.type == "") delete idx.type; - + let options = { }; - + if (idx.name) options.name = options.indexName = idx.name; // The name of the index. Default is __ @@ -160,7 +160,7 @@ const parseIndex = function(idx) if (idx.parser && idx.parser != "") options.parser = idx.parser; // For FULLTEXT columns set your parser - + idx.options = options; idx.hash = hash(idx); @@ -172,27 +172,27 @@ const parseIndex = function(idx) const reverseModels = function(sequelize, models) { let tables = {}; - + delete models.default; - + for (let model in models) { - let attributes = models[model].attributes || models[model].rawAttributes; - + let attributes = models[model].attributes || models[model].rawAttributes || models[model].tableAttributes; + for (let column in attributes) { delete attributes[column].Model; delete attributes[column].fieldName; // delete attributes[column].field; - - for(let property in attributes[column]) + + for(let property in attributes[column]) { if(property.startsWith('_')) { delete attributes[column][property]; continue; } - + if (property === 'defaultValue') { let _val = reverseSequelizeDefValueType(attributes[column][property]); @@ -204,15 +204,15 @@ const reverseModels = function(sequelize, models) } attributes[column][property] = _val; } - + // remove getters, setters... if (typeof attributes[column][property] == 'function') delete attributes[column][property]; } - - if(typeof attributes[column]['type'] === 'undefined') + + if(typeof attributes[column]['type'] === 'undefined') { - if(!attributes[column]['seqType']) + if(!attributes[column]['seqType']) { log(`[Not supported] Skip column with undefined type ${model}:${column}`); delete attributes[column]; @@ -227,9 +227,9 @@ const reverseModels = function(sequelize, models) } } } - + let seqType = reverseSequelizeColType(attributes[column]); - + // NO virtual types in migration if (seqType === 'Sequelize.VIRTUAL') { @@ -237,27 +237,27 @@ const reverseModels = function(sequelize, models) delete attributes[column]; continue; } - + if (!seqType) { if(typeof attributes[column]['type']['options'] !== 'undefined' && typeof attributes[column]['type']['options'].toString === 'function') seqType = attributes[column]['type']['options'].toString(sequelize); - - if(typeof attributes[column]['type'].toString === 'function') - seqType = attributes[column]['type'].toString(sequelize); + + if(typeof attributes[column]['type'].toString === 'function') + seqType = attributes[column]['type'].toString(sequelize); } - + attributes[column]['seqType'] = seqType; - + delete attributes[column].type; delete attributes[column].values; // ENUM } - + tables[models[model].tableName] = { tableName: models[model].tableName, schema: attributes }; - + if (models[model].options.indexes.length > 0) { let idx_out = {}; @@ -266,21 +266,21 @@ const reverseModels = function(sequelize, models) let index = parseIndex(models[model].options.indexes[_i]); idx_out[index.hash+''] = index; delete index.hash; - + // make it immutable Object.freeze(index); } models[model].options.indexes = idx_out; } - + if (typeof models[model].options.charset !== 'undefined') { tables[models[model].tableName].charset = models[model].options.charset; } - + tables[models[model].tableName].indexes = models[model].options.indexes; } - + return tables; }; @@ -289,12 +289,12 @@ const parseDifference = function(previousState, currentState) // log(JSON.stringify(currentState, null, 4)); let actions = []; let difference = diff(previousState, currentState); - - for(let _d in difference) + + for(let _d in difference) { let df = difference[_d]; // log (JSON.stringify(df, null, 4)); - switch (df.kind) + switch (df.kind) { // add new case 'N': @@ -307,7 +307,7 @@ const parseDifference = function(previousState, currentState) _.each(df.rhs.schema, (v) => { if ( v.references ) depends.push(v.references.model)}); let options = {}; - if (typeof df.rhs.charset !== 'undefined') + if (typeof df.rhs.charset !== 'undefined') { options.charset = df.rhs.charset; } @@ -319,23 +319,23 @@ const parseDifference = function(previousState, currentState) options: options, depends: depends }); - + // create indexes if (df.rhs.indexes) for(let _i in df.rhs.indexes) { actions.push(_.extend({ - actionType: 'addIndex', + actionType: 'addIndex', tableName: tableName, depends: [ tableName ] }, _.clone(df.rhs.indexes[_i]))); } break; } - + let tableName = df.path[0]; let depends = [tableName]; - + if (df.path[1] === 'schema') { // if (df.path.length === 3) - new field @@ -344,7 +344,7 @@ const parseDifference = function(previousState, currentState) // new field if (df.rhs && df.rhs.references) depends.push(df.rhs.references.model); - + actions.push({ actionType: 'addColumn', tableName: tableName, @@ -354,17 +354,17 @@ const parseDifference = function(previousState, currentState) }); break; } - - // if (df.path.length > 3) - add new attribute to column (change col) + + // if (df.path.length > 3) - add new attribute to column (change col) if (df.path.length > 3) { if (df.path[1] === 'schema') - { + { // new field attributes let options = currentState[tableName].schema[df.path[2]]; if (options.references) depends.push(options.references.nodel); - + actions.push({ actionType: 'changeColumn', tableName: tableName, @@ -374,9 +374,9 @@ const parseDifference = function(previousState, currentState) }); break; } - } + } } - + // new index if (df.path[1] === 'indexes') { @@ -390,13 +390,13 @@ const parseDifference = function(previousState, currentState) } } break; - + // drop case 'D': { let tableName = df.path[0]; let depends = [tableName]; - + if (df.path.length === 1) { // drop table @@ -407,7 +407,7 @@ const parseDifference = function(previousState, currentState) }); break; } - + if (df.path[1] === 'schema') { // if (df.path.length === 3) - drop field @@ -423,15 +423,15 @@ const parseDifference = function(previousState, currentState) }); break; } - - // if (df.path.length > 3) - drop attribute from column (change col) + + // if (df.path.length > 3) - drop attribute from column (change col) if (df.path.length > 3) { // new field attributes let options = currentState[tableName].schema[df.path[2]]; if (options.references) depends.push(options.references.nodel); - + actions.push({ actionType: 'changeColumn', tableName: tableName, @@ -440,9 +440,9 @@ const parseDifference = function(previousState, currentState) depends: depends }); break; - } + } } - + if (df.path[1] === 'indexes') { // log(df) @@ -457,20 +457,20 @@ const parseDifference = function(previousState, currentState) } } break; - + // edit case 'E': { let tableName = df.path[0]; let depends = [tableName]; - + if (df.path[1] === 'schema') { // new field attributes let options = currentState[tableName].schema[df.path[2]]; if (options.references) depends.push(options.references.nodel); - + actions.push({ actionType: 'changeColumn', tableName: tableName, @@ -479,7 +479,7 @@ const parseDifference = function(previousState, currentState) depends: depends }); } - + // updated index // only support updating and dropping indexes if (df.path[1] === 'indexes') @@ -517,7 +517,7 @@ const parseDifference = function(previousState, currentState) } break; - + // array change indexes case 'A': { @@ -526,7 +526,7 @@ const parseDifference = function(previousState, currentState) log(JSON.stringify(df, null, 4)); } break; - + default: // code break; @@ -550,31 +550,31 @@ const sortActions = function(actions) { const orderedActionTypes = [ 'removeIndex', - 'removeColumn', + 'removeColumn', 'dropTable', 'createTable', 'addColumn', 'changeColumn', 'addIndex' ]; - + //test //actions = shuffleArray(actions); - + actions.sort((a, b) => { if (orderedActionTypes.indexOf(a.actionType) < orderedActionTypes.indexOf(b.actionType)) return -1; if (orderedActionTypes.indexOf(a.actionType) > orderedActionTypes.indexOf(b.actionType)) - return 1; - + return 1; + if (a.depends.length === 0 && b.depends.length > 0) return -1; // a < b if (b.depends.length === 0 && a.depends.length > 0) return 1; // b < a - - return 0; - }); - + + return 0; + }); + for (let k = 0; k <= actions.length ; k++) for (let i = 0; i < actions.length ; i++) { @@ -582,34 +582,34 @@ const sortActions = function(actions) continue; if (actions[i].depends.length === 0) continue; - + let a = actions[i]; - + for (let j = 0; j < actions.length; j++) { if (!actions[j].depends) continue; if (actions[j].depends.length === 0) - continue; - + continue; + let b = actions[j]; - + if (a.actionType != b.actionType) continue; - + if (b.depends.indexOf(a.tableName) !== -1 && i > j) { let c = actions[i]; actions[i] = actions[j]; actions[j] = c; } - + } } }; -const getMigration = function(actions) +const getMigration = function(actions) { let propertyToStr = (obj) => { let vals = []; @@ -620,7 +620,7 @@ const getMigration = function(actions) vals.push('"type": '+obj[k]); continue; } - + if (k === 'defaultValue') { if (obj[k].internal) @@ -636,15 +636,15 @@ const getMigration = function(actions) vals.push(JSON.stringify(x).slice(1, -1)); continue; } - + let x = {}; x[k] = obj[k]; vals.push(JSON.stringify(x).slice(1, -1)); } - + return '{ ' + vals.reverse().join(', ') + ' }'; }; - + let getAttributes = (attrs) => { let ret = []; for (let attrName in attrs) @@ -656,11 +656,11 @@ const getMigration = function(actions) let commandsUp = []; let consoleOut = []; - + for (let _i in actions) { let action = actions[_i]; - switch (action.actionType) + switch (action.actionType) { case 'createTable': { @@ -670,7 +670,7 @@ let resUp =`{ fn: "createTable", params: [ ${JSON.stringify(action.options)} ] }`; commandsUp.push(resUp); - + consoleOut.push(`createTable "${action.tableName}", deps: [${action.depends.join(', ')}]`); } break; @@ -679,11 +679,11 @@ let resUp =`{ fn: "createTable", params: [ { let res = `{ fn: "dropTable", params: ["${action.tableName}"] }`; commandsUp.push(res); - + consoleOut.push(`dropTable "${action.tableName}"`); } break; - + case 'addColumn': { let resUp = `{ fn: "addColumn", params: [ @@ -702,11 +702,11 @@ let resUp = `{ fn: "addColumn", params: [ { let res = `{ fn: "removeColumn", params: ["${action.tableName}", "${(action.options && action.options.field) ? action.options.field : action.columnName}"] }`; commandsUp.push(res); - + consoleOut.push(`removeColumn "${(action.options && action.options.field) ? action.options.field : action.columnName}" from table "${action.tableName}"`); } break; - + case 'changeColumn': { let res = `{ fn: "changeColumn", params: [ @@ -715,11 +715,11 @@ let res = `{ fn: "changeColumn", params: [ ${propertyToStr(action.options)} ] }`; commandsUp.push(res); - + consoleOut.push(`changeColumn "${action.attributeName}" on table "${action.tableName}"`); } break; - + case 'addIndex': { let res = `{ fn: "addIndex", params: [ @@ -728,26 +728,26 @@ let res = `{ fn: "addIndex", params: [ ${JSON.stringify(action.options)} ] }`; commandsUp.push(res); - + let nameOrAttrs = (action.options && action.options.indexName && action.options.indexName != '') ? `"${action.options.indexName}"` : JSON.stringify(action.fields); consoleOut.push(`addIndex ${nameOrAttrs} to table "${action.tableName}"`); } break; - + case 'removeIndex': { // log(action) let nameOrAttrs = (action.options && action.options.indexName && action.options.indexName != '') ? `"${action.options.indexName}"` : JSON.stringify(action.fields); - + let res = `{ fn: "removeIndex", params: [ "${action.tableName}", ${nameOrAttrs} ] }`; commandsUp.push(res); - + consoleOut.push(`removeIndex ${nameOrAttrs} from table "${action.tableName}"`); } - + default: // code } @@ -761,7 +761,7 @@ const writeMigration = function(revision, migration, migrationsDir, name = '', c { let _commands = "var migrationCommands = [ \n" + migration.commandsUp.join(", \n") +' \n];\n'; let _actions = ' * ' + migration.consoleOut.join("\n * "); - + _commands = beautify(_commands); let info = { revision, @@ -769,7 +769,7 @@ const writeMigration = function(revision, migration, migrationsDir, name = '', c created: new Date(), comment }; - + let template = `'use strict'; var Sequelize = require('sequelize'); @@ -813,27 +813,27 @@ module.exports = { let filename = path.join(migrationsDir, revision + ((name != '') ? `-${name}` : '') + '.js'); fs.writeFileSync(filename, template); - + return {filename, info}; }; const executeMigration = function(queryInterface, filename, pos, cb) { let mig = require(filename); - + if (!mig) return cb("Can't require file "+filename); - + if (pos > 0) { console.log("Set position to "+pos); mig.pos = pos; } - + mig.up(queryInterface, Sequelize).then( () => { cb(); - }, + }, (err) => { cb(err); }