sequelize
5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/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'
, environment = process.env.NODE_ENV || 'development'
, 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() {
var config
try {
config = fs.readFileSync(configFile)
} catch(e) {
throw new Error('Error reading "config/config.json".')
}
try {
config = JSON.parse(config)
} catch (e) {
throw new Error('Error parsing "config/config.json" as JSON.')
}
if (config[environment]) {
config = config[environment]
}
return config
}
program
.version(packageJson.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.')
.parse(process.argv)
if(typeof program.env === 'string') {
environment = program.env
}
console.log("Using environment '" + environment + "'.")
if(program.migrate) {
if(configFileExists) {
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: 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 {
console.log('Cannot find "config/config.json". Have you run "sequelize --init"?')
process.exit(1)
}
} 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('Created "config/config.json"')
} else {
console.log('"config/config.json" already exists. Run "sequelize --init --force" to overwrite.')
process.exit(1)
}
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, 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')
fs.writeFileSync(migrationsPath + '/' + migrationName, migrationContent)
} else {
console.log('Try "sequelize --help" for usage information.')
}