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

Commit 9ccd6864 by Mick Hansen

chore(instance/association): rename dao to instance

1 parent 0747c747
......@@ -76,23 +76,25 @@ var Mixin = module.exports = function(){}
* @param {boolean} [options.hooks=false] Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks
* @param {string} [options.as] The alias of this model. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the singularized version of target.name
* @param {string} [options.foreignKey] The name of the foreign key in the target table. Defaults to the name of source + primary key of source
* @param {string} [options.onDelete='SET NULL']
* @param {string} [options.onDelete='SET NULL']
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
*/
Mixin.hasOne = function(associatedModel, options) {
Mixin.hasOne = function(targetModel, options) {
var sourceModel = this
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = options.hooks
// the id is in the foreign table
var association = new HasOne(this, associatedModel, Utils._.extend(options, this.options))
this.associations[association.associationAccessor] = association.injectAttributes()
var association = new HasOne(sourceModel, targetModel, Utils._.extend(options, sourceModel.options))
sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype);
association.injectSetter(this.DAO.prototype);
association.injectCreator(this.DAO.prototype);
association.injectGetter(sourceModel.Instance.prototype);
association.injectSetter(sourceModel.Instance.prototype);
association.injectCreator(sourceModel.Instance.prototype);
return association
}
......@@ -119,19 +121,21 @@ Mixin.hasOne = function(associatedModel, options) {
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
*/
Mixin.belongsTo = function(associatedModel, options) {
Mixin.belongsTo = function(targetModel, options) {
var sourceModel = this
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = options.hooks
// the id is in this table
var association = new BelongsTo(this, associatedModel, Utils._.extend(options, this.options))
this.associations[association.associationAccessor] = association.injectAttributes()
var association = new BelongsTo(sourceModel, targetModel, Utils._.extend(options, sourceModel.options))
sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype)
association.injectSetter(this.DAO.prototype)
association.injectCreator(this.DAO.prototype)
association.injectGetter(sourceModel.Instance.prototype)
association.injectSetter(sourceModel.Instance.prototype)
association.injectCreator(sourceModel.Instance.prototype)
return association
}
......@@ -203,21 +207,23 @@ Mixin.belongsTo = function(associatedModel, options) {
* @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key.
*/
Mixin.hasMany = function(associatedModel, options) {
Mixin.hasMany = function(targetModel, options) {
var sourceModel = this
// Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = options.hooks
options = Utils._.extend(options, Utils._.omit(this.options, ['hooks']))
options = Utils._.extend(options, Utils._.omit(sourceModel.options, ['hooks']))
// the id is in the foreign table or in a connecting table
var association = new HasMany(this, associatedModel, options)
this.associations[association.associationAccessor] = association.injectAttributes()
var association = new HasMany(sourceModel, targetModel, options)
sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype)
association.injectSetter(this.DAO.prototype)
association.injectCreator(this.DAO.prototype)
association.injectGetter(sourceModel.Instance.prototype)
association.injectSetter(sourceModel.Instance.prototype)
association.injectCreator(sourceModel.Instance.prototype)
return association
}
......
......@@ -94,7 +94,7 @@ function extendModelValidations(modelInstance){
* @param {Object} options A dict with options.
* @constructor
*/
var DaoValidator = module.exports = function(modelInstance, options) {
var InstanceValidator = module.exports = function(modelInstance, options) {
options = options || {}
// assign defined and default options
......@@ -126,14 +126,14 @@ var DaoValidator = module.exports = function(modelInstance, options) {
}
/** @define {string} The error key for arguments as passed by custom validators */
DaoValidator.RAW_KEY_NAME = '__raw'
InstanceValidator.RAW_KEY_NAME = '__raw'
/**
* The main entry point for the Validation module, invoke to start the dance.
*
* @return {EventEmitter}
*/
DaoValidator.prototype.validate = function() {
InstanceValidator.prototype.validate = function() {
if (this.inProgress) {
throw new Error('Validations already in progress.');
}
......@@ -163,7 +163,7 @@ DaoValidator.prototype.validate = function() {
*
* @return {Promise}
*/
DaoValidator.prototype.hookValidate = function() {
InstanceValidator.prototype.hookValidate = function() {
var self = this
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance).then(function () {
return self.validate().then(function (error) {
......@@ -182,7 +182,7 @@ DaoValidator.prototype.hookValidate = function() {
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle().
* @private
*/
DaoValidator.prototype._builtinValidators = function() {
InstanceValidator.prototype._builtinValidators = function() {
var self = this
// promisify all attribute invocations
......@@ -213,7 +213,7 @@ DaoValidator.prototype._builtinValidators = function() {
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle().
* @private
*/
DaoValidator.prototype._customValidators = function() {
InstanceValidator.prototype._customValidators = function() {
var validators = [];
var self = this;
......@@ -239,7 +239,7 @@ DaoValidator.prototype._customValidators = function() {
* auto populates error on this.error local object.
* @private
*/
DaoValidator.prototype._builtinAttrValidate = function(value, field) {
InstanceValidator.prototype._builtinAttrValidate = function(value, field) {
var self = this;
// check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') {
......@@ -277,7 +277,7 @@ DaoValidator.prototype._builtinAttrValidate = function(value, field) {
* @return {Promise} A promise.
* @private
*/
DaoValidator.prototype._invokeCustomValidator = Promise.method(function(validator, validatorType, optAttrDefined, optValue, optField) {
InstanceValidator.prototype._invokeCustomValidator = Promise.method(function(validator, validatorType, optAttrDefined, optValue, optField) {
var validatorFunction = null // the validation function to call
var isAsync = false
......@@ -319,7 +319,7 @@ DaoValidator.prototype._invokeCustomValidator = Promise.method(function(validato
* @return {Object} An object with specific keys to invoke the validator.
* @private
*/
DaoValidator.prototype._invokeBuiltinValidator = Promise.method(function(value, test, validatorType, field) {
InstanceValidator.prototype._invokeBuiltinValidator = Promise.method(function(value, test, validatorType, field) {
// check if Validator knows that kind of validation test
if (typeof Validator[validatorType] !== 'function') {
......@@ -352,7 +352,7 @@ DaoValidator.prototype._invokeBuiltinValidator = Promise.method(function(value,
* @param {*} value anything.
* @private
*/
DaoValidator.prototype._validateSchema = function(rawAttribute, field, value) {
InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
......@@ -390,7 +390,7 @@ DaoValidator.prototype._validateSchema = function(rawAttribute, field, value) {
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private
*/
DaoValidator.prototype._handleSettledResult = function(field, promiseInspections) {
InstanceValidator.prototype._handleSettledResult = function(field, promiseInspections) {
var self = this;
promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) {
......@@ -408,14 +408,14 @@ DaoValidator.prototype._handleSettledResult = function(field, promiseInspections
* @param {Error|string} rawError The original error.
* @private
*/
DaoValidator.prototype._pushError = function(isBuiltin, errorKey, rawError) {
InstanceValidator.prototype._pushError = function(isBuiltin, errorKey, rawError) {
if (!this.errors.hasOwnProperty(errorKey)) {
this.errors[errorKey] = [];
}
var error = new sequelizeError.ValidationError()
error[DaoValidator.RAW_KEY_NAME] = rawError
error[InstanceValidator.RAW_KEY_NAME] = rawError
error.message = rawError.message || rawError || 'Validation error'
this.errors[errorKey].push(error);
......
var Utils = require("./utils")
, DAO = require("./dao")
, Instance = require("./instance")
, DataTypes = require("./data-types")
, Util = require('util')
, sql = require('sql')
......@@ -239,12 +239,12 @@ module.exports = (function() {
Utils.injectScope.call(this, this.options.defaultScope)
}
// DAO prototype
this.DAO = function() {
DAO.apply(this, arguments);
// Instance prototype
this.Instance = this.DAO = function() {
Instance.apply(this, arguments);
}
Util.inherits(this.DAO, DAO);
Util.inherits(this.Instance, Instance);
this._readOnlyAttributes = Utils._.values(this._timestampAttributes)
this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length
......@@ -254,7 +254,7 @@ module.exports = (function() {
if (this.options.instanceMethods) {
Utils._.each(this.options.instanceMethods, function(fct, name) {
self.DAO.prototype[name] = fct
self.Instance.prototype[name] = fct
})
}
......@@ -264,7 +264,7 @@ module.exports = (function() {
this._dateAttributes = []
this._hstoreAttributes = []
this._defaultValues = {}
this.DAO.prototype.validators = {}
this.Instance.prototype.validators = {}
Utils._.each(this.rawAttributes, function (definition, name) {
if (((definition === DataTypes.BOOLEAN) || (definition.type === DataTypes.BOOLEAN))) {
......@@ -282,7 +282,7 @@ module.exports = (function() {
}
if (definition.hasOwnProperty('validate')) {
self.DAO.prototype.validators[name] = definition.validate;
self.Instance.prototype.validators[name] = definition.validate;
}
})
......@@ -301,7 +301,7 @@ module.exports = (function() {
return self._hstoreAttributes.indexOf(key) !== -1
})
this.DAO.prototype.Model = this
this.Instance.prototype.Model = this
this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues)
......@@ -312,13 +312,13 @@ module.exports = (function() {
var self = this
, attributeManipulation = {};
this.DAO.prototype._customGetters = {}
this.DAO.prototype._customSetters = {}
this.Instance.prototype._customGetters = {}
this.Instance.prototype._customSetters = {}
Utils._.each(['get', 'set'], function(type) {
var opt = type + 'terMethods'
, funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {})
, _custom = type === 'get' ? self.DAO.prototype._customGetters : self.DAO.prototype._customSetters
, _custom = type === 'get' ? self.Instance.prototype._customGetters : self.Instance.prototype._customSetters
Utils._.each(funcs, function (method, attribute) {
_custom[attribute] = method
......@@ -366,15 +366,15 @@ module.exports = (function() {
})
})
this.DAO.prototype._hasCustomGetters = Object.keys(this.DAO.prototype._customGetters).length
this.DAO.prototype._hasCustomSetters = Object.keys(this.DAO.prototype._customSetters).length
this.Instance.prototype._hasCustomGetters = Object.keys(this.Instance.prototype._customGetters).length
this.Instance.prototype._hasCustomSetters = Object.keys(this.Instance.prototype._customSetters).length
Object.defineProperties(this.DAO.prototype, attributeManipulation)
Object.defineProperties(this.Instance.prototype, attributeManipulation)
this.DAO.prototype.rawAttributes = this.rawAttributes;
this.DAO.prototype.attributes = Object.keys(this.DAO.prototype.rawAttributes)
this.DAO.prototype._isAttribute = Utils._.memoize(function (key) {
return self.DAO.prototype.attributes.indexOf(key) !== -1
this.Instance.prototype.rawAttributes = this.rawAttributes;
this.Instance.prototype.attributes = Object.keys(this.Instance.prototype.rawAttributes)
this.Instance.prototype._isAttribute = Utils._.memoize(function (key) {
return self.Instance.prototype.attributes.indexOf(key) !== -1
})
}
......@@ -640,7 +640,7 @@ module.exports = (function() {
* @param {String|Array|Sequelize.fn} [options.order] Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several columns / functions to order by. Each element can be further wrapped in a two-element array. The first element is the column / function to order by, the second is the direction. For example: `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not.
* @param {Number} [options.limit]
* @param {Number} [options.offset]
* @param {Object} [queryOptions] Set the query options, e.g. raw, specifying that you want raw data instead of built DAOs. See sequelize.query for options
* @param {Object} [queryOptions] Set the query options, e.g. raw, specifying that you want raw data instead of built Instances. See sequelize.query for options
* @param {Transaction} [queryOptions.transaction]
*
* @see {Sequelize#query}
......@@ -789,7 +789,7 @@ module.exports = (function() {
* @param {String} field The field to aggregate over. Can be a field name or *
* @param {String} aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param {Object} [options] Query options. See sequelize.query for full options
* @param {DataType|String} [options.dataType] The type of the result. If field is a field in the DAO, the default will be the type of that field, otherwise defaults to float.
* @param {DataType|String} [options.dataType] The type of the result. If field is a field in the Instance, the default will be the type of that field, otherwise defaults to float.
*
* @return {Promise}
*/
......@@ -927,7 +927,7 @@ module.exports = (function() {
* @param {Boolean} [options.isDirty=true]
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set`
*
* @return {DAO}
* @return {Instance}
*/
Model.prototype.build = function(values, options) {
if (Array.isArray(values)) {
......@@ -945,7 +945,7 @@ module.exports = (function() {
validateIncludedElements.call(this, options)
}
return new this.DAO(values, options)
return new this.Instance(values, options)
}
......@@ -970,8 +970,8 @@ module.exports = (function() {
/**
* Builds a new model instance and calls save on it.
* @see {DAO#build}
* @see {DAO#save}
* @see {Instance#build}
* @see {Instance#save}
*
* @param {Object} values
* @param {Object} [options]
......@@ -1098,13 +1098,13 @@ module.exports = (function() {
*
* The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. This is because MySQL
* and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records.
* To obtain DAOs for the newly created values, you will need to query for them again.
* To obtain Instances for the newly created values, you will need to query for them again.
*
* @param {Array} records List of objects (key/value pairs) to create instances from
* @param {Object} [options]
* @param {Array} [options.fields] Fields to insert (defaults to all fields)
* @param {Boolean} [options.validate=false] Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
* @param {Boolean} [options.hooks=false] Run before / after create hooks for each individual DAO? BulkCreate hooks will still be run.
* @param {Boolean} [options.hooks=false] Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run.
* @param {Boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by postgres)
*
* @return {Promise}
......@@ -1601,20 +1601,20 @@ module.exports = (function() {
tail[this._timestampAttributes.createdAt] = {
type: DataTypes.DATE,
allowNull: false,
_autoGenerated: true,
_autoGenerated: true
}
}
if (this._timestampAttributes.updatedAt) {
tail[this._timestampAttributes.updatedAt] = {
type: DataTypes.DATE,
allowNull: false,
_autoGenerated: true,
_autoGenerated: true
}
}
if (this._timestampAttributes.deletedAt) {
tail[this._timestampAttributes.deletedAt] = {
type: DataTypes.DATE,
_autoGenerated: true,
autoGenerated: true
}
}
......@@ -1647,7 +1647,7 @@ module.exports = (function() {
fields.forEach(function(field) {
if (this.autoIncrementField) {
throw new Error('Invalid DAO definition. Only one autoincrement field allowed.')
throw new Error('Invalid Instance definition. Only one autoincrement field allowed.')
} else {
this.autoIncrementField = field
}
......@@ -1877,7 +1877,7 @@ module.exports = (function() {
var optClone = function (options) {
return Utils._.cloneDeep(options, function (elem) {
// The DAOFactories used for include are pass by ref, so don't clone them.
// The InstanceFactories used for include are pass by ref, so don't clone them.
if (elem instanceof Model ||
elem instanceof Utils.col ||
elem instanceof Utils.literal ||
......
......@@ -96,7 +96,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
userscore: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }
})
}).to.throw(Error, 'Invalid DAO definition. Only one autoincrement field allowed.')
}).to.throw(Error, 'Invalid Instance definition. Only one autoincrement field allowed.')
done()
})
......@@ -1842,7 +1842,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
})
it("returns an instanceof DAO", function(done) {
var DAO = require(__dirname + "/../lib/dao")
var DAO = require(__dirname + "/../lib/instance")
this.User.where({ username: "foo" }).exec().success(function(users) {
expect(users[0]).to.be.instanceOf(DAO)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!