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

Commit 1b5f45fa by Sascha Depold

getting associations running

1 parent b9c7923e
...@@ -15,6 +15,7 @@ var classMethods = { ...@@ -15,6 +15,7 @@ var classMethods = {
TEXT: 'VARCHAR(4000)', TEXT: 'VARCHAR(4000)',
INTEGER: 'INT', INTEGER: 'INT',
DATE: 'DATETIME', DATE: 'DATETIME',
sqlQueryFor: function(command, values) { sqlQueryFor: function(command, values) {
var query = null var query = null
switch(command) { switch(command) {
...@@ -59,6 +60,32 @@ Sequelize.prototype = { ...@@ -59,6 +60,32 @@ Sequelize.prototype = {
return result return result
}, },
sync: function(callback) {
var finished = []
var tables = this.tables
SequelizeHelper.Hash.forEach(tables, function(table, tableName) {
table.constructor.sync(function() {
finished.push(true)
if(finished.length == SequelizeHelper.Hash.keys(tables).length)
callback()
})
})
},
drop: function(callback) {
var finished = []
var tables = this.tables
SequelizeHelper.Hash.forEach(tables, function(table, tableName) {
table.constructor.drop(function() {
finished.push(true)
if(finished.length == SequelizeHelper.Hash.keys(tables).length)
callback()
})
})
},
define: function(name, attributes) { define: function(name, attributes) {
attributes.createdAt = 'DATETIME NOT NULL' attributes.createdAt = 'DATETIME NOT NULL'
attributes.updatedAt = 'DATETIME NOT NULL' attributes.updatedAt = 'DATETIME NOT NULL'
......
...@@ -5,6 +5,10 @@ SequelizeHelper = { ...@@ -5,6 +5,10 @@ SequelizeHelper = {
}, },
SQL: { SQL: {
asTableIdentifier: function(name) {
return name.toLowerCase().replace(/s$/, "") + "Id"
},
asTableName: function(name) { asTableName: function(name) {
return name + "s" return name + "s"
}, },
...@@ -25,7 +29,7 @@ SequelizeHelper = { ...@@ -25,7 +29,7 @@ SequelizeHelper = {
result = [] result = []
SequelizeHelper.Hash.forEach(actualValues, function(value, key) { SequelizeHelper.Hash.forEach(actualValues, function(value, key) {
var dataType = object.attributes[key] var dataType = object.table.attributes[key]
result.push(SequelizeHelper.SQL.transformValueByDataType(value, dataType)) result.push(SequelizeHelper.SQL.transformValueByDataType(value, dataType))
}) })
......
...@@ -6,38 +6,62 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -6,38 +6,62 @@ SequelizeTable = function(sequelize, tableName, attributes) {
self[key] = value self[key] = value
}) })
this.id = null // specify id as null to declare this object as unsaved and as not present in the database this.id = null // specify id as null to declare this object as unsaved and as not present in the database
this.tableName = tableName this.table = table
this.attributes = attributes
table.associations.forEach(function(association) {
self[association.name] = function(callback) {
var myTableName = tableName.toLowerCase().replace(/s$/, "")
if(association.type = 'hasMany') {
var whereConditions = [myTableName+"Id", self.id].join("=")
return association.table.findAll({where: whereConditions})
}
}
})
} }
// class methods // class methods
var classMethods = { var classMethods = {
associations: [], associations: [],
attributes: attributes,
tableName: tableName,
isCrossAssociatedWith: function(_table) {
var result = false
_table.associations.forEach(function(association) {
if((association.table.tableName == table.tableName) && (association.type == 'hasMany'))
result = true
})
return result
},
sync: function(callback) { sync: function(callback) {
table.associations.forEach(function(association) {
switch(association.type) {
case 'hasMany':
if(association.table.isCrossAssociatedWith(association.table)) {
// many to many relation
} else {
// one to many relation
association.table.attributes[table.identifier] = Sequelize.INTEGER
}
break
case 'hasOne':
// e.g. assocTable.myTableId = Sequelize.INTEGER
association.table.attributes[table.identifier] = Sequelize.INTEGER
break
case 'belongsTo':
// e.g. table.dayId = Sequelize.INTEGER
table.attributes[table.identifier] = Sequelize.INTEGER
break
}
})
var fields = ["id INT NOT NULL auto_increment PRIMARY KEY"] var fields = ["id INT NOT NULL auto_increment PRIMARY KEY"]
SequelizeHelper.Hash.keys(attributes).forEach(function(name) { fields.push(name + " " + attributes[name]) }) SequelizeHelper.Hash.forEach(table.attributes, function(type, name) {
fields.push(name + " " + type)
})
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor( 'create', { table: tableName, fields: fields.join(', ') } ), Sequelize.sqlQueryFor( 'create', { table: table.tableName, fields: fields.join(', ') } ),
function() { if(callback) callback(table) } function() { if(callback) callback(table) }
) )
}, },
drop: function(callback) { drop: function(callback) {
var query = "DROP TABLE IF EXISTS " + tableName
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('drop', { table: tableName }), Sequelize.sqlQueryFor('drop', { table: table.tableName }),
function() { if(callback) callback(table) } function() { if(callback) callback(table) }
) )
}, },
...@@ -46,7 +70,9 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -46,7 +70,9 @@ SequelizeTable = function(sequelize, tableName, attributes) {
findAll: function(options, callback) { findAll: function(options, callback) {
// 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') ? SequelizeHelper.Hash.merge(options, { table: tableName }) : { table: tableName } var queryOptions = (typeof options == 'object')
? SequelizeHelper.Hash.merge(options, { table: table.tableName })
: { table: table.tableName }
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('select', queryOptions), Sequelize.sqlQueryFor('select', queryOptions),
...@@ -66,47 +92,74 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -66,47 +92,74 @@ SequelizeTable = function(sequelize, tableName, attributes) {
find: function(conditions, callback) { find: function(conditions, callback) {
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('select', { Sequelize.sqlQueryFor('select', {
table: tableName, where: SequelizeHelper.SQL.hashToWhereConditions(conditions, this.attributes), order: 'id DESC', limit: 1 table: table.tableName,
where: SequelizeHelper.SQL.hashToWhereConditions(conditions, table.attributes),
order: 'id DESC',
limit: 1
}), function(result) { }), function(result) {
if (callback) callback(table.sqlResultToObject(result[0])) var _result = result[0] ? table.sqlResultToObject(result[0]) : null
if (callback) callback(_result)
} }
) )
}, },
// TODO: mysql library currently doesn't support MYSQL_DATE!!! don't merge if fixed // TODO: mysql library currently doesn't support MYSQL_DATE!!! don't merge if fixed
sqlResultToObject: function(result) { sqlResultToObject: function(result) {
if(typeof result == undefined) return null
var object = new table(SequelizeHelper.Hash.merge({createdAt: new Date(), updatedAt: new Date()}, result, true)) var object = new table(SequelizeHelper.Hash.merge({createdAt: new Date(), updatedAt: new Date()}, result, true))
object.id = result.id object.id = result.id
return object return object
}, },
hasMany: function(assocName, table) { hasMany: function(assocName, _table) {
this.associations.push({ table.associations.push({
name: assocName, name: assocName,
table: table, table: _table,
type: 'hasMany' type: 'hasMany'
}) })
table.prototype[assocName] = function(callback) {
var whereConditions = [table.identifier, this.id].join("=")
_table.findAll({where: whereConditions}, callback)
}
return table return table
}, },
hasOne: function(assocName, table) { hasOne: function(assocName, _table) {
this.associations.push({ table.associations.push({
name: assocName, name: assocName,
table: table, table: _table,
type: 'hasOne' type: 'hasOne'
}) })
table.prototype[assocName] = function(callback) {
var whereConditions = {}
whereConditions[table.identifier] = this.id
_table.find(whereConditions, callback)
}
return table return table
}, },
belongsTo: function(assocName, table) { belongsTo: function(assocName, _table) {
this.associations.push({ table.associations.push({
name: assocName, name: assocName,
table: table, table: _table,
type: 'belongsTo' type: 'belongsTo'
}) })
table.prototype[assocName] = function(callback) {
var whereConditions = ["id", this[_table.identifier]].join("=")
_table.find({where: whereConditions}, callback)
}
return table return table
} }
} }
// don't put this into the hash!
classMethods.identifier = SequelizeHelper.SQL.asTableIdentifier(classMethods.tableName)
// instance methods // instance methods
table.prototype = { table.prototype = {
...@@ -114,7 +167,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -114,7 +167,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
var result = {} var result = {}
var self = this var self = this
SequelizeHelper.Hash.keys(attributes).forEach(function(attribute) { SequelizeHelper.Hash.keys(table.attributes).forEach(function(attribute) {
result[attribute] = self[attribute] result[attribute] = self[attribute]
}) })
...@@ -129,10 +182,10 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -129,10 +182,10 @@ SequelizeTable = function(sequelize, tableName, attributes) {
if(this.id == null) { if(this.id == null) {
this.createdAt = new Date() this.createdAt = new Date()
query = Sequelize.sqlQueryFor('insert', { query = Sequelize.sqlQueryFor('insert', {
table: this.tableName, fields: SequelizeHelper.SQL.fieldsForInsertQuery(this), values: SequelizeHelper.SQL.valuesForInsertQuery(this) table: table.tableName, fields: SequelizeHelper.SQL.fieldsForInsertQuery(this), values: SequelizeHelper.SQL.valuesForInsertQuery(this)
}) })
} else } else
query = Sequelize.sqlQueryFor('update', { table: this.tableName, values: SequelizeHelper.SQL.valuesForUpdate(this), id: this.id }) query = Sequelize.sqlQueryFor('update', { table: table.tableName, values: SequelizeHelper.SQL.valuesForUpdate(this), id: this.id })
sequelize.query(query, function() { sequelize.query(query, function() {
if(self.id == null) { if(self.id == null) {
...@@ -148,7 +201,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -148,7 +201,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
updateAttributes: function(newValues, callback) { updateAttributes: function(newValues, callback) {
var self = this var self = this
SequelizeHelper.Hash.keys(this.attributes).forEach(function(attribute) { SequelizeHelper.Hash.keys(table.attributes).forEach(function(attribute) {
if(newValues[attribute]) if(newValues[attribute])
self[attribute] = newValues[attribute] self[attribute] = newValues[attribute]
}) })
...@@ -157,7 +210,7 @@ SequelizeTable = function(sequelize, tableName, attributes) { ...@@ -157,7 +210,7 @@ SequelizeTable = function(sequelize, tableName, attributes) {
destroy: function(callback) { destroy: function(callback) {
sequelize.query( sequelize.query(
Sequelize.sqlQueryFor('delete', { table: this.tableName, id: this.id }), Sequelize.sqlQueryFor('delete', { table: table.tableName, id: this.id }),
callback callback
) )
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!