Sequelize.js
7.13 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
var Sequelize = function(database, username, password, options) {
options = options || {}
this.tables = {}
this.options = Sequelize.Helper.Hash.without(options, ["host", "port", "disableTableNameModification"])
this.config = {
database: database,
username: username,
password: (((["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
host : options.host || 'localhost',
port : options.port || 3306
}
Sequelize.Helper.configure({
disableTableNameModification: (options.disableTableNameModification || false)
})
}
var classMethods = {
Helper: new (require(__dirname + "/Helper").Helper)(Sequelize),
STRING: 'VARCHAR(255)',
TEXT: 'TEXT',
INTEGER: 'INT',
DATE: 'DATETIME',
BOOLEAN: 'TINYINT(1)',
FLOAT: 'FLOAT',
sqlQueryFor: function(command, values) {
var query = null
if(values.hasOwnProperty('fields') && Array.isArray(values.fields))
values.fields = values.fields.map(function(field) { return ['', field, ''].join('`') }).join(", ")
switch(command) {
case 'create':
query = "CREATE TABLE IF NOT EXISTS `%{table}` (%{fields})"
break
case 'drop':
query = "DROP TABLE IF EXISTS `%{table}`"
break
case 'select':
values.fields = values.fields || '*'
query = "SELECT %{fields} FROM `%{table}`"
if(values.where) {
if(Sequelize.Helper.Hash.isHash(values.where))
values.where = Sequelize.Helper.SQL.hashToWhereConditions(values.where)
query += " WHERE %{where}"
}
if(values.order) query += " ORDER BY %{order}"
if(values.group) query += " GROUP BY %{group}"
if(values.limit) {
if(values.offset) query += " LIMIT %{offset}, %{limit}"
else query += " LIMIT %{limit}"
}
break
case 'insert':
query = "INSERT INTO `%{table}` (%{fields}) VALUES (%{values})"
break
case 'update':
if(Sequelize.Helper.Hash.isHash(values.values))
values.values = Sequelize.Helper.SQL.hashToWhereConditions(values.values)
query = "UPDATE `%{table}` SET %{values} WHERE `id`=%{id}"
break
case 'delete':
if(Sequelize.Helper.Hash.isHash(values.where))
values.where = Sequelize.Helper.SQL.hashToWhereConditions(values.where)
query = "DELETE FROM `%{table}` WHERE %{where}"
if(typeof values.limit == 'undefined') query += " LIMIT 1"
else if(values.limit != null) query += " LIMIT " + values.limit
break
}
return Sequelize.Helper.evaluateTemplate(query, values)
},
chainQueries: function() {
this.Helper.QueryChainer.chain.apply(this.Helper.QueryChainer, arguments)
}
}
Sequelize.prototype = {
define: function(name, attributes, options) {
var SequelizeTable = require(__dirname + "/SequelizeTable").SequelizeTable
var _attributes = {}
var createdAt = "createdAt";
var updatedAt = "updatedAt";
if(options){
if(options.createdAt)createdAt = options.createdAt;
if(options.updatedAt)updatedAt = options.updatedAt;
}
Sequelize.Helper.Hash.forEach(attributes, function(value, key) {
if(typeof value == 'string')
_attributes[key] = { type: value }
else if((typeof value == 'object') && (!value.length))
_attributes[key] = value
else
throw new Error("Please specify a datatype either by using Sequelize.* or pass a hash!")
})
_attributes[createdAt] = { type: Sequelize.DATE, allowNull: false}
_attributes[updatedAt] = { type: Sequelize.DATE, allowNull: false}
var table = new SequelizeTable(Sequelize, this, Sequelize.Helper.SQL.asTableName(name), _attributes, options)
// refactor this to use the table's attributes
this.tables[name] = {klass: table, attributes: attributes}
table.sequelize = this
return table
},
import: function(path) {
var imported = require(path),
self = this,
result = {}
Sequelize.Helper.Hash.forEach(imported, function(definition, functionName) {
definition(Sequelize, self)
})
Sequelize.Helper.Hash.forEach(this.tables, function(constructor, name) {
result[name] = constructor.klass
})
return result
},
get tableNames() {
var result = []
Sequelize.Helper.Hash.keys(this.tables).forEach(function(tableName) {
result.push(Sequelize.Helper.SQL.asTableName(tableName))
})
return result
},
sync: function(callback) {
var finished = [],
tables = this.tables,
errors = []
Sequelize.Helper.Hash.forEach(tables, function(table) {
table.klass.prepareAssociations()
})
if((Sequelize.Helper.Hash.keys(this.tables).length == 0) && callback)
callback()
else
Sequelize.Helper.Hash.forEach(tables, function(table) {
table.klass.sync(function(_, err) {
finished.push(true)
if(err) errors.push(err)
if((finished.length == Sequelize.Helper.Hash.keys(tables).length) && callback)
callback(errors)
})
})
},
drop: function(callback) {
var finished = [],
tables = this.tables,
errors = []
if((Sequelize.Helper.Hash.keys(tables).length == 0) && callback)
callback()
else
Sequelize.Helper.Hash.forEach(tables, function(table, tableName) {
table.klass.drop(function(_, err) {
finished.push(true)
if(err) errors.push(err)
if((finished.length == Sequelize.Helper.Hash.keys(tables).length) && callback)
callback(errors)
})
})
},
query: function(queryString, callback) {
var fields = [],
values = [],
self = this,
client = require(__dirname + "/../nodejs-mysql-native/index").createTCPClient(this.config.host, this.config.port)
client.connection.on('error', function() {
callback(null, null, { message: "Unable to establish a connection to " + [self.config.host, self.config.port].join(":") })
})
client.auto_prepare = true
client
.auth(self.config.database, self.config.username, self.config.password)
.on('error', function(err) { callback(null, null, err) })
.on('authorized', function() {
if(!self.options.disableLogging)
Sequelize.Helper.log("Executing the query: " + queryString)
client
.query(queryString)
.on('error', function(err) { Sequelize.Helper.log(err) })
.on('row', function(r){ values.push(r) })
.on('field', function(f){ fields.push(f)})
.on('end', function(stats) {
if(callback) {
var result = []
values.forEach(function(valueArray) {
var mapping = {}
for(var i = 0; i < fields.length; i++)
mapping[fields[i].name] = valueArray[i]
result.push(mapping)
})
if(callback) callback(result, stats)
}
})
client.close()
})
}
}
for (var key in classMethods) Sequelize[key] = classMethods[key]
module.exports = Sequelize