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

Commit 74399645 by Sascha Depold

refactored Sequelize to not using global variables but exporting it according to CommonJS standard

1 parent 6e7b1043
...@@ -6,11 +6,14 @@ The Sequelize library provides easy access to a MySQL database by mapping databa ...@@ -6,11 +6,14 @@ The Sequelize library provides easy access to a MySQL database by mapping databa
Sequelize will have a Kiwi package in future. For now, you can install it via NPM or just download the code from the git repository and require _sequelize.js_: Sequelize will have a Kiwi package in future. For now, you can install it via NPM or just download the code from the git repository and require _sequelize.js_:
#npm: # npm:
npm install sequelize npm install sequelize
var Sequelize = require("sequelize").Sequelize
#checkout: # checkout:
require(__dirname + "/path/to/sequelize/sequelize") cd <path/to/lib>
git clone git://github.com/sdepold/sequelize.git
var Sequelize = require(__dirname + "/lib/sequelize/src/sequelize").Sequelize
This will make the class Sequelize available. This will make the class Sequelize available.
......
...@@ -27,4 +27,7 @@ ...@@ -27,4 +27,7 @@
- added BOOLEAN type - added BOOLEAN type
- added FLOAT type - added FLOAT type
- fixed DATE type issue - fixed DATE type issue
- fixed npm package - fixed npm package
\ No newline at end of file
# 0.2.6 #
- refactored Sequelize to fit CommonJS module conventions
\ No newline at end of file
/*
var sequelize = new require('sequelize').sequelize(database, username[, password])
var Tag = sequelize.define('Tag', {title: sequelize.TEXT, createdAt: sequelize.DATE})
var t = new Tag({title: 'Office-Stuff', createdAt: new Date()})
t.save(function() {
callback
})
*/
require(__dirname + "/src/Sequelize")
require(__dirname + "/SequelizeHelper") var Sequelize = function(database, username, password, options) {
require(__dirname + "/SequelizeTable")
Sequelize = function(database, username, password, options) {
this.config = { this.config = {
database: database, database: database,
username: username, username: username,
...@@ -12,6 +9,8 @@ Sequelize = function(database, username, password, options) { ...@@ -12,6 +9,8 @@ Sequelize = function(database, username, password, options) {
} }
var classMethods = { var classMethods = {
Helper: new require(__dirname + "/Helper").Helper(Sequelize),
STRING: 'VARCHAR(255)', STRING: 'VARCHAR(255)',
TEXT: 'TEXT', TEXT: 'TEXT',
INTEGER: 'INT', INTEGER: 'INT',
...@@ -52,20 +51,20 @@ var classMethods = { ...@@ -52,20 +51,20 @@ var classMethods = {
break break
} }
return SequelizeHelper.evaluateTemplate(query, values) return Sequelize.Helper.evaluateTemplate(query, values)
}, },
chainQueries: function(queries, callback) { chainQueries: function(queries, callback) {
// queries = [{method: object}, {method: object, params: [1,2,3]}, {method: object}] // queries = [{method: object}, {method: object, params: [1,2,3]}, {method: object}]
var executeQuery = function(index) { var executeQuery = function(index) {
var queryHash = queries[index] var queryHash = queries[index]
var method = SequelizeHelper.Array.without(SequelizeHelper.Hash.keys(queryHash), "params")[0] var method = Sequelize.Helper.Array.without(Sequelize.Helper.Hash.keys(queryHash), "params")[0]
var object = queryHash[method] var object = queryHash[method]
var iterator = function() { var iterator = function() {
if(queries.length > (index + 1)) executeQuery(index + 1) if(queries.length > (index + 1)) executeQuery(index + 1)
else if (callback) callback() else if (callback) callback()
} }
object[method].apply(object, SequelizeHelper.Array.join(queryHash.params || [], [iterator])) object[method].apply(object, Sequelize.Helper.Array.join(queryHash.params || [], [iterator]))
} }
if(queries.length > 0) executeQuery(0) if(queries.length > 0) executeQuery(0)
else if (callback) callback() else if (callback) callback()
...@@ -75,8 +74,8 @@ var classMethods = { ...@@ -75,8 +74,8 @@ var classMethods = {
Sequelize.prototype = { Sequelize.prototype = {
get tableNames() { get tableNames() {
var result = [] var result = []
SequelizeHelper.Hash.keys(this.tables).forEach(function(tableName) { Sequelize.Helper.Hash.keys(this.tables).forEach(function(tableName) {
result.push(SequelizeHelper.SQL.asTableName(tableName)) result.push(Sequelize.Helper.SQL.asTableName(tableName))
}) })
return result return result
}, },
...@@ -85,17 +84,17 @@ Sequelize.prototype = { ...@@ -85,17 +84,17 @@ Sequelize.prototype = {
var finished = [] var finished = []
var tables = this.tables var tables = this.tables
SequelizeHelper.Hash.forEach(tables, function(table) { Sequelize.Helper.Hash.forEach(tables, function(table) {
table.klass.prepareAssociations() table.klass.prepareAssociations()
}) })
if((SequelizeHelper.Hash.keys(this.tables).length == 0) && callback) if((Sequelize.Helper.Hash.keys(this.tables).length == 0) && callback)
callback() callback()
else else
SequelizeHelper.Hash.forEach(tables, function(table) { Sequelize.Helper.Hash.forEach(tables, function(table) {
table.klass.sync(function() { table.klass.sync(function() {
finished.push(true) finished.push(true)
if((finished.length == SequelizeHelper.Hash.keys(tables).length) && callback) if((finished.length == Sequelize.Helper.Hash.keys(tables).length) && callback)
callback() callback()
}) })
}) })
...@@ -105,22 +104,24 @@ Sequelize.prototype = { ...@@ -105,22 +104,24 @@ Sequelize.prototype = {
var finished = [] var finished = []
var tables = this.tables var tables = this.tables
if((SequelizeHelper.Hash.keys(tables).length == 0) && callback) callback() if((Sequelize.Helper.Hash.keys(tables).length == 0) && callback) callback()
else else
SequelizeHelper.Hash.forEach(tables, function(table, tableName) { Sequelize.Helper.Hash.forEach(tables, function(table, tableName) {
table.klass.drop(function() { table.klass.drop(function() {
finished.push(true) finished.push(true)
if(finished.length == SequelizeHelper.Hash.keys(tables).length) if(finished.length == Sequelize.Helper.Hash.keys(tables).length)
if(callback) callback() if(callback) callback()
}) })
}) })
}, },
define: function(name, attributes) { define: function(name, attributes) {
var SequelizeTable = require(__dirname + "/SequelizeTable").SequelizeTable
attributes.createdAt = 'DATETIME NOT NULL' attributes.createdAt = 'DATETIME NOT NULL'
attributes.updatedAt = 'DATETIME NOT NULL' attributes.updatedAt = 'DATETIME NOT NULL'
var table = new SequelizeTable(this, SequelizeHelper.SQL.asTableName(name), attributes) var table = new SequelizeTable(Sequelize, this, Sequelize.Helper.SQL.asTableName(name), attributes)
table.attributes = attributes table.attributes = attributes
this.tables[name] = {klass: table, attributes: attributes} this.tables[name] = {klass: table, attributes: attributes}
...@@ -139,7 +140,7 @@ Sequelize.prototype = { ...@@ -139,7 +140,7 @@ Sequelize.prototype = {
.auth(this.config.database, this.config.username, this.config.password) .auth(this.config.database, this.config.username, this.config.password)
.addListener('authorized', function() { .addListener('authorized', function() {
if(!self.options.disableLogging) if(!self.options.disableLogging)
SequelizeHelper.log("Executing the query: " + queryString) Sequelize.Helper.log("Executing the query: " + queryString)
connection connection
.query(queryString) .query(queryString)
...@@ -162,6 +163,6 @@ Sequelize.prototype = { ...@@ -162,6 +163,6 @@ Sequelize.prototype = {
} }
} }
SequelizeHelper.Hash.forEach(classMethods, function(method, methodName) { for (var key in classMethods) Sequelize[key] = classMethods[key]
Sequelize[methodName] = method
}) exports.Sequelize = Sequelize
\ No newline at end of file \ No newline at end of file
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
A.hasMany(B) + B.hasMany(A) => AB.aId + AB.bId A.hasMany(B) + B.hasMany(A) => AB.aId + AB.bId
*/ */
SequelizeTable = function(sequelize, tableName, attributes) { exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes) {
var table = function(values) { var table = function(values) {
var self = this var self = this
SequelizeHelper.Hash.forEach(values, function(value, key) { Sequelize.Helper.Hash.forEach(values, function(value, key) {
if(attributes[key]) { if(attributes[key]) {
if(attributes[key].indexOf(Sequelize.BOOLEAN) > -1) if(attributes[key].indexOf(Sequelize.BOOLEAN) > -1)
self[key] = ((value == 1) || (value == true)) ? true : false self[key] = ((value == 1) || (value == true)) ? true : false
...@@ -31,7 +31,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -31,7 +31,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
isAssociatedWith: function(anotherTable, associationType) { isAssociatedWith: function(anotherTable, associationType) {
var result = false var result = false
var associations = SequelizeHelper.Array.select(table.associations, function(assoc) { var associations = Sequelize.Helper.Array.select(table.associations, function(assoc) {
return assoc.table.tableName == anotherTable.tableName return assoc.table.tableName == anotherTable.tableName
}) })
...@@ -56,7 +56,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -56,7 +56,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
var _attributes = {} var _attributes = {}
_attributes[table.identifier] = Sequelize.INTEGER _attributes[table.identifier] = Sequelize.INTEGER
_attributes[association.table.identifier] = Sequelize.INTEGER _attributes[association.table.identifier] = Sequelize.INTEGER
sequelize.define(SequelizeHelper.SQL.manyToManyTableName(table, association.table), _attributes) sequelize.define(Sequelize.Helper.SQL.manyToManyTableName(table, association.table), _attributes)
} else { } else {
// one to many relation // one to many relation
association.table.attributes[table.identifier] = Sequelize.INTEGER association.table.attributes[table.identifier] = Sequelize.INTEGER
...@@ -77,7 +77,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -77,7 +77,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
sync: function(callback) { sync: function(callback) {
var fields = ["id INT NOT NULL auto_increment PRIMARY KEY"] var fields = ["id INT NOT NULL auto_increment PRIMARY KEY"]
SequelizeHelper.Hash.forEach(table.attributes, function(type, name) { Sequelize.Helper.Hash.forEach(table.attributes, function(type, name) {
fields.push(name + " " + type) fields.push(name + " " + type)
}) })
...@@ -98,13 +98,13 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -98,13 +98,13 @@ SequelizeTable = function(sequelize, tableName, attributes) {
// use the first param as callback if it is no object (hash) // use the first param as callback if it is no object (hash)
var _callback = (typeof options == 'object') ? callback : options var _callback = (typeof options == 'object') ? callback : options
var queryOptions = (typeof options == 'object') var queryOptions = (typeof options == 'object')
? SequelizeHelper.Hash.merge(options, { table: table.tableName }) ? Sequelize.Helper.Hash.merge(options, { table: table.tableName })
: { table: table.tableName } : { table: table.tableName }
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('select', queryOptions), Sequelize.sqlQueryFor('select', queryOptions),
function(result) { function(result) {
var objects = SequelizeHelper.Array.map(result, function(r) { return table.sqlResultToObject(r) }) var objects = Sequelize.Helper.Array.map(result, function(r) { return table.sqlResultToObject(r) })
if(_callback) _callback(objects) if(_callback) _callback(objects)
} }
) )
...@@ -114,7 +114,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -114,7 +114,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('select', { Sequelize.sqlQueryFor('select', {
table: table.tableName, table: table.tableName,
where: SequelizeHelper.SQL.hashToWhereConditions(conditions, table.attributes), where: Sequelize.Helper.SQL.hashToWhereConditions(conditions, table.attributes),
order: 'id DESC', order: 'id DESC',
limit: 1 limit: 1
}), function(result) { }), function(result) {
...@@ -142,7 +142,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -142,7 +142,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
// don't check inside of method to increase performance // don't check inside of method to increase performance
if(_table.isCrossAssociatedWith(table)) { if(_table.isCrossAssociatedWith(table)) {
table.prototype[assocName] = function(callback) { table.prototype[assocName] = function(callback) {
var Association = sequelize.tables[SequelizeHelper.SQL.manyToManyTableName(_table, table)].klass var Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(_table, table)].klass
var whereConditions = [table.identifier, this.id].join("=") var whereConditions = [table.identifier, this.id].join("=")
Association.findAll({ where: whereConditions }, function(result) { Association.findAll({ where: whereConditions }, function(result) {
if(result.length > 0) { if(result.length > 0) {
...@@ -154,11 +154,11 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -154,11 +154,11 @@ SequelizeTable = function(sequelize, tableName, attributes) {
} }
}) })
} }
table.prototype[SequelizeHelper.SQL.addPrefix('set', assocName)] = function(objects, callback) { table.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = function(objects, callback) {
var self = this var self = this
var Association = sequelize.tables[SequelizeHelper.SQL.manyToManyTableName(_table, table)].klass var Association = sequelize.tables[Sequelize.Helper.SQL.manyToManyTableName(_table, table)].klass
var currentAssociations = null var currentAssociations = null
var objectIds = SequelizeHelper.Array.map(objects, function(obj) { return obj.id }) var objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })
var getAssociatedObjects = function(callback) { var getAssociatedObjects = function(callback) {
self[assocName](function(associations) { self[assocName](function(associations) {
...@@ -180,8 +180,8 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -180,8 +180,8 @@ SequelizeTable = function(sequelize, tableName, attributes) {
) )
} }
var createNewAssociations = function(obsolete) { var createNewAssociations = function(obsolete) {
var currentIds = SequelizeHelper.Array.map(currentAssociations, function(assoc) { return assoc.id }) var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id })
var withoutExisting = SequelizeHelper.Array.reject(objects, function(o) { var withoutExisting = Sequelize.Helper.Array.reject(objects, function(o) {
currentIds.indexOf(o.id) > -1 currentIds.indexOf(o.id) > -1
}) })
var savings = [] var savings = []
...@@ -209,18 +209,18 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -209,18 +209,18 @@ SequelizeTable = function(sequelize, tableName, attributes) {
var whereConditions = [table.identifier, this.id].join("=") var whereConditions = [table.identifier, this.id].join("=")
_table.findAll({where: whereConditions}, callback) _table.findAll({where: whereConditions}, callback)
} }
table.prototype[SequelizeHelper.SQL.addPrefix('set', assocName)] = function(objects, callback) { table.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = function(objects, callback) {
var self = this var self = this
var objectIds = SequelizeHelper.Array.map(objects, function(obj) { return obj.id }) var objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })
this[assocName](function(currentAssociations) { this[assocName](function(currentAssociations) {
var currentIds = SequelizeHelper.Array.map(currentAssociations, function(assoc) { return assoc.id }) var currentIds = Sequelize.Helper.Array.map(currentAssociations, function(assoc) { return assoc.id })
var obsoleteAssociations = SequelizeHelper.Array.select(currentAssociations, function(assoc) { return objectsIds.indexOf(assoc.id) == -1 }) var obsoleteAssociations = Sequelize.Helper.Array.select(currentAssociations, function(assoc) { return objectsIds.indexOf(assoc.id) == -1 })
var queries = [] var queries = []
obsoleteAssociations.forEach(function(assoc) { obsoleteAssociations.forEach(function(assoc) {
var attr = {}; attr[table.identifier] = null var attr = {}; attr[table.identifier] = null
queries.push({updateAttributes: assoc, params: [attr]}) queries.push({updateAttributes: assoc, params: [attr]})
}) })
var newAssociations = SequelizeHelper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 }) var newAssociations = Sequelize.Helper.Array.select(objects, function(o) { return currentIds.indexOf(o.id) == -1 })
newAssociations.forEach(function(assoc) { newAssociations.forEach(function(assoc) {
var attr = {}; attr[table.identifier] = self.id var attr = {}; attr[table.identifier] = self.id
queries.push({updateAttributes: assoc, params: [attr]}) queries.push({updateAttributes: assoc, params: [attr]})
...@@ -248,7 +248,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -248,7 +248,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
_table.find(whereConditions, callback) _table.find(whereConditions, callback)
} }
table.prototype[SequelizeHelper.SQL.addPrefix('set', assocName)] = function(object, callback) { table.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = function(object, callback) {
var self = this var self = this
this[assocName](function(currentAssociation) { this[assocName](function(currentAssociation) {
...@@ -286,7 +286,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -286,7 +286,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
_table.find(this[_table.identifier], callback) _table.find(this[_table.identifier], callback)
} }
table.prototype[SequelizeHelper.SQL.addPrefix('set', assocName)] = function(object, callback) { table.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = function(object, callback) {
var attr = {}; attr[object.table.identifier] = object.id var attr = {}; attr[object.table.identifier] = object.id
var self = this var self = this
this.updateAttributes(attr, function() { this.updateAttributes(attr, function() {
...@@ -298,7 +298,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -298,7 +298,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
} }
} }
// don't put this into the hash! // don't put this into the hash!
classMethods.identifier = SequelizeHelper.SQL.asTableIdentifier(classMethods.tableName) classMethods.identifier = Sequelize.Helper.SQL.asTableIdentifier(classMethods.tableName)
// instance methods // instance methods
table.prototype = { table.prototype = {
...@@ -306,7 +306,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -306,7 +306,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
var result = {} var result = {}
var self = this var self = this
SequelizeHelper.Hash.keys(table.attributes).forEach(function(attribute) { Sequelize.Helper.Hash.keys(table.attributes).forEach(function(attribute) {
result[attribute] = (typeof self[attribute] == "undefined") ? null : self[attribute] result[attribute] = (typeof self[attribute] == "undefined") ? null : self[attribute]
}) })
...@@ -322,11 +322,11 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -322,11 +322,11 @@ SequelizeTable = function(sequelize, tableName, attributes) {
this.createdAt = new Date() this.createdAt = new Date()
query = Sequelize.sqlQueryFor('insert', { query = Sequelize.sqlQueryFor('insert', {
table: table.tableName, table: table.tableName,
fields: SequelizeHelper.SQL.fieldsForInsertQuery(this), fields: Sequelize.Helper.SQL.fieldsForInsertQuery(this),
values: SequelizeHelper.SQL.valuesForInsertQuery(this) values: Sequelize.Helper.SQL.valuesForInsertQuery(this)
}) })
} else } else
query = Sequelize.sqlQueryFor('update', { table: table.tableName, values: SequelizeHelper.SQL.valuesForUpdate(this), id: this.id }) query = Sequelize.sqlQueryFor('update', { table: table.tableName, values: Sequelize.Helper.SQL.valuesForUpdate(this), id: this.id })
sequelize.query(query, function(result, stats) { sequelize.query(query, function(result, stats) {
self.id = self.id || stats.insert_id self.id = self.id || stats.insert_id
...@@ -336,7 +336,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -336,7 +336,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
updateAttributes: function(newValues, callback) { updateAttributes: function(newValues, callback) {
var self = this var self = this
SequelizeHelper.Hash.keys(table.attributes).forEach(function(attribute) { Sequelize.Helper.Hash.keys(table.attributes).forEach(function(attribute) {
if(typeof newValues[attribute] != 'undefined') if(typeof newValues[attribute] != 'undefined')
self[attribute] = newValues[attribute] self[attribute] = newValues[attribute]
}) })
...@@ -352,7 +352,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -352,7 +352,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
} }
} }
SequelizeHelper.Hash.forEach(classMethods, function(method, methodName) { Sequelize.Helper.Hash.forEach(classMethods, function(method, methodName) {
table[methodName] = method table[methodName] = method
}) })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!