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

Commit e05fe99a by Sascha Depold

it is now possible to define default values

1 parent d235a604
var Sequelize = require(__dirname + "/../../lib/sequelize/Sequelize").Sequelize,
sequelize = new Sequelize("sequelize_test", "root", null),
User = sequelize.define('User', {
name: { type: Sequelize.STRING, allowNull: false},
isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, default: false }
}),
user = new User({ name: 'Someone' })
Sequelize.chainQueries([{drop: User}, {sync: User}], function() {
user.save(function(user) {
Sequelize.Helper.log("user.isAdmin should be the default value (false): " + user.isAdmin)
user.updateAttributes({ isAdmin: true }, function(user) {
Sequelize.Helper.log("user.isAdmin was overwritten to true: " + user.isAdmin)
})
})
})
\ No newline at end of file
......@@ -71,7 +71,9 @@ exports.Helper = function(Sequelize) {
return Helper.Hash.keys(object.values).join(", ")
},
transformValueByDataType: function(value, dataType) {
transformValueByDataType: function(value, attributeOptions) {
var dataType = attributeOptions.type
if((value == null)||(typeof value == 'undefined')||((dataType.indexOf(Sequelize.INTEGER) > -1) && isNaN(value)))
return "NULL"
......
......@@ -18,7 +18,7 @@ var classMethods = {
TEXT: 'TEXT',
INTEGER: 'INT',
DATE: 'DATETIME',
BOOLEAN: 'TINYINT(1) NOT NULL',
BOOLEAN: 'TINYINT(1)',
FLOAT: 'FLOAT',
sqlQueryFor: function(command, values) {
......@@ -77,12 +77,23 @@ var classMethods = {
Sequelize.prototype = {
define: function(name, attributes, options) {
var SequelizeTable = require(__dirname + "/SequelizeTable").SequelizeTable
var _attributes = {}
attributes.createdAt = 'DATETIME NOT NULL'
attributes.updatedAt = 'DATETIME NOT NULL'
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)
var table = new SequelizeTable(Sequelize, this, Sequelize.Helper.SQL.asTableName(name), attributes, options)
table.attributes = attributes
// refactor this to use the table's attributes
this.tables[name] = {klass: table, attributes: attributes}
table.sequelize = this
......@@ -156,35 +167,39 @@ Sequelize.prototype = {
query: function(queryString, callback) {
var fields = [],
values = [],
self = this,
connection = require(__dirname + "/../nodejs-mysql-native/index").createTCPClient(this.config.host, this.config.port)
connection.auto_prepare = true
connection
.auth(this.config.database, this.config.username, this.config.password)
.addListener("error", function(err) { callback(null, null, err) })
.addListener('authorized', function() {
if(!self.options.disableLogging)
Sequelize.Helper.log("Executing the query: " + queryString)
self = this
require(__dirname + "/../nodejs-mysql-native/index").createTCPClient(this.config.host, this.config.port, function(err, connection) {
if(err) callback(null, null, { message: "Unable to establish a connection to " + [self.config.host, self.config.port].join(":") })
else {
connection.auto_prepare = true
connection
.query(queryString)
.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)
.auth(self.config.database, self.config.username, self.config.password)
.addListener("error", function(err) { callback(null, null, err) })
.addListener('authorized', function() {
if(!self.options.disableLogging)
Sequelize.Helper.log("Executing the query: " + queryString)
connection
.query(queryString)
.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)
}
})
if(callback) callback(result, stats)
}
connection.close()
})
connection.close()
})
}
})
}
}
......
......@@ -11,17 +11,29 @@ exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes, o
options.instanceMethods = options.instanceMethods || {}
var table = function(values) {
var self = this
var self = this,
defaults = {}
// read all default values ...
Sequelize.Helper.Hash.forEach(table.attributes, function(options, key) {
if(typeof options.default != 'undefined') defaults[key] = options.default
})
// and merge them into the passed one
Sequelize.Helper.Hash.merge(defaults, values)
// now iterate over the values and assign them the current object
Sequelize.Helper.Hash.forEach(values, function(value, key) {
if(attributes[key]) {
if(attributes[key].indexOf(Sequelize.BOOLEAN) > -1)
if(attributes[key].type.indexOf(Sequelize.BOOLEAN) > -1)
self[key] = ((value == 1) || (value == true)) ? true : false
else if(attributes[key].indexOf(Sequelize.DATE) > -1)
else if(attributes[key].type.indexOf(Sequelize.DATE) > -1)
self[key] = (value instanceof Date) ? value : new Date(Date.parse(value))
else
self[key] = value
}
})
this.id = null // specify id as null to declare this object as unsaved and as not present in the database
this.table = table
}
......@@ -63,16 +75,16 @@ exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes, o
sequelize.define(Sequelize.Helper.SQL.manyToManyTableName(table, association.table), _attributes)
} else {
// one to many relation
association.table.attributes[table.identifier] = Sequelize.INTEGER
association.table.attributes[table.identifier] = {type: Sequelize.INTEGER}
}
break
case 'hasOne':
// e.g. assocTable.myTableId = Sequelize.INTEGER
association.table.attributes[table.identifier] = Sequelize.INTEGER
association.table.attributes[table.identifier] = {type: Sequelize.INTEGER}
break
case 'belongsTo':
// e.g. table.dayId = Sequelize.INTEGER
table.attributes[association.table.identifier] = Sequelize.INTEGER
table.attributes[association.table.identifier] = {type :Sequelize.INTEGER}
break
}
})
......@@ -82,8 +94,8 @@ exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes, o
/* returns: table, error */
sync: function(callback) {
var fields = ["id INT NOT NULL auto_increment PRIMARY KEY"]
Sequelize.Helper.Hash.forEach(table.attributes, function(type, name) {
fields.push(name + " " + type)
Sequelize.Helper.Hash.forEach(table.attributes, function(options, name) {
fields.push(name + " " + options.type)
})
sequelize.query(
......@@ -214,6 +226,7 @@ exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes, o
var whereConditions = [table.identifier, this.id].join("=")
_table.findAll({where: whereConditions}, callback)
}
table.prototype[Sequelize.Helper.SQL.addPrefix('set', assocName)] = function(objects, callback) {
var self = this
var objectIds = Sequelize.Helper.Array.map(objects, function(obj) { return obj.id })
......@@ -318,20 +331,48 @@ exports.SequelizeTable = function(Sequelize, sequelize, tableName, attributes, o
return result
},
get invalidFields() {
var result = [],
self = this
Sequelize.Helper.Hash.forEach(table.attributes, function(options, attribute) {
if(['createdAt', 'updatedAt'].indexOf(attribute) > -1) return
var allowsNull = ((typeof options.allowNull == 'undefined') || (options.allowNull !== false))
var hasDefault = (typeof options.default != 'undefined')
if(!allowsNull && !hasDefault && (typeof self[attribute] == 'undefined'))
result.push({ field: attribute, reason: 'The field does not allow NULL values and has no default!'})
})
return result
},
get isValid() {
return this.invalidFields.length == 0
},
save: function(callback) {
var query = null
var self = this
var query = null,
self = this
if(!this.isValid) {
var errorText = "The object is not valid! Invalid fields: " + Sequelize.Helper.Array.map(this.invalidFields, function(fieldHash) { return fieldHash.field }).join(", ")
throw new Error(errorText)
}
this.updatedAt = new Date()
if(this.id == null) {
this.createdAt = new Date()
query = Sequelize.sqlQueryFor('insert', {
table: table.tableName,
fields: Sequelize.Helper.SQL.fieldsForInsertQuery(this),
values: Sequelize.Helper.SQL.valuesForInsertQuery(this)
})
} else
} else {
query = Sequelize.sqlQueryFor('update', { table: table.tableName, values: Sequelize.Helper.SQL.valuesForUpdate(this), id: this.id })
}
sequelize.query(query, function(result, stats) {
self.id = self.id || stats.insert_id
......
......@@ -44,15 +44,15 @@ module.exports = {
assert.eql(result, 'name, createdAt, updatedAt')
},
'SQL: transformValueByDataType': function(assert) {
assert.equal(h.SQL.transformValueByDataType('asd', Sequelize.STRING), "'asd'")
assert.equal(h.SQL.transformValueByDataType('asd', Sequelize.TEXT), "'asd'")
assert.equal(h.SQL.transformValueByDataType(6, Sequelize.INTEGER), "6")
assert.equal(h.SQL.transformValueByDataType(null, Sequelize.INTEGER), "NULL")
assert.equal(h.SQL.transformValueByDataType(null, Sequelize.STRING), "NULL")
assert.equal(h.SQL.transformValueByDataType(null, Sequelize.TEXT), "NULL")
assert.equal(h.SQL.transformValueByDataType('asd', {type: Sequelize.STRING}), "'asd'")
assert.equal(h.SQL.transformValueByDataType('asd', {type: Sequelize.TEXT}), "'asd'")
assert.equal(h.SQL.transformValueByDataType(6, {type: Sequelize.INTEGER}), "6")
assert.equal(h.SQL.transformValueByDataType(null, {type: Sequelize.INTEGER}), "NULL")
assert.equal(h.SQL.transformValueByDataType(null, {type: Sequelize.STRING}), "NULL")
assert.equal(h.SQL.transformValueByDataType(null, {type: Sequelize.TEXT}), "NULL")
var d = new Date(Date.parse("Tue, 1 Jan 2000 00:00:00 GMT"))
assert.equal(h.SQL.transformValueByDataType(d, Sequelize.DATE), "'2000-01-01 01:00:00'")
assert.equal(h.SQL.transformValueByDataType(d, {type: Sequelize.DATE}), "'2000-01-01 01:00:00'")
},
'SQL: valuesForUpdate': function(assert) {
var s = new Sequelize('sequelize_test', 'test', 'test')
......
......@@ -5,7 +5,7 @@ var Day = s.define('Day', { name: Sequelize.TEXT })
module.exports = {
'constructor': function(assert) {
assert.eql(Day.associations, [])
assert.eql(Day.attributes, {"name":"TEXT","createdAt":"DATETIME NOT NULL","updatedAt":"DATETIME NOT NULL"})
assert.eql(Day.attributes, {"name": {type: "TEXT"},"createdAt": {type: "DATETIME", allowNull: false},"updatedAt": {type: "DATETIME", allowNull: false}})
assert.eql(Day.tableName, 'Days')
},
'new': function(assert) {
......@@ -193,7 +193,9 @@ module.exports = {
var assertMe = null
Sequelize.chainQueries([{sync: s2}, {drop: s2}, {sync: s2}, {save: task}, {save: deadline}], function() {
task.setDeadline(deadline, function(_deadline) { assertMe = _deadline })
task.setDeadline(deadline, function(_deadline) {
assertMe = _deadline
})
})
beforeExit(function() {
......
......@@ -25,12 +25,6 @@ module.exports = {
var Day = s.define('Day', { name: Sequelize.TEXT })
assert.equal(typeof Day, 'function')
},
'define should store attributes': function(assert) {
var Day = s.define('Day', { name: Sequelize.TEXT })
assert.isDefined(Day.attributes)
assert.isNotNull(Day.attributes)
assert.eql(Day.attributes, { name: Sequelize.TEXT, createdAt: "DATETIME NOT NULL", updatedAt: "DATETIME NOT NULL"})
},
'define should add new table to tables': function(assert) {
var Day = s.define('Day', { name: Sequelize.TEXT })
assert.includes(Sequelize.Helper.Hash.keys(Day.sequelize.tables), 'Day')
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!