不要怂,就是干,撸起袖子干!

sequelize 3.29 KB
#!/usr/bin/env node

const path      = require("path")
    , fs        = require("fs")
    , program   = require("commander")
    , Sequelize = require(__dirname + '/../index')
    , _         = Sequelize.Utils._

var configPath       = process.cwd() + '/config'
  , migrationsPath   = process.cwd() + '/migrations'
  , configFile       = configPath + '/config.json'
  , configPathExists = path.existsSync(configPath)
  , configFileExists = path.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 {
    return JSON.parse(fs.readFileSync(configFile))
  } catch(e) {
    throw new Error('The config.json is not available or contains invalid JSON.')
  }
}

program
  .version('1.3.0')
  .option('-i, --init', 'Initializes the project. Creates a config/config.json')
  .option('-m, --migrate', 'Runs undone migrations')
  .option('-u, --undo', 'Redo the last migration.')
  .option('-f, --force', 'Forces the action to be done.')
  .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.findOrCreateSequelizeMetaModel().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({
      username: "root",
      password: null,
      database: 'database',
      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 {
  console.log('Please define any params!')
}