Skip to content
Fetching contributors…
Cannot retrieve contributors at this time
executable file 161 lines (138 sloc) 4.59 KB
#!/usr/bin/env node
const path = require("path")
, fs = require("fs")
, program = require("commander")
, Sequelize = require(__dirname + '/../index')
, moment = require("moment")
, _ = Sequelize.Utils._
var configPath = process.cwd() + '/config'
, migrationsPath = process.cwd() + '/migrations'
, packageJsonPath = __dirname + '/../package.json'
, packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString())
, configFile = configPath + '/config.json'
, configPathExists = fs.existsSync(configPath)
, configFileExists = fs.existsSync(configFile)
var writeConfig = function(config) {
!configPathExists && fs.mkdirSync(configPath)
config = JSON.stringify(config)
config = config.replace('{', '{\n ')
config = config.replace(/,/g, ",\n ")
config = config.replace('}', "\n}")
fs.writeFileSync(configFile, config)
}
var createMigrationsFolder = function(force) {
if(force) {
console.log('Deleting the migrations folder.')
try {
fs.readdirSync(migrationsPath).forEach(function(filename) {
fs.unlinkSync(migrationsPath + '/' + filename)
})
} catch(e) {}
try {
fs.rmdirSync(migrationsPath)
console.log('Successfully deleted the migrations folder.')
} catch(e) {}
}
console.log('Creating migrations folder.')
try {
fs.mkdirSync(migrationsPath)
console.log('Successfully create migrations folder.')
} catch(e) {
console.log('Migrations folder already exist.')
}
}
var readConfig = function() {
try {
var config = JSON.parse(fs.readFileSync(configFile))
, env = process.env.NODE_ENV || 'development'
if (config[env]) {
config = config[env]
}
return config
} catch(e) {
throw new Error('The config.json is not available or contains invalid JSON.')
}
}
program
.version(packageJson.version)
.option('-i, --init', 'Initializes the project. Creates a config/config.json')
.option('-m, --migrate', 'Runs undone migrations')
.option('-u, --undo', 'Undo the last migration.')
.option('-f, --force', 'Forces the action to be done.')
.option('-c, --create-migration [migration-name]', 'Create a new migration skeleton file.')
.parse(process.argv)
if(program.migrate) {
if(configFileExists) {
var config = readConfig()
, options = {}
_.each(config, function(value, key) {
if(['database', 'username', 'password'].indexOf(key) == -1) {
options[key] = value
}
})
options = _.extend(options, { logging: false })
var sequelize = new Sequelize(config.database, config.username, config.password, options)
, migratorOptions = { path: migrationsPath }
, migrator = sequelize.getMigrator(migratorOptions)
if(program.undo) {
sequelize.migrator.findOrCreateSequelizeMetaDAO().success(function(Meta) {
Meta.find({ order: 'id DESC' }).success(function(meta) {
if(meta) {
migrator = sequelize.getMigrator(_.extend(migratorOptions, meta), true)
}
migrator.migrate({ method: 'down' })
})
})
} else {
sequelize.migrate()
}
} else {
throw new Error('Please add a configuration file under config/config.json. You might run "sequelize --init".')
}
} else if(program.init) {
if(!configFileExists || !!program.force) {
writeConfig({
development: {
username: "root",
password: null,
database: 'database_development',
host: '127.0.0.1'
},
test: {
username: "root",
password: null,
database: 'database_test',
host: '127.0.0.1'
},
production: {
username: "root",
password: null,
database: 'database_production',
host: '127.0.0.1'
}
})
console.log('Successfully created config.json')
} else {
console.log('A config.json already exists. Run "sequelize --init --force" to overwrite it.')
}
createMigrationsFolder(program.force)
} else if(program.createMigration) {
createMigrationsFolder()
var migrationName = [
moment().format('YYYYMMDDHHmmss'),
(typeof program.createMigration == 'string') ? program.createMigration : 'unnamed-migration'
].join('-') + '.js'
var migrationContent = [
"module.exports = {",
" up: function(migration, DataTypes) {",
" // add altering commands here",
" },",
" down: function(migration) {",
" // add reverting commands here",
" }",
"}"
].join('\n')
fs.writeFileSync(migrationsPath + '/' + migrationName, migrationContent)
} else {
console.log('Please define any params!')
}
Something went wrong with that request. Please try again.