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

Commit 9ccd6864 by Mick Hansen

chore(instance/association): rename dao to instance

1 parent 0747c747
...@@ -76,23 +76,25 @@ var Mixin = module.exports = function(){} ...@@ -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 {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.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.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 {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. * @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) // Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {} options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks) options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = options.hooks options.useHooks = options.hooks
// the id is in the foreign table // the id is in the foreign table
var association = new HasOne(this, associatedModel, Utils._.extend(options, this.options)) var association = new HasOne(sourceModel, targetModel, Utils._.extend(options, sourceModel.options))
this.associations[association.associationAccessor] = association.injectAttributes() sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype); association.injectGetter(sourceModel.Instance.prototype);
association.injectSetter(this.DAO.prototype); association.injectSetter(sourceModel.Instance.prototype);
association.injectCreator(this.DAO.prototype); association.injectCreator(sourceModel.Instance.prototype);
return association return association
} }
...@@ -119,19 +121,21 @@ Mixin.hasOne = function(associatedModel, options) { ...@@ -119,19 +121,21 @@ Mixin.hasOne = function(associatedModel, options) {
* @param {string} [options.onUpdate='CASCADE'] * @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. * @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) // Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {} options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks) options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = options.hooks options.useHooks = options.hooks
// the id is in this table // the id is in this table
var association = new BelongsTo(this, associatedModel, Utils._.extend(options, this.options)) var association = new BelongsTo(sourceModel, targetModel, Utils._.extend(options, sourceModel.options))
this.associations[association.associationAccessor] = association.injectAttributes() sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype) association.injectGetter(sourceModel.Instance.prototype)
association.injectSetter(this.DAO.prototype) association.injectSetter(sourceModel.Instance.prototype)
association.injectCreator(this.DAO.prototype) association.injectCreator(sourceModel.Instance.prototype)
return association return association
} }
...@@ -203,21 +207,23 @@ Mixin.belongsTo = function(associatedModel, options) { ...@@ -203,21 +207,23 @@ Mixin.belongsTo = function(associatedModel, options) {
* @param {string} [options.onUpdate='CASCADE'] * @param {string} [options.onUpdate='CASCADE']
* @param {boolean} [options.constraints=true] Should on update and on delete constraints be enabled on the foreign key. * @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) // Since this is a mixin, we'll need a unique variable name for hooks (since Model will override our hooks option)
options = options || {} options = options || {}
options.hooks = options.hooks === undefined ? false : Boolean(options.hooks) options.hooks = options.hooks === undefined ? false : Boolean(options.hooks)
options.useHooks = 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 // the id is in the foreign table or in a connecting table
var association = new HasMany(this, associatedModel, options) var association = new HasMany(sourceModel, targetModel, options)
this.associations[association.associationAccessor] = association.injectAttributes() sourceModel.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype) association.injectGetter(sourceModel.Instance.prototype)
association.injectSetter(this.DAO.prototype) association.injectSetter(sourceModel.Instance.prototype)
association.injectCreator(this.DAO.prototype) association.injectCreator(sourceModel.Instance.prototype)
return association return association
} }
......
...@@ -94,7 +94,7 @@ function extendModelValidations(modelInstance){ ...@@ -94,7 +94,7 @@ function extendModelValidations(modelInstance){
* @param {Object} options A dict with options. * @param {Object} options A dict with options.
* @constructor * @constructor
*/ */
var DaoValidator = module.exports = function(modelInstance, options) { var InstanceValidator = module.exports = function(modelInstance, options) {
options = options || {} options = options || {}
// assign defined and default options // assign defined and default options
...@@ -126,14 +126,14 @@ var DaoValidator = module.exports = function(modelInstance, options) { ...@@ -126,14 +126,14 @@ var DaoValidator = module.exports = function(modelInstance, options) {
} }
/** @define {string} The error key for arguments as passed by custom validators */ /** @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. * The main entry point for the Validation module, invoke to start the dance.
* *
* @return {EventEmitter} * @return {EventEmitter}
*/ */
DaoValidator.prototype.validate = function() { InstanceValidator.prototype.validate = function() {
if (this.inProgress) { if (this.inProgress) {
throw new Error('Validations already in progress.'); throw new Error('Validations already in progress.');
} }
...@@ -163,7 +163,7 @@ DaoValidator.prototype.validate = function() { ...@@ -163,7 +163,7 @@ DaoValidator.prototype.validate = function() {
* *
* @return {Promise} * @return {Promise}
*/ */
DaoValidator.prototype.hookValidate = function() { InstanceValidator.prototype.hookValidate = function() {
var self = this var self = this
return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance).then(function () { return self.modelInstance.Model.runHooks('beforeValidate', self.modelInstance).then(function () {
return self.validate().then(function (error) { return self.validate().then(function (error) {
...@@ -182,7 +182,7 @@ DaoValidator.prototype.hookValidate = function() { ...@@ -182,7 +182,7 @@ DaoValidator.prototype.hookValidate = function() {
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle(). * @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle().
* @private * @private
*/ */
DaoValidator.prototype._builtinValidators = function() { InstanceValidator.prototype._builtinValidators = function() {
var self = this var self = this
// promisify all attribute invocations // promisify all attribute invocations
...@@ -213,7 +213,7 @@ DaoValidator.prototype._builtinValidators = function() { ...@@ -213,7 +213,7 @@ DaoValidator.prototype._builtinValidators = function() {
* @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle(). * @return {Promise(Array.<Promise.PromiseInspection>)} A promise from .settle().
* @private * @private
*/ */
DaoValidator.prototype._customValidators = function() { InstanceValidator.prototype._customValidators = function() {
var validators = []; var validators = [];
var self = this; var self = this;
...@@ -239,7 +239,7 @@ DaoValidator.prototype._customValidators = function() { ...@@ -239,7 +239,7 @@ DaoValidator.prototype._customValidators = function() {
* auto populates error on this.error local object. * auto populates error on this.error local object.
* @private * @private
*/ */
DaoValidator.prototype._builtinAttrValidate = function(value, field) { InstanceValidator.prototype._builtinAttrValidate = function(value, field) {
var self = this; var self = this;
// check if value is null (if null not allowed the Schema pass will capture it) // check if value is null (if null not allowed the Schema pass will capture it)
if (value === null || typeof value === 'undefined') { if (value === null || typeof value === 'undefined') {
...@@ -277,7 +277,7 @@ DaoValidator.prototype._builtinAttrValidate = function(value, field) { ...@@ -277,7 +277,7 @@ DaoValidator.prototype._builtinAttrValidate = function(value, field) {
* @return {Promise} A promise. * @return {Promise} A promise.
* @private * @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 validatorFunction = null // the validation function to call
var isAsync = false var isAsync = false
...@@ -319,7 +319,7 @@ DaoValidator.prototype._invokeCustomValidator = Promise.method(function(validato ...@@ -319,7 +319,7 @@ DaoValidator.prototype._invokeCustomValidator = Promise.method(function(validato
* @return {Object} An object with specific keys to invoke the validator. * @return {Object} An object with specific keys to invoke the validator.
* @private * @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 // check if Validator knows that kind of validation test
if (typeof Validator[validatorType] !== 'function') { if (typeof Validator[validatorType] !== 'function') {
...@@ -352,7 +352,7 @@ DaoValidator.prototype._invokeBuiltinValidator = Promise.method(function(value, ...@@ -352,7 +352,7 @@ DaoValidator.prototype._invokeBuiltinValidator = Promise.method(function(value,
* @param {*} value anything. * @param {*} value anything.
* @private * @private
*/ */
DaoValidator.prototype._validateSchema = function(rawAttribute, field, value) { InstanceValidator.prototype._validateSchema = function(rawAttribute, field, value) {
var error var error
if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) { if (rawAttribute.allowNull === false && ((value === null) || (value === undefined))) {
...@@ -390,7 +390,7 @@ DaoValidator.prototype._validateSchema = function(rawAttribute, field, value) { ...@@ -390,7 +390,7 @@ DaoValidator.prototype._validateSchema = function(rawAttribute, field, value) {
* @param {Array.<Promise.PromiseInspection>} Promise inspection objects. * @param {Array.<Promise.PromiseInspection>} Promise inspection objects.
* @private * @private
*/ */
DaoValidator.prototype._handleSettledResult = function(field, promiseInspections) { InstanceValidator.prototype._handleSettledResult = function(field, promiseInspections) {
var self = this; var self = this;
promiseInspections.forEach(function(promiseInspection) { promiseInspections.forEach(function(promiseInspection) {
if (promiseInspection.isRejected()) { if (promiseInspection.isRejected()) {
...@@ -408,14 +408,14 @@ DaoValidator.prototype._handleSettledResult = function(field, promiseInspections ...@@ -408,14 +408,14 @@ DaoValidator.prototype._handleSettledResult = function(field, promiseInspections
* @param {Error|string} rawError The original error. * @param {Error|string} rawError The original error.
* @private * @private
*/ */
DaoValidator.prototype._pushError = function(isBuiltin, errorKey, rawError) { InstanceValidator.prototype._pushError = function(isBuiltin, errorKey, rawError) {
if (!this.errors.hasOwnProperty(errorKey)) { if (!this.errors.hasOwnProperty(errorKey)) {
this.errors[errorKey] = []; this.errors[errorKey] = [];
} }
var error = new sequelizeError.ValidationError() var error = new sequelizeError.ValidationError()
error[DaoValidator.RAW_KEY_NAME] = rawError error[InstanceValidator.RAW_KEY_NAME] = rawError
error.message = rawError.message || rawError || 'Validation error' error.message = rawError.message || rawError || 'Validation error'
this.errors[errorKey].push(error); this.errors[errorKey].push(error);
......
var Utils = require("./utils") var Utils = require("./utils")
, Mixin = require("./associations/mixin") , Mixin = require("./associations/mixin")
, DaoValidator = require("./dao-validator") , InstanceValidator = require("./instance-validator")
, DataTypes = require("./data-types") , DataTypes = require("./data-types")
, _ = require('lodash') , _ = require('lodash')
, defaultsOptions = { raw: true } , defaultsOptions = { raw: true }
module.exports = (function() { module.exports = (function() {
/** /**
* This class represents an single instance, a database row. You might see it referred to as both DAO and instance. You should not * This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
* instantiate the DAO class directly, instead you access it using the finder and creation methods on the model. * instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.
* *
* DAO instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance. * Instance instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance.
* By default, the values from dataValues can also be accessed directly from the DAO, that is: * By default, the values from dataValues can also be accessed directly from the Instance, that is:
* ```js * ```js
* instance.field * instance.field
* // is the same as * // is the same as
...@@ -24,9 +24,9 @@ module.exports = (function() { ...@@ -24,9 +24,9 @@ module.exports = (function() {
* Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters. * Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
* *
* @see {Sequelize#define} for more information about getters and setters * @see {Sequelize#define} for more information about getters and setters
* @class DAO * @class Instance
*/ */
var DAO = function(values, options) { var Instance = function(values, options) {
this.dataValues = {} this.dataValues = {}
this._previousDataValues = {} this._previousDataValues = {}
this.__options = this.Model.options this.__options = this.Model.options
...@@ -56,11 +56,11 @@ module.exports = (function() { ...@@ -56,11 +56,11 @@ module.exports = (function() {
* @property sequelize * @property sequelize
* @return {Sequelize} * @return {Sequelize}
*/ */
Object.defineProperty(DAO.prototype, 'sequelize', { Object.defineProperty(Instance.prototype, 'sequelize', {
get: function(){ return this.Model.modelManager.sequelize } get: function(){ return this.Model.modelManager.sequelize }
}) })
Object.defineProperty(DAO.prototype, 'QueryInterface', { Object.defineProperty(Instance.prototype, 'QueryInterface', {
get: function(){ return this.sequelize.getQueryInterface() } get: function(){ return this.sequelize.getQueryInterface() }
}) })
...@@ -69,19 +69,19 @@ module.exports = (function() { ...@@ -69,19 +69,19 @@ module.exports = (function() {
* @property isDeleted * @property isDeleted
* @return {Boolean} * @return {Boolean}
*/ */
Object.defineProperty(DAO.prototype, 'isDeleted', { Object.defineProperty(Instance.prototype, 'isDeleted', {
get: function() { get: function() {
return this.Model._timestampAttributes.deletedAt && this.dataValues[this.Model._timestampAttributes.deletedAt] !== null return this.Model._timestampAttributes.deletedAt && this.dataValues[this.Model._timestampAttributes.deletedAt] !== null
} }
}) })
/** /**
* Get the values of this DAO. Proxies to `this.get` * Get the values of this Instance. Proxies to `this.get`
* @see {DAO#get} * @see {Instance#get}
* @property values * @property values
* @return {Object} * @return {Object}
*/ */
Object.defineProperty(DAO.prototype, 'values', { Object.defineProperty(Instance.prototype, 'values', {
get: function() { get: function() {
return this.get() return this.get()
} }
...@@ -90,11 +90,11 @@ module.exports = (function() { ...@@ -90,11 +90,11 @@ module.exports = (function() {
/** /**
* A getter for `this.changed()`. Returns true if any keys have changed. * A getter for `this.changed()`. Returns true if any keys have changed.
* *
* @see {DAO#changed} * @see {Instance#changed}
* @property isDirty * @property isDirty
* @return {Boolean} * @return {Boolean}
*/ */
Object.defineProperty(DAO.prototype, 'isDirty', { Object.defineProperty(Instance.prototype, 'isDirty', {
get: function() { get: function() {
return !!this.changed() return !!this.changed()
} }
...@@ -106,7 +106,7 @@ module.exports = (function() { ...@@ -106,7 +106,7 @@ module.exports = (function() {
* @property primaryKeyValues * @property primaryKeyValues
* @return {Object} * @return {Object}
*/ */
Object.defineProperty(DAO.prototype, 'primaryKeyValues', { Object.defineProperty(Instance.prototype, 'primaryKeyValues', {
get: function() { get: function() {
var result = {} var result = {}
, self = this , self = this
...@@ -119,7 +119,7 @@ module.exports = (function() { ...@@ -119,7 +119,7 @@ module.exports = (function() {
} }
}) })
Object.defineProperty(DAO.prototype, "identifiers", { Object.defineProperty(Instance.prototype, "identifiers", {
get: function() { get: function() {
var primaryKeys = Object.keys(this.Model.primaryKeys) var primaryKeys = Object.keys(this.Model.primaryKeys)
, result = {} , result = {}
...@@ -138,7 +138,7 @@ module.exports = (function() { ...@@ -138,7 +138,7 @@ module.exports = (function() {
* @param {String} key * @param {String} key
* @return {any} * @return {any}
*/ */
DAO.prototype.getDataValue = function(key) { Instance.prototype.getDataValue = function(key) {
return this.dataValues[key] return this.dataValues[key]
} }
...@@ -148,7 +148,7 @@ module.exports = (function() { ...@@ -148,7 +148,7 @@ module.exports = (function() {
* @param {String} key * @param {String} key
* @param {any} value * @param {any} value
*/ */
DAO.prototype.setDataValue = function(key, value) { Instance.prototype.setDataValue = function(key, value) {
this.dataValues[key] = value this.dataValues[key] = value
} }
...@@ -160,7 +160,7 @@ module.exports = (function() { ...@@ -160,7 +160,7 @@ module.exports = (function() {
* @param {String} [key] * @param {String} [key]
* @return {Object|any} * @return {Object|any}
*/ */
DAO.prototype.get = function (key) { Instance.prototype.get = function (key) {
if (key) { if (key) {
if (this._customGetters[key]) { if (this._customGetters[key]) {
return this._customGetters[key].call(this, key) return this._customGetters[key].call(this, key)
...@@ -209,7 +209,7 @@ module.exports = (function() { ...@@ -209,7 +209,7 @@ module.exports = (function() {
* @param {Object} [options.include] * @param {Object} [options.include]
* @alias setAttributes * @alias setAttributes
*/ */
DAO.prototype.set = function (key, value, options) { Instance.prototype.set = function (key, value, options) {
var values var values
, originalValue , originalValue
, keys , keys
...@@ -324,7 +324,7 @@ module.exports = (function() { ...@@ -324,7 +324,7 @@ module.exports = (function() {
* @param {String} [key] * @param {String} [key]
* @return {Boolean|Array} * @return {Boolean|Array}
*/ */
DAO.prototype.changed = function(key) { Instance.prototype.changed = function(key) {
if (key) { if (key) {
if (this.Model._isDateAttribute(key) && this._previousDataValues[key] && this.dataValues[key]) { if (this.Model._isDateAttribute(key) && this._previousDataValues[key] && this.dataValues[key]) {
return this._previousDataValues[key].valueOf() !== this.dataValues[key].valueOf() return this._previousDataValues[key].valueOf() !== this.dataValues[key].valueOf()
...@@ -343,13 +343,13 @@ module.exports = (function() { ...@@ -343,13 +343,13 @@ module.exports = (function() {
* @param {String} key * @param {String} key
* @return {Boolean} * @return {Boolean}
*/ */
DAO.prototype.previous = function(key) { Instance.prototype.previous = function(key) {
return this._previousDataValues[key] return this._previousDataValues[key]
} }
DAO.prototype._setInclude = function(key, value, options) { Instance.prototype._setInclude = function(key, value, options) {
if (!Array.isArray(value)) value = [value] if (!Array.isArray(value)) value = [value]
if (value[0] instanceof DAO) { if (value[0] instanceof Instance) {
value = value.map(function (instance) { value = value.map(function (instance) {
return instance.dataValues return instance.dataValues
}) })
...@@ -401,7 +401,7 @@ module.exports = (function() { ...@@ -401,7 +401,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.save = function(fieldsOrOptions, options) { Instance.prototype.save = function(fieldsOrOptions, options) {
if (fieldsOrOptions instanceof Array) { if (fieldsOrOptions instanceof Array) {
fieldsOrOptions = { fields: fieldsOrOptions } fieldsOrOptions = { fields: fieldsOrOptions }
} }
...@@ -512,7 +512,7 @@ module.exports = (function() { ...@@ -512,7 +512,7 @@ module.exports = (function() {
hook = 'Update' hook = 'Update'
} }
// Add the values to the DAO // Add the values to the Instance
self.dataValues = _.extend(self.dataValues, values) self.dataValues = _.extend(self.dataValues, values)
return self.Model.runHooks('before' + hook, self).then(function () { return self.Model.runHooks('before' + hook, self).then(function () {
...@@ -546,7 +546,7 @@ module.exports = (function() { ...@@ -546,7 +546,7 @@ module.exports = (function() {
// Transfer database generated values (defaults, autoincrement, etc) // Transfer database generated values (defaults, autoincrement, etc)
values = _.extend(values, result.dataValues) values = _.extend(values, result.dataValues)
// Ensure new values are on DAO, and reset previousDataValues // Ensure new values are on Instance, and reset previousDataValues
result.dataValues = _.extend(result.dataValues, values) result.dataValues = _.extend(result.dataValues, values)
result._previousDataValues = _.clone(result.dataValues) result._previousDataValues = _.clone(result.dataValues)
...@@ -558,14 +558,14 @@ module.exports = (function() { ...@@ -558,14 +558,14 @@ module.exports = (function() {
/* /*
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object. * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* This is different from doing a `find(DAO.id)`, because that would create and return a new instance. With this method, * This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the DAO are updated with the new data and no new objects are created. * all references to the Instance are updated with the new data and no new objects are created.
* *
* @see {Model#find} * @see {Model#find}
* @param {Object} [options] Options that are passed on to `Model.find` * @param {Object} [options] Options that are passed on to `Model.find`
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.reload = function(options) { Instance.prototype.reload = function(options) {
var self = this var self = this
, where = [ , where = [
this.QueryInterface.quoteTable(this.Model.name) + '.' + this.QueryInterface.quoteIdentifier(this.Model.primaryKeyAttribute)+'=?', this.QueryInterface.quoteTable(this.Model.name) + '.' + this.QueryInterface.quoteIdentifier(this.Model.primaryKeyAttribute)+'=?',
...@@ -588,16 +588,16 @@ module.exports = (function() { ...@@ -588,16 +588,16 @@ module.exports = (function() {
* *
* @param {Object} [options] Options that are passed to the validator * @param {Object} [options] Options that are passed to the validator
* @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated * @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated
* @see {DAOValidator} * @see {InstanceValidator}
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.validate = function(options) { Instance.prototype.validate = function(options) {
return new DaoValidator(this, options).validate() return new InstanceValidator(this, options).validate()
} }
DAO.prototype.hookValidate = function(object) { Instance.prototype.hookValidate = function(object) {
var validator = new DaoValidator(this, object) var validator = new InstanceValidator(this, object)
return validator.hookValidate() return validator.hookValidate()
} }
...@@ -605,14 +605,14 @@ module.exports = (function() { ...@@ -605,14 +605,14 @@ module.exports = (function() {
/** /**
* This is the same as calling `setAttributes`, then calling `save`. * This is the same as calling `setAttributes`, then calling `save`.
* *
* @see {DAO#setAttributes} * @see {Instance#setAttributes}
* @see {DAO#save} * @see {Instance#save}
* @param {Object} updates See `setAttributes` * @param {Object} updates See `setAttributes`
* @param {Object} options See `save` * @param {Object} options See `save`
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.updateAttributes = function(updates, options) { Instance.prototype.updateAttributes = function(updates, options) {
if (options instanceof Array) { if (options instanceof Array) {
options = { fields: options } options = { fields: options }
} }
...@@ -621,7 +621,7 @@ module.exports = (function() { ...@@ -621,7 +621,7 @@ module.exports = (function() {
return this.save(options) return this.save(options)
} }
DAO.prototype.setAttributes = function(updates) { Instance.prototype.setAttributes = function(updates) {
return this.set(updates) return this.set(updates)
} }
...@@ -633,7 +633,7 @@ module.exports = (function() { ...@@ -633,7 +633,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.destroy = function(options) { Instance.prototype.destroy = function(options) {
options = options || {} options = options || {}
options.force = options.force === undefined ? false : Boolean(options.force) options.force = options.force === undefined ? false : Boolean(options.force)
...@@ -658,11 +658,11 @@ module.exports = (function() { ...@@ -658,11 +658,11 @@ module.exports = (function() {
} }
/** /**
* Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the DAO. The increment is done using a * Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
* ```sql * ```sql
* SET column = column + X * SET column = column + X
* ``` * ```
* query. To get the correct value after an increment into the DAO you should do a reload. * query. To get the correct value after an increment into the Instance you should do a reload.
* *
*```js *```js
* instance.increment('number') // increment number by 1 * instance.increment('number') // increment number by 1
...@@ -671,7 +671,7 @@ module.exports = (function() { ...@@ -671,7 +671,7 @@ module.exports = (function() {
* // `by` is ignored, since each column has its own value * // `by` is ignored, since each column has its own value
* ``` * ```
* *
* @see {DAO#reload} * @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given * @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given
* @param {Object} [options] * @param {Object} [options]
* @param {Integer} [options.by=1] The number to increment by * @param {Integer} [options.by=1] The number to increment by
...@@ -679,7 +679,7 @@ module.exports = (function() { ...@@ -679,7 +679,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.increment = function(fields, countOrOptions) { Instance.prototype.increment = function(fields, countOrOptions) {
Utils.validateParameter(countOrOptions, Object, { Utils.validateParameter(countOrOptions, Object, {
optional: true, optional: true,
deprecated: 'number', deprecated: 'number',
...@@ -723,11 +723,11 @@ module.exports = (function() { ...@@ -723,11 +723,11 @@ module.exports = (function() {
} }
/** /**
* Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the DAO. The decrement is done using a * Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
* ```sql * ```sql
* SET column = column - X * SET column = column - X
* ``` * ```
* query. To get the correct value after an decrement into the DAO you should do a reload. * query. To get the correct value after an decrement into the Instance you should do a reload.
* *
* ```js * ```js
* instance.decrement('number') // decrement number by 1 * instance.decrement('number') // decrement number by 1
...@@ -736,7 +736,7 @@ module.exports = (function() { ...@@ -736,7 +736,7 @@ module.exports = (function() {
* // `by` is ignored, since each column has its own value * // `by` is ignored, since each column has its own value
* ``` * ```
* *
* @see {DAO#reload} * @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given * @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
* @param {Object} [options] * @param {Object} [options]
* @param {Integer} [options.by=1] The number to decrement by * @param {Integer} [options.by=1] The number to decrement by
...@@ -744,7 +744,7 @@ module.exports = (function() { ...@@ -744,7 +744,7 @@ module.exports = (function() {
* *
* @return {Promise} * @return {Promise}
*/ */
DAO.prototype.decrement = function (fields, countOrOptions) { Instance.prototype.decrement = function (fields, countOrOptions) {
Utils.validateParameter(countOrOptions, Object, { Utils.validateParameter(countOrOptions, Object, {
optional: true, optional: true,
deprecated: 'number', deprecated: 'number',
...@@ -773,12 +773,12 @@ module.exports = (function() { ...@@ -773,12 +773,12 @@ module.exports = (function() {
} }
/** /**
* Check whether all values of this and `other` DAO are the same * Check whether all values of this and `other` Instance are the same
* *
* @param {DAO} other * @param {Instance} other
* @return {Boolean} * @return {Boolean}
*/ */
DAO.prototype.equals = function(other) { Instance.prototype.equals = function(other) {
var result = true var result = true
Utils._.each(this.dataValues, function(value, key) { Utils._.each(this.dataValues, function(value, key) {
...@@ -798,7 +798,7 @@ module.exports = (function() { ...@@ -798,7 +798,7 @@ module.exports = (function() {
* @param {Array} others * @param {Array} others
* @return {Boolean} * @return {Boolean}
*/ */
DAO.prototype.equalsOneOf = function(others) { Instance.prototype.equalsOneOf = function(others) {
var self = this var self = this
return _.any(others, function (other) { return _.any(others, function (other) {
...@@ -806,17 +806,17 @@ module.exports = (function() { ...@@ -806,17 +806,17 @@ module.exports = (function() {
}) })
} }
DAO.prototype.setValidators = function(attribute, validators) { Instance.prototype.setValidators = function(attribute, validators) {
this.validators[attribute] = validators this.validators[attribute] = validators
} }
/** /**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters. * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters.
* *
* @see {DAO#get} * @see {Instance#get}
* @return {object} * @return {object}
*/ */
DAO.prototype.toJSON = function() { Instance.prototype.toJSON = function() {
return this.get(); return this.get();
} }
...@@ -872,5 +872,5 @@ module.exports = (function() { ...@@ -872,5 +872,5 @@ module.exports = (function() {
this.set(values, options) this.set(values, options)
} }
return DAO return Instance
})() })()
var Utils = require("./utils") var Utils = require("./utils")
, DAO = require("./dao") , Instance = require("./instance")
, DataTypes = require("./data-types") , DataTypes = require("./data-types")
, Util = require('util') , Util = require('util')
, sql = require('sql') , sql = require('sql')
...@@ -239,12 +239,12 @@ module.exports = (function() { ...@@ -239,12 +239,12 @@ module.exports = (function() {
Utils.injectScope.call(this, this.options.defaultScope) Utils.injectScope.call(this, this.options.defaultScope)
} }
// DAO prototype // Instance prototype
this.DAO = function() { this.Instance = this.DAO = function() {
DAO.apply(this, arguments); Instance.apply(this, arguments);
} }
Util.inherits(this.DAO, DAO); Util.inherits(this.Instance, Instance);
this._readOnlyAttributes = Utils._.values(this._timestampAttributes) this._readOnlyAttributes = Utils._.values(this._timestampAttributes)
this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length this._hasReadOnlyAttributes = this._readOnlyAttributes && this._readOnlyAttributes.length
...@@ -254,7 +254,7 @@ module.exports = (function() { ...@@ -254,7 +254,7 @@ module.exports = (function() {
if (this.options.instanceMethods) { if (this.options.instanceMethods) {
Utils._.each(this.options.instanceMethods, function(fct, name) { 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() { ...@@ -264,7 +264,7 @@ module.exports = (function() {
this._dateAttributes = [] this._dateAttributes = []
this._hstoreAttributes = [] this._hstoreAttributes = []
this._defaultValues = {} this._defaultValues = {}
this.DAO.prototype.validators = {} this.Instance.prototype.validators = {}
Utils._.each(this.rawAttributes, function (definition, name) { Utils._.each(this.rawAttributes, function (definition, name) {
if (((definition === DataTypes.BOOLEAN) || (definition.type === DataTypes.BOOLEAN))) { if (((definition === DataTypes.BOOLEAN) || (definition.type === DataTypes.BOOLEAN))) {
...@@ -282,7 +282,7 @@ module.exports = (function() { ...@@ -282,7 +282,7 @@ module.exports = (function() {
} }
if (definition.hasOwnProperty('validate')) { 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() { ...@@ -301,7 +301,7 @@ module.exports = (function() {
return self._hstoreAttributes.indexOf(key) !== -1 return self._hstoreAttributes.indexOf(key) !== -1
}) })
this.DAO.prototype.Model = this this.Instance.prototype.Model = this
this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues) this._hasDefaultValues = !Utils._.isEmpty(this._defaultValues)
...@@ -312,13 +312,13 @@ module.exports = (function() { ...@@ -312,13 +312,13 @@ module.exports = (function() {
var self = this var self = this
, attributeManipulation = {}; , attributeManipulation = {};
this.DAO.prototype._customGetters = {} this.Instance.prototype._customGetters = {}
this.DAO.prototype._customSetters = {} this.Instance.prototype._customSetters = {}
Utils._.each(['get', 'set'], function(type) { Utils._.each(['get', 'set'], function(type) {
var opt = type + 'terMethods' var opt = type + 'terMethods'
, funcs = Utils._.clone(Utils._.isObject(self.options[opt]) ? self.options[opt] : {}) , 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) { Utils._.each(funcs, function (method, attribute) {
_custom[attribute] = method _custom[attribute] = method
...@@ -366,15 +366,15 @@ module.exports = (function() { ...@@ -366,15 +366,15 @@ module.exports = (function() {
}) })
}) })
this.DAO.prototype._hasCustomGetters = Object.keys(this.DAO.prototype._customGetters).length this.Instance.prototype._hasCustomGetters = Object.keys(this.Instance.prototype._customGetters).length
this.DAO.prototype._hasCustomSetters = Object.keys(this.DAO.prototype._customSetters).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.Instance.prototype.rawAttributes = this.rawAttributes;
this.DAO.prototype.attributes = Object.keys(this.DAO.prototype.rawAttributes) this.Instance.prototype.attributes = Object.keys(this.Instance.prototype.rawAttributes)
this.DAO.prototype._isAttribute = Utils._.memoize(function (key) { this.Instance.prototype._isAttribute = Utils._.memoize(function (key) {
return self.DAO.prototype.attributes.indexOf(key) !== -1 return self.Instance.prototype.attributes.indexOf(key) !== -1
}) })
} }
...@@ -640,7 +640,7 @@ module.exports = (function() { ...@@ -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 {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.limit]
* @param {Number} [options.offset] * @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] * @param {Transaction} [queryOptions.transaction]
* *
* @see {Sequelize#query} * @see {Sequelize#query}
...@@ -789,7 +789,7 @@ module.exports = (function() { ...@@ -789,7 +789,7 @@ module.exports = (function() {
* @param {String} field The field to aggregate over. Can be a field name or * * @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 {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 {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} * @return {Promise}
*/ */
...@@ -927,7 +927,7 @@ module.exports = (function() { ...@@ -927,7 +927,7 @@ module.exports = (function() {
* @param {Boolean} [options.isDirty=true] * @param {Boolean} [options.isDirty=true]
* @param {Array} [options.include] an array of include options - Used to build prefetched/included model instances. See `set` * @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) { Model.prototype.build = function(values, options) {
if (Array.isArray(values)) { if (Array.isArray(values)) {
...@@ -945,7 +945,7 @@ module.exports = (function() { ...@@ -945,7 +945,7 @@ module.exports = (function() {
validateIncludedElements.call(this, options) validateIncludedElements.call(this, options)
} }
return new this.DAO(values, options) return new this.Instance(values, options)
} }
...@@ -970,8 +970,8 @@ module.exports = (function() { ...@@ -970,8 +970,8 @@ module.exports = (function() {
/** /**
* Builds a new model instance and calls save on it. * Builds a new model instance and calls save on it.
* @see {DAO#build} * @see {Instance#build}
* @see {DAO#save} * @see {Instance#save}
* *
* @param {Object} values * @param {Object} values
* @param {Object} [options] * @param {Object} [options]
...@@ -1098,13 +1098,13 @@ module.exports = (function() { ...@@ -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 * 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. * 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 {Array} records List of objects (key/value pairs) to create instances from
* @param {Object} [options] * @param {Object} [options]
* @param {Array} [options.fields] Fields to insert (defaults to all fields) * @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.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) * @param {Boolean} [options.ignoreDuplicates=false] Ignore duplicate values for primary keys? (not supported by postgres)
* *
* @return {Promise} * @return {Promise}
...@@ -1599,22 +1599,22 @@ module.exports = (function() { ...@@ -1599,22 +1599,22 @@ module.exports = (function() {
if (this._timestampAttributes.createdAt) { if (this._timestampAttributes.createdAt) {
tail[this._timestampAttributes.createdAt] = { tail[this._timestampAttributes.createdAt] = {
type: DataTypes.DATE, type: DataTypes.DATE,
allowNull: false, allowNull: false,
_autoGenerated: true, _autoGenerated: true
} }
} }
if (this._timestampAttributes.updatedAt) { if (this._timestampAttributes.updatedAt) {
tail[this._timestampAttributes.updatedAt] = { tail[this._timestampAttributes.updatedAt] = {
type: DataTypes.DATE, type: DataTypes.DATE,
allowNull: false, allowNull: false,
_autoGenerated: true, _autoGenerated: true
} }
} }
if (this._timestampAttributes.deletedAt) { if (this._timestampAttributes.deletedAt) {
tail[this._timestampAttributes.deletedAt] = { tail[this._timestampAttributes.deletedAt] = {
type: DataTypes.DATE, type: DataTypes.DATE,
_autoGenerated: true, autoGenerated: true
} }
} }
...@@ -1647,7 +1647,7 @@ module.exports = (function() { ...@@ -1647,7 +1647,7 @@ module.exports = (function() {
fields.forEach(function(field) { fields.forEach(function(field) {
if (this.autoIncrementField) { 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 { } else {
this.autoIncrementField = field this.autoIncrementField = field
} }
...@@ -1877,7 +1877,7 @@ module.exports = (function() { ...@@ -1877,7 +1877,7 @@ module.exports = (function() {
var optClone = function (options) { var optClone = function (options) {
return Utils._.cloneDeep(options, function (elem) { 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 || if (elem instanceof Model ||
elem instanceof Utils.col || elem instanceof Utils.col ||
elem instanceof Utils.literal || elem instanceof Utils.literal ||
......
...@@ -96,7 +96,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -96,7 +96,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
userscore: { 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() done()
}) })
...@@ -1842,7 +1842,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () { ...@@ -1842,7 +1842,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
}) })
it("returns an instanceof DAO", function(done) { 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) { this.User.where({ username: "foo" }).exec().success(function(users) {
expect(users[0]).to.be.instanceOf(DAO) 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!