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

Commit 24ab2003 by Sascha Depold

Remove the CLI

1 parent bc017654
# Sequelize
# Sequelize
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sequelize/sequelize/trend.png)](https://bitdeli.com/free "Bitdeli Badge") [![Build Status](https://secure.travis-ci.org/sequelize/sequelize.png)](http://travis-ci.org/sequelize/sequelize) [![Dependency Status](https://david-dm.org/sequelize/sequelize.png)](https://david-dm.org/sequelize/sequelize) [![Coverage Status](https://img.shields.io/coveralls/sequelize/sequelize.svg)](https://coveralls.io/r/sequelize/sequelize?branch=master)[![Flattr this](http://api.flattr.com/button/flattr-badge-large.png)](http://flattr.com/thing/1259407/Sequelize) #
......@@ -24,6 +24,7 @@ To install 2.x.x branch - which has a unstable API and will break backwards comp
- Hooks/callbacks/lifecycle events
- Prefetching/association including
- Transactions
- CLI ([sequelize-cli](https://github.com/sequelize/cli))
### Resources
- [Changelog](https://github.com/sequelize/sequelize/blob/master/changelog.md)
......
#!/usr/bin/env node
var path = require("path")
, fs = require("fs")
, program = require("commander")
, Sequelize = require(__dirname + '/../index')
, moment = require("moment")
, _ = Sequelize.Utils._
, url = require("url")
, supportsCoffee
var configuration = {
configFile: process.cwd() + '/config/config.json',
environment: process.env.NODE_ENV || 'development',
version: require(__dirname + '/../package.json').version,
migrationsPath: process.cwd() + '/migrations'
}
var loadDefaultOptions = function(pathToOptionsFile) {
try {
var options = require(pathToOptionsFile);
Object.keys(options).forEach(function(key) {
program[key] = options[key]
})
} catch(e) {
console.log(e);
throw new Error('Error reading "' + pathToOptionsFile + '".')
}
}
var configFileExists = function() {
return fs.existsSync(configuration.configFile)
}
var relativeConfigFile = function() {
return path.relative(process.cwd(), configuration.configFile)
}
// Taken from
// http://stackoverflow.com/questions/15375544/how-can-i-robustly-detect-a-relative-path-in-node-js/17521358#17521358
var isRelativePath = function(p) {
var normal = path.normalize(p)
, absolute = path.resolve(p);
return normal != absolute;
}
var writeDefaultConfig = function(config) {
var configPath = path.dirname(configuration.configFile)
if (!fs.existsSync(configPath)) {
fs.mkdirSync(configPath)
}
config = JSON.stringify({
development: {
username: "root",
password: null,
database: 'database_development',
host: '127.0.0.1',
dialect: 'mysql'
},
test: {
username: "root",
password: null,
database: 'database_test',
host: '127.0.0.1',
dialect: 'mysql'
},
production: {
username: "root",
password: null,
database: 'database_production',
host: '127.0.0.1',
dialect: 'mysql'
}
}, undefined, 2) + "\n"
fs.writeFileSync(configuration.configFile, config)
}
var createMigrationsFolder = function(force) {
if(force) {
console.log('Deleting the migrations folder. (--force)')
try {
fs.readdirSync(configuration.migrationsPath).forEach(function(filename) {
fs.unlinkSync(configuration.migrationsPath + '/' + filename)
})
} catch(e) {}
try {
fs.rmdirSync(configuration.migrationsPath)
console.log('Successfully deleted the migrations folder.')
} catch(e) {}
}
try {
mkdirp(configuration.migrationsPath)
console.log('Successfully created migrations folder at "' + configuration.migrationsPath + '".')
} catch(e) {
}
}
var mkdirp = function (path, root) {
var dirs = path.split('/')
, dir = dirs.shift()
, root = (root || '') + dir + '/'
try {
fs.mkdirSync(root)
} catch (e) {
// dir wasn't made, something went wrong
if (!fs.statSync(root).isDirectory()) {
throw new Error(e)
}
}
return !dirs.length || mkdirp(dirs.join('/'), root)
}
var parseDbUrl = function(urlString) {
var urlParts,
config = {};
try {
urlParts = url.parse(urlString)
config.database = urlParts.path.replace(/^\//, '');
config.dialect = urlParts.protocol;
config.dialect = config.dialect.replace(/:$/, '');
config.host = urlParts.hostname;
config.port = urlParts.port;
if (config.dialect === 'sqlite') {
config.storage = '/' + config.database;
}
if (urlParts.auth) {
config.username = urlParts.auth.split(':')[0]
config.password = urlParts.auth.split(':')[1]
}
} catch (e) {
throw new Error('Error parsing url: ' + url);
}
return config
};
var readConfig = function() {
var config
if (program.url) {
config = parseDbUrl(program.url);
} else {
try {
config = require(configuration.configFile);
} catch(e) {
throw new Error('Error reading "' + relativeConfigFile() + '".')
}
}
if (typeof config != 'object') {
throw new Error('Config must be an object: ' + relativeConfigFile());
}
if (program.url) {
console.log('Parsed url ' + program.url);
} else {
console.log('Loaded configuration file "' + relativeConfigFile() + '".');
}
if (config[configuration.environment]) {
console.log('Using environment "' + configuration.environment + '".')
config = config[configuration.environment]
}
supportsCoffee = program.coffee || config.coffee
return config
}
program
.version(configuration.version)
.option('-i, --init', 'Initializes the project.')
.option('-e, --env <environment>', 'Specify the environment.')
.option('-m, --migrate', 'Run pending migrations.')
.option('-u, --undo', 'Undo the last migration.')
.option('-f, --force', 'Forces the action to be done.')
.option('-c, --create-migration [migration-name]', 'Creates a new migration.')
.option('-p, --migrations-path <migration-path>', 'migration directory path.')
.option('-U, --url <url>', 'Database url. An alternative to a config file')
.option('-o,--options-path <options_file>', 'Specifies lib options from file.')
.option('--config <config_file>', 'Specifies alternate config file.')
.option('--coffee', 'Consider coffee script files as migration source.')
.parse(process.argv)
if(typeof program.optionsPath === 'string') {
var optionsFilesPath = null;
if (isRelativePath(program.optionsPath)) {
optionsFilePath = path.join(process.cwd(), program.optionsPath);
} else {
optionsFilePath = program.optionsPath;
}
loadDefaultOptions(optionsFilePath);
}
if(typeof program.config === 'string') {
if (isRelativePath(program.config)) {
configuration.configFile = path.join(process.cwd(), program.config);
} else {
configuration.configFile = program.config
}
}
if(typeof program.migrationsPath=== 'string') {
configuration.migrationsPath = program.migrationsPath;
}
if(typeof program.env === 'string') {
configuration.environment = program.env
}
if (program.migrate || program.undo) {
if (configFileExists() || program.url) {
var config
, options = {}
try {
config = readConfig()
} catch(e) {
console.log(e.message)
process.exit(1)
}
_.each(config, function(value, key) {
if(['database', 'username', 'password'].indexOf(key) == -1) {
options[key] = value
}
if (key === "use_env_variable") {
if (process.env[value]) {
var db_info = process.env[value].match(/([^:]+):\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/);
config.database = db_info[6];
config.username = db_info[2];
config.password = db_info[3];
options = _.extend(options, {
host: db_info[4],
port: db_info[5],
dialect: db_info[1],
protocol: db_info[1]
});
}
}
})
options = _.extend(options, { logging: false })
var sequelize = new Sequelize(config.database, config.username, config.password, options)
, migratorOptions = { path: configuration.migrationsPath }
if (supportsCoffee) {
migratorOptions = _.merge(migratorOptions, { filesFilter: /\.js$|\.coffee$/ })
}
sequelize.authenticate().success(function () {
var migrator = sequelize.getMigrator(migratorOptions)
if (program.undo) {
migrator.findOrCreateSequelizeMetaDAO().success(function(Meta) {
Meta.find({ order: 'id DESC' }).success(function(meta) {
if (meta) {
migrator = sequelize.getMigrator(_.extend(migratorOptions, meta.values), true)
migrator.migrate({ method: 'down' }).success(function() {
process.exit(0)
})
} else {
console.log("There are no pending migrations.")
process.exit(0)
}
})
})
} else {
sequelize.migrate().success(function() {
process.exit(0)
})
}
}).error(function (err) {
console.error("Unable to connect to database: "+err)
})
} else {
console.log('Cannot find "' + configuration.configFile + '". Have you run "sequelize --init"?')
process.exit(1)
}
} else if(program.init) {
if(!configFileExists() || !!program.force) {
writeDefaultConfig()
console.log('Created "' + relativeConfigFile() + '"')
} else {
console.log('The file "' + relativeConfigFile() + '" already exists. Run "sequelize --init --force" to overwrite it.')
process.exit(1)
}
createMigrationsFolder(program.force)
} else if(program.createMigration) {
createMigrationsFolder()
var config;
try {
config = readConfig()
} catch(e) {
console.log(e.message)
process.exit(1)
}
var migrationContent = ""
, migrationExtension = supportsCoffee ? '.coffee' : '.js'
, migrationName = [
moment().format('YYYYMMDDHHmmss'),
(typeof program.createMigration === 'string') ? program.createMigration : 'unnamed-migration'
].join('-') + migrationExtension
if (supportsCoffee) {
migrationContent = [
"module.exports = ",
" up: (migration, DataTypes, done) ->",
" # add altering commands here, calling 'done' when finished",
" done()",
"",
" down: (migration, DataTypes, done) ->",
" # add reverting commands here, calling 'done' when finished",
" done()"
].join('\n') + "\n"
} else {
migrationContent = [
"module.exports = {",
" up: function(migration, DataTypes, done) {",
" // add altering commands here, calling 'done' when finished",
" done()",
" },",
" down: function(migration, DataTypes, done) {",
" // add reverting commands here, calling 'done' when finished",
" done()",
" }",
"}"
].join('\n') + "\n"
}
fs.writeFileSync(configuration.migrationsPath + '/' + migrationName, migrationContent)
console.log('New migration "' + migrationName + '" was added to "' +
path.relative(process.cwd(), configuration.migrationsPath) + '/".')
} else {
console.log('No action specified. Try "sequelize --help" for usage information.')
}
......@@ -13,6 +13,7 @@ Notice: All 1.7.x changes are present in 2.0.x aswell
- [BUG] Fix logging options for sequelize.sync
- [INTERNALS] `bulkDeleteQuery` was removed from the MySQL / abstract query generator, since it was never used internally. Please use `deleteQuery` instead.
- [BUG] find no longer applies limit: 1 if querying on a primary key, should fix a lot of subquery issues.
- [FEATURE] Extract CLI into [separate projects](https://github.com/sequelize/cli).
#### Breaking changes
- Sequelize now returns promises instead of its custom event emitter from most calls. This affects methods that return multiple values (like `findOrCreate` or `findOrInitialize`). If your current callbacks do not accept the 2nd success parameter you might be seeing an array as the first param. Either use `.spread()` for these methods or add another argument to your callback: `.success(instance)` -> `.success(instance, created)`.
......
var markdox = require('markdox')
, program = require('commander')
, fs = require('fs')
, _ = require('lodash');
program
.version('0.0.1')
.option('-f, --file [file]', 'Process a single file', '')
.option('-a, --all', 'Process all files, generate index etc. (default if no options are specified')
.option('-c, --clean', 'Remove all generated markdown and HTML files')
.option('--html', 'Generate html files from the markdown ones (requires manual installation of the github-flavored-markdown package')
.parse(process.argv)
if (program.clean) {
fs.readdirSync('docs/').forEach(function (file) {
if (file.indexOf('.ejs') === -1 && file.indexOf('.js') === -1) {
fs.unlinkSync ('docs/' + file);
}
})
return
}
if (program.html) {
var ghm = require('github-flavored-markdown')
}
var getTag = function(tags, tagName) {
return _.find(tags, function (tag) {
return tag.type === tagName;
});
};
var getTags = function(tags, tagName) {
return _.where(tags, function (tag) {
return tag.type === tagName;
});
}
var options = {
formatter: function (docfile) {
docfile = markdox.defaultFormatter(docfile);
docfile.members = [];
docfile.javadoc.forEach(function(javadoc){
// Find constructor tags
javadoc.isConstructor = getTag(javadoc.raw.tags, 'constructor') !== undefined;
javadoc.isMixin = getTag(javadoc.raw.tags, 'mixin') !== undefined;
javadoc.isProperty = getTag(javadoc.raw.tags, 'property') !== undefined
javadoc.private = getTag(javadoc.raw.tags, 'private') !== undefined
javadoc.since = getTag(javadoc.raw.tags, 'since');
// Only show params without a dot in them (dots means attributes of object, so no need to clutter the signature too much)
var params = []
javadoc.paramTags.forEach(function (paramTag) {
if (paramTag.name.indexOf('.') === -1) {
params.push(paramTag.name);
}
});
javadoc.paramStr = (javadoc.isMethod || javadoc.isFunction) ? '(' + params.join(', ') + ')' : '';
// Convert | to &#124; to be able to use github flavored md tables
if (javadoc.paramTags) {
javadoc.paramTags.forEach(function (paramTag) {
paramTag.joinedTypes = paramTag.joinedTypes.replace(/\|/g, '&#124;')
});
}
// Handle aliases
javadoc.aliases = getTags(javadoc.raw.tags, 'alias').map(function (a) {
return a.string
}).join(', ')
// Handle deprecation text
if (javadoc.deprecated) {
var deprecation = getTag(javadoc.raw.tags, 'deprecated')
javadoc.deprecated = deprecation.string
}
// Handle linking in comments
javadoc.see = getTags(javadoc.raw.tags, 'see');
javadoc.see.forEach(function (see, i, collection) {
collection[i] = {}
if (see.local) {
collection[i].external = false
if (see.local.indexOf('{') === 0){
var _see = see.local.split('}')
_see[0] = _see[0].substring(1)
collection[i].url = 'API-Reference-' + _see[0]
collection[i].text = see.local.replace(/{|}/g, '')
} else {
collection[i].url = false
collection[i].text = see.local
}
} else {
see.external = true
see.text = see.url
collection[i] = see
}
})
// Set a name for properties
if (!javadoc.name) {
var property = getTag(javadoc.raw.tags, 'property')
if (property) {
javadoc.name = property.string
}
}
if (javadoc.isMixin) {
javadoc.name = getTag(javadoc.raw.tags, 'mixin').string;
}
javadoc.mixes = getTags(javadoc.raw.tags, 'mixes').map(function (mix) {
return {
text: mix.string,
link: (mix.string.indexOf('www') !== -1 || mix.string.indexOf('http') !== -1) ? mix.string: 'API-Reference-' + mix.string
}
})
if (!javadoc.isClass) {
if (!javadoc.isProperty) {
docfile.members.push({
text: javadoc.name + javadoc.paramStr,
link: '#' + javadoc.name
})
} else {
docfile.members.push({
text: javadoc.name,
link: '#' + javadoc.name
})
}
}
});
return docfile;
},
template: 'docs/output.md.ejs'
};
var files;
if (program.file) {
files = [{file: program.file, output: 'tmp'}]
} else {
files = [
{file:'lib/sequelize.js', output: 'API-Reference-Sequelize'},
{file:'lib/dao.js', output: 'API-Reference-DAO'},
{file:'lib/dao-factory.js', output: 'API-Reference-DAOFactory'},
{file:'lib/query-chainer.js', output: 'API-Reference-QueryChainer'},
{file:'lib/emitters/custom-event-emitter.js', output: 'API-Reference-EventEmitter'},
{file:'lib/hooks.js', output: 'API-Reference-Hooks'},
{file:'lib/associations/mixin.js', output: 'API-Reference-Associations'},
{file:'lib/promise.js', output: 'API-Reference-Promise'},
{file:'lib/transaction.js', output: 'API-Reference-Transaction'}
];
}
files.forEach(function (file) {
var opts = _.clone(options)
, output = 'docs/' + file.output + '.md'
opts.output = output
markdox.process(file.file, opts, function(){
if (program.html) {
var md = fs.readFileSync(output).toString();
fs.writeFileSync(output.replace('md', 'html'), ghm.parse(md))
}
});
})
\ No newline at end of file
<? docfiles.forEach(function(doc) { ?>
<? doc.javadoc.forEach(function(comment) { ?>
<? if (comment.name && comment.private !== true) { -?>
<? if (!comment.ignore) { ?>
<a name="<?= comment.name ?>" />
<? if (comment.isConstructor) { ?>
### `new <?= comment.name ?><?= comment.paramStr ?>`
<? } else if (comment.isMixin) { ?>
### Mixin <?= comment.name ?>
<? } else if (comment.isClass) { ?>
### Class <?= comment.name ?>
<? } else { ?>
#### `<?= comment.name ?><?= comment.paramStr ?>` <? if (comment.returnTags.length > 0) { ?> -> `<?= comment.returnTags[0].joinedTypes ?>` <? } ?>
<? } ?>
<? } ?>
<?= comment.description ?>
<? if (comment.mixes.length) { ?>
### Mixes:
<? comment.mixes.forEach(function (mix) { -?>
* [<?=mix.text ?>](<?=mix.link ?>)
<? }) ?>
<? } ?>
<? if (comment.isClass) { ?>
### Members:
<? doc.members.forEach(function (member) { -?>
* [<?= member.text ?>](<?= member.link ?>)
<? }) -?>
<? } ?>
<? if (comment.deprecated) { ?>
**Deprecated** <?- comment.deprecated ?>
<? } ?>
<? if (comment.version) { ?>
Version: <?= comment.version ?>
<? } ?>
<? if (comment.see.length) { ?>See:<? } ?>
<? comment.see.forEach(function (see) { -?>
<? if (see.url !== false) { -?>
* [<?= see.text ?>](<?= see.url ?>)
<? } else { -?>
* <?= see.text ?>
<? } -?>
<? }) -?>
<? if (comment.paramTags.length > 0) { ?>
##### Params:
| Name | Type | Description |
| ---- | ---- | ----------- |
<? comment.paramTags.forEach(function(paramTag) { -?>
| <?= paramTag.name ?> | <?= paramTag.joinedTypes ?> | <?= paramTag.description ?> |
<? }) ?>
<? } ?>
<? if (comment.returnTags.length > 0 && comment.returnTags[0].description.length > 0) { ?>
__Returns:__ <?= comment.returnTags[0].description ?>
<? } ?>
<? if (comment.aliases) { ?>
__Aliases:__ *<?= comment.aliases ?>*
<? } ?>
<? if (comment.since) { ?>
__Since:__ *<?= comment.since.string ?>*
<? } ?>
======
<? } ?>
<? }) ?>
_This document is automatically generated based on source code comments. Please do not edit it directly, as your changes will be ignored. Please write on <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, open an issue or a create a pull request if you feel something can be improved. For help on how to write source code documentation see [JSDoc](http://usejsdoc.org) and [markdox](https://github.com/cbou/markdox)_
_This documentation was automagically created on <?= new Date().toString() ?>_
<? }) ?>
\ No newline at end of file
......@@ -40,7 +40,6 @@
"url": "https://github.com/sequelize/sequelize/issues"
},
"dependencies": {
"commander": "~2.1.0",
"lodash": "~2.4.0",
"underscore.string": "~2.3.0",
"lingo": "~0.0.5",
......@@ -88,9 +87,6 @@
"test": "make all",
"docs": "node_modules/.bin/yuidoc . -o docs"
},
"bin": {
"sequelize": "bin/sequelize"
},
"engines": {
"node": ">=0.6.21"
},
......
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/support')
, DataTypes = require(__dirname + "/../lib/data-types")
, dialect = Support.getTestDialect()
, _ = require('lodash')
, exec = require('child_process').exec
, version = (require(__dirname + '/../package.json')).version
, path = require('path')
, os = require('os')
chai.config.includeStack = true
if (os.type().toLowerCase().indexOf('windows') === -1) {
describe(Support.getTestDialectTeaser("Executable"), function() {
describe('call without arguments', function() {
it("prints usage instructions", function(done) {
exec('bin/sequelize', function(err, stdout, stderr) {
expect(stdout).to.include("No action specified. Try \"sequelize --help\" for usage information.")
done()
})
})
})
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(stdout).to.include("Usage: sequelize [options]")
done()
})
})
})
})
})(["--help", "-h"])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("prints the help", function(done) {
exec("bin/sequelize " + flag, function(err, stdout, stderr) {
expect(version).to.not.be.empty
expect(stdout).to.include(version)
done()
})
})
})
})
})(['--version', '-V'])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
;(function(folders) {
folders.forEach(function(folder) {
it("creates a '" + folder + "' folder", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include(folder)
done()
})
})
})
})
})
})(['config', 'migrations'])
it("creates a custom migrations folder", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init -p ./db/migrate", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('db')
done()
})
})
})
})
it("creates a config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("ls -ila config", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('config.json')
done()
})
})
})
})
it("does not overwrite an existing config.json file", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("echo 'foo' > config/config.json", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(err) {
expect(err.code).to.equal(1)
exec("cat config/config.json", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.equal("foo\n")
done()
})
})
})
})
})
})
})
})
})(['--init', '-i'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
})
})
}
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
expect(stdout).to.match(new RegExp(sDate + "..-foo.js"))
done()
})
})
})
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: function(migration, DataTypes, done) {')
expect(stdout).to.include('down: function(migration, DataTypes, done) {')
done()
})
})
})
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.js", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
})
})
})
})
})
})(['--create-migration', '-c'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function() {
exec("../../bin/sequelize " + flag + " 'foo'", { cwd: __dirname + '/tmp' }, callback)
})
})
}
describe(flag, function() {
it("creates a new file with the current timestamp", function(done) {
prepare(function() {
exec("ls -1 migrations", { cwd: __dirname + '/tmp' }, function(err, stdout) {
var date = new Date()
, format = function(i) { return (parseInt(i, 10) < 10 ? '0' + i : i) }
, sDate = [date.getFullYear(), format(date.getMonth() + 1), format(date.getDate()), format(date.getHours()), format(date.getMinutes())].join('')
expect(stdout).to.match(new RegExp(sDate + "..-foo.coffee"))
done()
})
})
})
it("adds a skeleton with an up and a down method", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('up: (migration, DataTypes, done) ->')
expect(stdout).to.include('down: (migration, DataTypes, done) ->')
done()
})
})
})
it("calls the done callback", function(done) {
prepare(function() {
exec("cat migrations/*-foo.coffee", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('done()')
expect(stdout.match(/(done\(\))/)).to.have.length(2)
done()
})
})
})
})
})
})(['--coffee --create-migration', '--coffee -c'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var source = (flag.indexOf('coffee') === -1)
? "../assets/migrations/*-createPerson.js"
: "../assets/migrations/*-createPerson.coffee"
exec("cp " + source + " ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + flag, { cwd: __dirname + "/tmp" }, callback)
})
})
})
})
})
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("creates the respective table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
})
})
})
})([
'--migrate',
'--migrate --coffee',
'--migrate --config ../tmp/config/config.json',
'--migrate --config ' + path.join(__dirname, 'tmp', 'config', 'config.json'),
'-m',
'-m --coffee',
'-m --config ../tmp/config/config.json',
'-m --config ' + path.join(__dirname, 'tmp', 'config', 'config.json')
])
;(function(flags) {
flags.forEach(function(flag) {
var execBinary = function(callback, _flag) {
_flag = _flag || flag
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize " + _flag, { cwd: __dirname + "/tmp" }, callback)
})
}
var prepare = function(callback, options) {
options = options || {}
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
if (!options.skipExecBinary) {
execBinary(callback, options.flag)
}
})
})
})
})
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("stops execution if no migrations have been done yet", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function(err, output) {
expect(err).to.be.null
expect(output).to.include("There are no pending migrations.")
done()
}.bind(this))
})
it("is correctly undoing a migration if they have been done yet", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
execBinary(function(err, output) {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
expect(tables).to.have.length(1)
expect(tables[0]).to.equal("SequelizeMeta")
done()
})
})
})
}.bind(this), { flag: '-m' })
})
})
})
})(['--migrate --undo', '-mu', '--undo', '-u'])
;(function(flags) {
flags.forEach(function(flag) {
var prepare = function(callback) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize --init", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cp ../assets/migrations/*-createPerson.js ./migrations/", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("cat ../support.js|sed s,/../,/../../, > ./support.js", { cwd: __dirname + '/tmp' }, function(error, stdout) {
var dialect = Support.getTestDialect()
, config = require(__dirname + '/config/config.js')
config.sqlite.storage = __dirname + "/tmp/test.sqlite"
config = _.extend(config, config[dialect], { dialect: dialect })
var url = Support.getTestUrl(config);
exec("echo '" + JSON.stringify(config) + "' > config/config.json", { cwd: __dirname + '/tmp' }, function(error, stdout) {
exec("../../bin/sequelize -m " + flag + " " + url, { cwd: __dirname + "/tmp" }, callback)
})
})
})
})
})
}
describe(flag, function() {
it("creates a SequelizeMeta table", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[1]).to.equal("SequelizeMeta")
done()
})
}.bind(this))
})
it("creates the respective table via url", function(done) {
var sequelize = this.sequelize
if (this.sequelize.options.dialect === 'sqlite') {
var options = this.sequelize.options
options.storage = __dirname + "/tmp/test.sqlite"
sequelize = new Support.Sequelize("", "", "", options)
}
prepare(function() {
sequelize.getQueryInterface().showAllTables().success(function(tables) {
tables = tables.sort()
expect(tables).to.have.length(2)
expect(tables[0]).to.equal("Person")
done()
})
}.bind(this))
})
})
})
})(['--url', '-U'])
;(function(flags) {
flags.forEach(function(flag) {
describe(flag, function() {
it("using options file instead of cli switches", function(done) {
exec("rm -rf ./*", { cwd: __dirname + '/tmp' }, function() {
var _path = path.resolve(__dirname, 'config', 'options.js')
exec("../../bin/sequelize --init " + flag + " " + _path, { cwd: __dirname + '/tmp' }, function(err, stdout) {
exec("ls -ila", { cwd: __dirname + '/tmp' }, function(err, stdout) {
expect(stdout).to.include('db')
done()
})
})
})
})
});
})
})(['--options-path', '-o'])
})
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!