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

Commit 57073848 by Mick Hansen

chore(model): rename daoFactory to model

1 parent 7aebecad
......@@ -4,7 +4,7 @@ Notice: All 1.7.x changes are present in 2.0.x aswell
#### Breaking changes
- Sequelize now returns promises instead of its custom event emitter from most calls. This affects methods that return multiple values (like `findOrCreate` or `findOrInitialize`). If your current callbacks do not accept the 2nd success parameter you might be seeing an array as the first param. Either use `.spread()` for these methods or add another argument to your callback: `.success(instance)` -> `.success(instance, created)`.
- `.success()`/`.done()` and any other non promise methods are now deprecated (we will keep the codebase around for a few versions though). on('sql') persists for debugging purposes.
- Model association calls (belongsTo/hasOne/hasMany) are no longer chainable.
- Model association calls (belongsTo/hasOne/hasMany) are no longer chainable. (this is to support being able to pass association references to include rather than model/as combinations)
# v2.0.0-dev11
### Caution: This release contains many changes and is highly experimental
......
......@@ -71,7 +71,7 @@ var Mixin = module.exports = function(){}
*
* All methods return an event emitter.
*
* @param {DAOFactory} target
* @param {Model} target
* @param {object} [options]
* @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
......@@ -80,14 +80,14 @@ var Mixin = module.exports = function(){}
* @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(associatedDAOFactory, options) {
// Since this is a mixin, we'll need a unique variable name for hooks (since DAOFactory will override our hooks option)
Mixin.hasOne = function(associatedModel, options) {
// 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, associatedDAOFactory, Utils._.extend(options, this.options))
var association = new HasOne(this, associatedModel, Utils._.extend(options, this.options))
this.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype);
......@@ -110,7 +110,7 @@ Mixin.hasOne = function(associatedDAOFactory, options) {
*
* All methods return an event emitter.
*
* @param {DAOFactory} target
* @param {Model} target
* @param {object} [options]
* @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
......@@ -119,14 +119,14 @@ Mixin.hasOne = function(associatedDAOFactory, 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(associatedDAOFactory, options) {
// Since this is a mixin, we'll need a unique variable name for hooks (since DAOFactory will override our hooks option)
Mixin.belongsTo = function(associatedModel, options) {
// 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, associatedDAOFactory, Utils._.extend(options, this.options))
var association = new BelongsTo(this, associatedModel, Utils._.extend(options, this.options))
this.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype)
......@@ -148,7 +148,7 @@ Mixin.belongsTo = function(associatedDAOFactory, options) {
* User.hasMany(Project)
* Project.hasMany(User)
* ```
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a DAOFactory as `through` in the options.
* By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as `through` in the options.
* The following methods are injected on the source:
*
......@@ -193,18 +193,18 @@ Mixin.belongsTo = function(associatedDAOFactory, options) {
* })
* ```
*
* @param {DAOFactory} target
* @param {Model} target
* @param {object} [options]
* @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 {DAOFactory|string} [options.through] The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @param {Model|string} [options.through] The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it.
* @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 source table. Defaults to the name of target + primary key of target
* @param {string} [options.onDelete='SET NULL|CASCADE'] Cascade if this is a n:m, and set null if it is a 1:m
* @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(associatedDAOFactory, options) {
// Since this is a mixin, we'll need a unique variable name for hooks (since DAOFactory will override our hooks option)
Mixin.hasMany = function(associatedModel, options) {
// 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
......@@ -212,7 +212,7 @@ Mixin.hasMany = function(associatedDAOFactory, options) {
options = Utils._.extend(options, Utils._.omit(this.options, ['hooks']))
// the id is in the foreign table or in a connecting table
var association = new HasMany(this, associatedDAOFactory, options)
var association = new HasMany(this, associatedModel, options)
this.associations[association.associationAccessor] = association.injectAttributes()
association.injectGetter(this.DAO.prototype)
......
......@@ -42,9 +42,9 @@ module.exports = (function() {
/**
* Returns the Model the instance was created from.
* @see {DAOFactory}
* @see {Model}
* @property Model
* @return DAOFactory
* @return Model
*/
initValues.call(this, values, options);
......@@ -59,7 +59,7 @@ module.exports = (function() {
* @return {Sequelize}
*/
Object.defineProperty(DAO.prototype, 'sequelize', {
get: function(){ return this.Model.daoFactoryManager.sequelize }
get: function(){ return this.Model.modelManager.sequelize }
})
Object.defineProperty(DAO.prototype, 'QueryInterface', {
......@@ -202,7 +202,7 @@ module.exports = (function() {
*
* Set can also be used to build instances for associations, if you have values for those. TODO - mick should probably write something here about how includes in set works - perhaps also even some tests?
*
* @see {DAOFactory#find} for more information about includes
* @see {Model#find} for more information about includes
* @param {String|Object} key
* @param {any} value
* @param {Object} [options]
......@@ -456,7 +456,7 @@ module.exports = (function() {
if (self.Model.rawAttributes.hasOwnProperty(attrName)) {
var definition = self.Model.rawAttributes[attrName]
, isEnum = !!definition.type && (definition.type.toString() === DataTypes.ENUM.toString())
, isMySQL = ['mysql', 'mariadb'].indexOf(self.Model.daoFactoryManager.sequelize.options.dialect) !== -1
, isMySQL = ['mysql', 'mariadb'].indexOf(self.Model.modelManager.sequelize.options.dialect) !== -1
, ciCollation = !!self.Model.options.collate && self.Model.options.collate.match(/_ci$/i)
, valueOutOfScope
......@@ -563,8 +563,8 @@ module.exports = (function() {
* This is different from doing a `find(DAO.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.
*
* @see {DAOFactory#find}
* @param {Object} [options] Options that are passed on to `DAOFactory.find`
* @see {Model#find}
* @param {Object} [options] Options that are passed on to `Model.find`
* @return {Promise}
*/
DAO.prototype.reload = function(options) {
......@@ -718,7 +718,7 @@ module.exports = (function() {
}
if (updatedAtAttr && !values[updatedAtAttr]) {
countOrOptions.attributes[updatedAtAttr] = Utils.now(this.Model.daoFactoryManager.sequelize.options.dialect)
countOrOptions.attributes[updatedAtAttr] = Utils.now(this.Model.modelManager.sequelize.options.dialect)
}
return this.QueryInterface.increment(this, this.QueryInterface.QueryGenerator.addSchema(this.Model.tableName, this.Model.options.schema), values, where, countOrOptions)
......
var Utils = require("../../utils")
, SqlString = require("../../sql-string")
, daoFactory = require("../../dao-factory")
, daoFactory = require("../../model")
, _ = require('lodash')
module.exports = (function() {
......@@ -591,7 +591,7 @@ module.exports = (function() {
, query
, limit = options.limit
, mainQueryItems = []
, mainAttributes = options.attributes
, mainAttributes = options.attributes && options.attributes.slice(0)
, mainJoinQueries = []
// We'll use a subquery if we have hasMany associations and a limit and a filtered/required association
, subQuery = limit && (options.hasIncludeWhere || options.hasIncludeRequired || options.hasMultiAssociation)
......
var Toposort = require('toposort-class')
, DaoFactory = require('./dao-factory')
, _ = require('lodash')
module.exports = (function() {
var DAOFactoryManager = function(sequelize) {
var ModelManager = function(sequelize) {
this.daos = []
this.sequelize = sequelize
}
DAOFactoryManager.prototype.addDAO = function(dao) {
ModelManager.prototype.addDAO = function(dao) {
this.daos.push(dao)
return dao
}
DAOFactoryManager.prototype.removeDAO = function(dao) {
ModelManager.prototype.removeDAO = function(dao) {
this.daos = this.daos.filter(function(_dao) {
return _dao.name != dao.name
})
}
DAOFactoryManager.prototype.getDAO = function(daoName, options) {
ModelManager.prototype.getDAO = function(daoName, options) {
options = options || {}
options.attribute = options.attribute || 'name'
......@@ -31,7 +30,7 @@ module.exports = (function() {
return !!dao ? dao[0] : null
}
DAOFactoryManager.prototype.__defineGetter__('all', function() {
ModelManager.prototype.__defineGetter__('all', function() {
return this.daos
})
......@@ -40,7 +39,7 @@ module.exports = (function() {
* take foreign key constraints into account so that dependencies are visited
* before dependents.
*/
DAOFactoryManager.prototype.forEachDAO = function(iterator, options) {
ModelManager.prototype.forEachDAO = function(iterator, options) {
var daos = {}
, sorter = new Toposort()
, sorted
......@@ -89,5 +88,5 @@ module.exports = (function() {
})
}
return DAOFactoryManager
return ModelManager
})()
......@@ -9,13 +9,13 @@ var Utils = require("./utils")
module.exports = (function() {
/**
* A DAOFactory represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
* A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and already created models can be loaded using `sequelize.import`
*
* @class DAOFactory
* @class Model
* @mixes Hooks
* @mixes Associations
*/
var DAOFactory = function(name, attributes, options) {
var Model = function(name, attributes, options) {
this.options = Utils._.extend({
timestamps: true,
createdAt: 'createdAt',
......@@ -39,6 +39,8 @@ module.exports = (function() {
}
}, options || {})
this.sequelize = options.sequelize
// error check options
Utils._.each(options.validate, function(validator, validatorType) {
if (Utils._.contains(Utils._.keys(attributes), validatorType)) {
......@@ -101,7 +103,7 @@ module.exports = (function() {
})
Object.keys(attributes).forEach(function(attrName) {
if (attributes[attrName].references instanceof DAOFactory) {
if (attributes[attrName].references instanceof Model) {
attributes[attrName].references = attributes[attrName].references.tableName
}
})
......@@ -109,6 +111,7 @@ module.exports = (function() {
this.options.hooks = this.replaceHookAliases(this.options.hooks)
this.rawAttributes = attributes
this.modelManager =
this.daoFactoryManager = null // defined in init function
this.associations = {}
this.scopeObj = {}
......@@ -119,7 +122,7 @@ module.exports = (function() {
* @property attributes
* @return {Object}
*/
Object.defineProperty(DAOFactory.prototype, 'attributes', {
Object.defineProperty(Model.prototype, 'attributes', {
get: function() {
return this.QueryGenerator.attributesToSQL(this.rawAttributes)
}
......@@ -130,15 +133,15 @@ module.exports = (function() {
* @property sequelize
* @return {Sequelize}
*/
Object.defineProperty(DAOFactory.prototype, 'sequelize', {
get: function() { return this.daoFactoryManager.sequelize }
Object.defineProperty(Model.prototype, 'sequelize', {
get: function() { return this.modelManager.sequelize }
})
Object.defineProperty(DAOFactory.prototype, 'QueryInterface', {
get: function() { return this.daoFactoryManager.sequelize.getQueryInterface() }
Object.defineProperty(Model.prototype, 'QueryInterface', {
get: function() { return this.modelManager.sequelize.getQueryInterface() }
})
Object.defineProperty(DAOFactory.prototype, 'QueryGenerator', {
Object.defineProperty(Model.prototype, 'QueryGenerator', {
get: function() { return this.QueryInterface.QueryGenerator }
})
......@@ -150,10 +153,10 @@ module.exports = (function() {
for (var methodName in instance) {
;(function(methodName) {
DAOFactory.prototype[methodName] = function() {
Model.prototype[methodName] = function() {
var dataset = this.dataset()
, result = dataset[methodName].apply(dataset, arguments)
, dialect = this.daoFactoryManager.sequelize.options.dialect
, dialect = this.modelManager.sequelize.options.dialect
, self = this
result.toSql = function() {
......@@ -176,10 +179,11 @@ module.exports = (function() {
}
})()
DAOFactory.prototype.init = function(daoFactoryManager) {
Model.prototype.init = function(modelManager) {
var self = this
this.daoFactoryManager = daoFactoryManager
this.modelManager =
this.daoFactoryManager = modelManager
this.primaryKeys = {}
self.options.uniqueKeys = {}
......@@ -304,7 +308,7 @@ module.exports = (function() {
return this
}
DAOFactory.prototype.refreshAttributes = function() {
Model.prototype.refreshAttributes = function() {
var self = this
, attributeManipulation = {};
......@@ -375,11 +379,11 @@ module.exports = (function() {
}
/**
* Sync this DAOFactory to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
* Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
* @see {Sequelize#sync} for options
* @return {Promise}
*/
DAOFactory.prototype.sync = function(options) {
Model.prototype.sync = function(options) {
options = Utils._.extend({}, this.options, options || {})
var self = this
......@@ -402,11 +406,11 @@ module.exports = (function() {
* @param {Boolean} [options.cascade=false] Also drop all objects depending on this table, such as views. Only works in postgres
* @return {Promise}
*/
DAOFactory.prototype.drop = function(options) {
Model.prototype.drop = function(options) {
return this.QueryInterface.dropTable(this.getTableName(), options)
}
DAOFactory.prototype.dropSchema = function(schema) {
Model.prototype.dropSchema = function(schema) {
return this.QueryInterface.dropSchema(schema)
}
......@@ -419,7 +423,7 @@ module.exports = (function() {
* @param {String} [options.schemaDelimiter='.'] The character(s) that separates the schema name from the table name
* @return this
*/
DAOFactory.prototype.schema = function(schema, options) {
Model.prototype.schema = function(schema, options) {
this.options.schema = schema
if (!!options) {
......@@ -441,7 +445,7 @@ module.exports = (function() {
*
* @return {String|Object}
*/
DAOFactory.prototype.getTableName = function() {
Model.prototype.getTableName = function() {
return this.QueryGenerator.addSchema(this)
}
......@@ -482,9 +486,9 @@ module.exports = (function() {
* ```
*
* @param {Array|Object|String|null} options* The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
* @return {DAOFactory} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
* @return {Model} A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
*/
DAOFactory.prototype.scope = function(option) {
Model.prototype.scope = function(option) {
var self = Object.create(this)
, type
, options
......@@ -566,7 +570,7 @@ module.exports = (function() {
return self
}
DAOFactory.prototype.all = function(options, queryOptions) {
Model.prototype.all = function(options, queryOptions) {
return this.findAll(options, queryOptions)
}
......@@ -632,7 +636,7 @@ module.exports = (function() {
* @param {Object} [options] A hash of options to describe the scope of the search
* @param {Object} [options.where] A hash of attributes to describe your search. See above for examples.
* @param {Array<String>} [options.attributes] A list of the attributes that you want to select
* @param {Array<Object|DAOFactory>} [options.include] A list of associations to eagerly load. Supported is either { include: [ DaoFactory1, DaoFactory2, ...] } or { include: [ { model: DaoFactory1, as: 'Alias' } ] }. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also specify `attributes` to specify what columns to load, `where` to limit the relations, and `include` to load further nested relations
* @param {Array<Object|Model>} [options.include] A list of associations to eagerly load. Supported is either { include: [ Model1, Model2, ...] } or { include: [ { model: Model1, as: 'Alias' } ] }. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also specify `attributes` to specify what columns to load, `where` to limit the relations, and `include` to load further nested relations
* @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]
......@@ -643,7 +647,7 @@ module.exports = (function() {
* @return {Promise}
* @alias all
*/
DAOFactory.prototype.findAll = function(options, queryOptions) {
Model.prototype.findAll = function(options, queryOptions) {
var hasJoin = false
, tableNames = { }
......@@ -678,7 +682,7 @@ module.exports = (function() {
}
//right now, the caller (has-many-double-linked) is in charge of the where clause
DAOFactory.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
Model.prototype.findAllJoin = function(joinTableName, options, queryOptions) {
var optcpy = Utils._.clone(options)
optcpy.attributes = optcpy.attributes || [this.QueryInterface.quoteTable(this.name)+".*"]
// whereCollection is used for non-primary key updates
......@@ -695,10 +699,10 @@ module.exports = (function() {
* @param {Object|Number} [options] A hash of options to describe the scope of the search, or a number to search by id.
* @param {Object} [queryOptions]
*
* @see {DAOFactory#findAll} for an explanation of options and queryOptions
* @see {Model#findAll} for an explanation of options and queryOptions
* @return {Promise}
*/
DAOFactory.prototype.find = function(options, queryOptions) {
Model.prototype.find = function(options, queryOptions) {
var hasJoin = false
// no options defined?
......@@ -789,7 +793,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.aggregate = function(field, aggregateFunction, options) {
Model.prototype.aggregate = function(field, aggregateFunction, options) {
options = Utils._.extend({ attributes: [] }, options || {})
options.attributes.push([this.sequelize.fn(aggregateFunction, this.sequelize.col(field)), aggregateFunction])
......@@ -818,7 +822,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.count = function(options) {
Model.prototype.count = function(options) {
options = Utils._.clone(options || {})
var col = '*'
......@@ -850,10 +854,10 @@ module.exports = (function() {
* @param {Object} [findOptions] See findAll
* @param {Object} [queryOptions] See Sequelize.query
*
* @see {DAOFactory#findAll} for a specification of find and query options
* @see {Model#findAll} for a specification of find and query options
* @return {Promise}
*/
DAOFactory.prototype.findAndCountAll = function(findOptions, queryOptions) {
Model.prototype.findAndCountAll = function(findOptions, queryOptions) {
var self = this
// no limit, offset, order, attributes for the options given to count()
, countOptions = Utils._.omit(findOptions ? Utils._.merge({}, findOptions) : {}, ['offset', 'limit', 'order', 'attributes'])
......@@ -879,11 +883,11 @@ module.exports = (function() {
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {DAOFactory#aggregate} for options
* @see {Model#aggregate} for options
*
* @return {Promise}
*/
DAOFactory.prototype.max = function(field, options) {
Model.prototype.max = function(field, options) {
return this.aggregate(field, 'max', options)
}
......@@ -892,11 +896,11 @@ module.exports = (function() {
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {DAOFactory#aggregate} for options
* @see {Model#aggregate} for options
*
* @return {Promise}
*/
DAOFactory.prototype.min = function(field, options) {
Model.prototype.min = function(field, options) {
return this.aggregate(field, 'min', options)
}
......@@ -905,11 +909,11 @@ module.exports = (function() {
*
* @param {String} field
* @param {Object} [options] See aggregate
* @see {DAOFactory#aggregate} for options
* @see {Model#aggregate} for options
*
* @return {Promise}
*/
DAOFactory.prototype.sum = function(field, options) {
Model.prototype.sum = function(field, options) {
return this.aggregate(field, 'sum', options)
}
......@@ -925,7 +929,7 @@ module.exports = (function() {
*
* @return {DAO}
*/
DAOFactory.prototype.build = function(values, options) {
Model.prototype.build = function(values, options) {
if (Array.isArray(values)) {
return this.bulkBuild(values, options)
}
......@@ -945,7 +949,7 @@ module.exports = (function() {
}
DAOFactory.prototype.bulkBuild = function(valueSets, options) {
Model.prototype.bulkBuild = function(valueSets, options) {
options = options || { isNewRecord: true, isDirty: true }
if (options.hasOwnProperty('include') && options.include && !options.includeValidated) {
......@@ -980,9 +984,9 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.create = function(values, options) {
Model.prototype.create = function(values, options) {
Utils.validateParameter(values, Object, { optional: true })
Utils.validateParameter(options, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#create' })
Utils.validateParameter(options, Object, { deprecated: Array, optional: true, index: 2, method: 'Model#create' })
if (options instanceof Array) {
options = { fields: options }
}
......@@ -1011,7 +1015,7 @@ module.exports = (function() {
* @method
* @alias findOrBuild
*/
DAOFactory.prototype.findOrInitialize = DAOFactory.prototype.findOrBuild = function (params, defaults, options) {
Model.prototype.findOrInitialize = Model.prototype.findOrBuild = function (params, defaults, options) {
defaults = defaults || {}
options = options || {}
......@@ -1056,7 +1060,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.findOrCreate = function (where, defaults, options) {
Model.prototype.findOrCreate = function (where, defaults, options) {
var self = this
, values = {}
......@@ -1105,9 +1109,9 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.bulkCreate = function(records, fieldsOrOptions, options) {
Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'DAOFactory#bulkCreate' })
Utils.validateParameter(options, 'undefined', { deprecated: Object, optional: true, index: 3, method: 'DAOFactory#bulkCreate' })
Model.prototype.bulkCreate = function(records, fieldsOrOptions, options) {
Utils.validateParameter(fieldsOrOptions, Object, { deprecated: Array, optional: true, index: 2, method: 'Model#bulkCreate' })
Utils.validateParameter(options, 'undefined', { deprecated: Object, optional: true, index: 3, method: 'Model#bulkCreate' })
if (!records.length) {
return new Utils.Promise(function(resolve) {
......@@ -1166,11 +1170,11 @@ module.exports = (function() {
})
if (createdAtAttr && !values[createdAtAttr]) {
values[createdAtAttr] = Utils.now(self.daoFactoryManager.sequelize.options.dialect)
values[createdAtAttr] = Utils.now(self.modelManager.sequelize.options.dialect)
}
if (updatedAtAttr && !values[updatedAtAttr]) {
values[updatedAtAttr] = Utils.now(self.daoFactoryManager.sequelize.options.dialect)
values[updatedAtAttr] = Utils.now(self.modelManager.sequelize.options.dialect)
}
records.push(values)
......@@ -1231,7 +1235,7 @@ module.exports = (function() {
*
* @return {Promise}
*/
DAOFactory.prototype.destroy = function(where, options) {
Model.prototype.destroy = function(where, options) {
options = options || {}
options.force = options.force === undefined ? false : Boolean(options.force)
options.type = QueryTypes.BULKDELETE
......@@ -1355,7 +1359,7 @@ module.exports = (function() {
*
* @return {EventEmitter}
*/
DAOFactory.prototype.update = function(attrValueHash, where, options) {
Model.prototype.update = function(attrValueHash, where, options) {
var self = this
, query = null
, tick = 0
......@@ -1491,7 +1495,7 @@ module.exports = (function() {
*
* @return {EventEmitter}
*/
DAOFactory.prototype.describe = function(schema) {
Model.prototype.describe = function(schema) {
return this.QueryInterface.describeTable(this.tableName, schema || this.options.schema || undefined)
}
......@@ -1502,7 +1506,7 @@ module.exports = (function() {
* @see https://github.com/brianc/node-sql
* @return {node-sql} A node-sql instance
*/
DAOFactory.prototype.dataset = function() {
Model.prototype.dataset = function() {
if (!this.__sql) {
this.__setSqlDialect()
}
......@@ -1517,8 +1521,8 @@ module.exports = (function() {
return instance
}
DAOFactory.prototype.__setSqlDialect = function() {
var dialect = this.daoFactoryManager.sequelize.options.dialect
Model.prototype.__setSqlDialect = function() {
var dialect = this.modelManager.sequelize.options.dialect
this.__sql = sql.setDialect(dialect === 'mariadb' ? 'mysql' : dialect)
}
......@@ -1559,8 +1563,8 @@ module.exports = (function() {
// Apply on each include
if ( options.include && options.include.length ) {
options.include.forEach(function(include) {
if( typeof include == 'object' && include.daoFactory || include.model ){
paranoidClause.call( include.daoFactory || include.model, include )
if( typeof include == 'object' && include.daoFactory || include.daoFactory ){
paranoidClause.call( include.daoFactory || include.daoFactory, include )
}
})
}
......@@ -1660,12 +1664,12 @@ module.exports = (function() {
options.include = [options.include]
}
// convert all included elements to { daoFactory: Model } form
// convert all included elements to { Model: Model } form
var includes = options.include = options.include.map(function(include) {
if (include instanceof DAOFactory) {
if (include instanceof Model) {
return { daoFactory: include }
} else if (typeof include !== 'object') {
throw new Error('Include unexpected. Element has to be either an instance of DAOFactory or an object.')
throw new Error('Include unexpected. Element has to be either an instance of Model or an object.')
} else if (include.hasOwnProperty('model')) {
include.daoFactory = include.model
delete include.model
......@@ -1712,7 +1716,7 @@ module.exports = (function() {
var validateIncludedElement = function(include, tableNames) {
if (!include.hasOwnProperty('daoFactory')) {
throw new Error('Include malformed. Expected attributes: daoFactory, as!')
throw new Error('Include malformed. Expected attributes: model')
}
tableNames[include.daoFactory.tableName] = true
......@@ -1727,7 +1731,7 @@ module.exports = (function() {
// pseudo include just needed the attribute logic, return
if (include._pseudo) return include
// check if the current daoFactory is actually associated with the passed daoFactory - or it's a pseudo include
// check if the current Model is actually associated with the passed Model - or it's a pseudo include
var association = this.getAssociation(include.daoFactory, include.as)
if (association) {
include.association = association
......@@ -1872,7 +1876,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.
if (elem instanceof DAOFactory ||
if (elem instanceof Model ||
elem instanceof Utils.col ||
elem instanceof Utils.literal ||
elem instanceof Utils.cast ||
......@@ -1891,8 +1895,8 @@ module.exports = (function() {
})
}
Utils._.extend(DAOFactory.prototype, require("./associations/mixin"))
Utils._.extend(DAOFactory.prototype, require(__dirname + '/hooks'))
Utils._.extend(Model.prototype, require("./associations/mixin"))
Utils._.extend(Model.prototype, require(__dirname + '/hooks'))
return DAOFactory
return Model
})()
var url = require("url")
, Path = require("path")
, Utils = require("./utils")
, DAOFactory = require("./dao-factory")
, Model = require("./model")
, DataTypes = require('./data-types')
, DAOFactoryManager = require("./dao-factory-manager")
, ModelManager = require("./model-manager")
, QueryInterface = require("./query-interface")
, Transaction = require("./transaction")
, TransactionManager = require('./transaction-manager')
......@@ -162,7 +162,7 @@ module.exports = (function() {
} catch(err) {
throw new Error("The dialect " + this.getDialect() + " is not supported.")
}
this.daoFactoryManager = new DAOFactoryManager(this)
this.modelManager = this.daoFactoryManager = new ModelManager(this)
this.transactionManager = new TransactionManager(this)
this.importCache = {}
......@@ -191,7 +191,7 @@ module.exports = (function() {
*/
Sequelize.prototype.Validator = Sequelize.Validator = require('validator')
Sequelize.DAOFactory = Sequelize.Model = DAOFactory
Sequelize.Model = Sequelize.Model = Model
for (var dataType in DataTypes) {
Sequelize[dataType] = DataTypes[dataType]
......@@ -314,7 +314,7 @@ module.exports = (function() {
* @param {Boolean} [attributes.column.primaryKey=false]
* @param {Boolean} [attributes.column.autoIncrement=false]
* @param {String} [attributes.column.comment=null]
* @param {String|DAOFactory} [attributes.column.references] If this column references another table, provide it here as a DAOFactory, or a string
* @param {String|Model} [attributes.column.references] If this column references another table, provide it here as a Model, or a string
* @param {String} [attributes.column.referencesKey='id'] The column of the foreign table that this column references
* @param {String} [attributes.column.onUpdate] What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
* @param {String} [attributes.column.onDelete] What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or NO ACTION
......@@ -324,7 +324,7 @@ module.exports = (function() {
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor
* @param {Object} [options.defaultScope] Define the default search scope to use for this model. Scopes have the same form as the options passed to find / findAll
* @param {Object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `DAOFactory.scope` for more information about how scopes are defined, and what you can do with them
* @param {Object} [options.scopes] More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about how scopes are defined, and what you can do with them
* @param {Boolean} [options.omitNull] Don't persits null values. This means that all columns with null values will not be saved
* @param {Boolean} [options.timestamps=true] Adds createdAt and updatedAt timestamps to the model.
* @param {Boolean} [options.paranoid=false] Calling `destroy` will not delete the model, but instead set a `deletedAt` timestamp if this is true. Needs `timestamps=true` to work
......@@ -337,7 +337,7 @@ module.exports = (function() {
* @param {Object} [options.getterMethods] Provide getter functions that work like those defined per column. If you provide a getter method with the same name as a column, it will be used to access the value of that column. If you provide a name that does not match a column, this function will act as a virtual getter, that can fetch multiple other values
* @param {Object} [options.setterMethods] Provide setter functions that work like those defined per column. If you provide a setter method with the same name as a column, it will be used to update the value of that column. If you provide a name that does not match a column, this function will act as a virtual setter, that can act on and set other values, but will not be persisted
* @param {Object} [options.instanceMethods] Provide functions that are added to each instance (DAO)
* @param {Object} [options.classMethods] Provide functions that are added to the model (DAOFactory)
* @param {Object} [options.classMethods] Provide functions that are added to the model (Model)
* @param {String} [options.schema='public']
* @param {String} [options.engine]
* @param {String} [options.charset]
......@@ -346,7 +346,7 @@ module.exports = (function() {
* @param {Object} [options.hooks] An object of hook function that are called before and after certain lifecycle events. The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can either be a function, or an array of functions.
* @param {Object} [options.validate] An object of model wide validations. Validations have access to all model values via `this`. If the validator function takes an argument, it is asumed to be async, and is called with a callback that accepts an optional error.
*
* @return {DaoFactory}
* @return {Model}
*/
Sequelize.prototype.define = function(daoName, attributes, options) {
options = options || {}
......@@ -368,12 +368,12 @@ module.exports = (function() {
// if you call "define" multiple times for the same daoName, do not clutter the factory
if(this.isDefined(daoName)) {
this.daoFactoryManager.removeDAO(this.daoFactoryManager.getDAO(daoName))
this.modelManager.removeDAO(this.modelManager.getDAO(daoName))
}
options.sequelize = this
var factory = new DAOFactory(daoName, attributes, options)
this.daoFactoryManager.addDAO(factory.init(this.daoFactoryManager))
var factory = new Model(daoName, attributes, options)
this.modelManager.addDAO(factory.init(this.modelManager))
return factory
}
......@@ -383,14 +383,14 @@ module.exports = (function() {
*
* @param {String} daoName The name of a model defined with Sequelize.define
* @throws Will throw an error if the DAO is not define (that is, if sequelize#isDefined returns false)
* @return {DAOFactory}
* @return {Model}
*/
Sequelize.prototype.model = function(daoName) {
if(!this.isDefined(daoName)) {
throw new Error(daoName + ' has not been defined')
}
return this.daoFactoryManager.getDAO(daoName)
return this.modelManager.getDAO(daoName)
}
/**
......@@ -400,7 +400,7 @@ module.exports = (function() {
* @return {Boolean}
*/
Sequelize.prototype.isDefined = function(daoName) {
var daos = this.daoFactoryManager.daos
var daos = this.modelManager.daos
return (daos.filter(function(dao) { return dao.name === daoName }).length !== 0)
}
......@@ -411,7 +411,7 @@ module.exports = (function() {
*
* See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a short example of how to define your models in separate files so that they can be imported by sequelize.import
* @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
* @return {DAOFactory}
* @return {Model}
*/
Sequelize.prototype.import = function(path) {
// is it a relative path?
......@@ -442,7 +442,7 @@ module.exports = (function() {
*
* @method query
* @param {String} sql
* @param {DAOFactory} [callee] If callee is provided, the selected data will be used to build an instance of the DAO represented by the factory. Equivalent to calling DAOFactory.build with the values provided by the query.
* @param {Model} [callee] If callee is provided, the selected data will be used to build an instance of the DAO represented by the factory. Equivalent to calling Model.build with the values provided by the query.
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
......@@ -450,7 +450,7 @@ module.exports = (function() {
* @param {Object|Array} [replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @return {EventEmitter}
*
* @see {DAOFactory#build} for more information about callee.
* @see {Model#build} for more information about callee.
*/
Sequelize.prototype.query = function(sql, callee, options, replacements) {
if (arguments.length === 4) {
......@@ -550,7 +550,7 @@ module.exports = (function() {
chainer.add(this, 'drop', [options])
}
this.daoFactoryManager.forEachDAO(function(dao) {
this.modelManager.forEachDAO(function(dao) {
if (dao) {
chainer.add(dao, 'sync', [options])
} else {
......@@ -574,7 +574,7 @@ module.exports = (function() {
return new Utils.CustomEventEmitter(function(emitter) {
var chainer = new Utils.QueryChainer()
self.daoFactoryManager.forEachDAO(function(dao) {
self.modelManager.forEachDAO(function(dao) {
if (dao) {
chainer.add(dao, 'drop', [options])
}
......@@ -624,9 +624,9 @@ module.exports = (function() {
* })
* ```
*
* @see {DAOFactory#find}
* @see {DAOFactory#findAll}
* @see {DAOFactory#define}
* @see {Model#find}
* @see {Model#findAll}
* @see {Model#define}
* @see {Sequelize#col}
* @method fn
*
......@@ -686,7 +686,7 @@ module.exports = (function() {
/**
* An AND query
* @see {DAOFactory#find}
* @see {Model#find}
*
* @method and
* @param {String|Object} args Each argument will be joined by AND
......@@ -699,7 +699,7 @@ module.exports = (function() {
/**
* An OR query
* @see {DAOFactory#find}
* @see {Model#find}
*
* @method or
* @param {String|Object} args Each argument will be joined by OR
......@@ -712,7 +712,7 @@ module.exports = (function() {
/*
* A way of specifying attr = condition. Mostly used internally
* @see {DAOFactory#find}
* @see {Model#find}
*
* @param {string} attr The attribute
* @param {String|Object} condition The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` etc.)
......
......@@ -293,7 +293,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
var self = this
expect(function() {
self.Worker.find({ include: [ 1 ] })
}).to.throw(Error, 'Include unexpected. Element has to be either an instance of DAOFactory or an object.')
}).to.throw(Error, 'Include unexpected. Element has to be either an instance of Model or an object.')
done()
})
......@@ -329,9 +329,8 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
var self = Object.create(this)
self.Domain = self.sequelize.define('Domain', { ip: Sequelize.STRING })
self.Environment = self.sequelize.define('Environment', { name: Sequelize.STRING })
self.Environment
.belongsTo(self.Domain, { as: 'PrivateDomain', foreignKey: 'privateDomainId' })
.belongsTo(self.Domain, { as: 'PublicDomain', foreignKey: 'publicDomainId' })
self.Environment.belongsTo(self.Domain, { as: 'PrivateDomain', foreignKey: 'privateDomainId' })
self.Environment.belongsTo(self.Domain, { as: 'PublicDomain', foreignKey: 'publicDomainId' })
self.Domain.sync({ force: true }).success(function() {
self.Environment.sync({ force: true }).success(function() {
......
......@@ -545,7 +545,7 @@ describe(Support.getTestDialectTeaser("DAOFactory"), function () {
var self = this
expect(function() {
self.Worker.all({ include: [ 1 ] })
}).to.throw(Error, 'Include unexpected. Element has to be either an instance of DAOFactory or an object.')
}).to.throw(Error, 'Include unexpected. Element has to be either an instance of Model or an object.')
done()
})
......
......@@ -21,13 +21,11 @@ describe(Support.getTestDialectTeaser("Include"), function () {
D = S.define('D', { name: DT.STRING(40) }, { paranoid: true })
// Associations
A
.hasMany( B )
A.hasMany( B )
B
.belongsTo( B )
.belongsTo( D )
.hasMany( C, {
B.belongsTo( B )
B.belongsTo( D )
B.hasMany( C, {
through: 'BC',
})
......
......@@ -28,11 +28,10 @@ describe(Support.getTestDialectTeaser("Include"), function () {
// Associate them
User.hasMany( SomeConnection, { foreignKey: 'u' })
SomeConnection
.belongsTo( User, { foreignKey: 'u' })
.belongsTo( A, { foreignKey: 'fk' })
.belongsTo( B, { foreignKey: 'fk' })
.belongsTo( C, { foreignKey: 'fk' })
SomeConnection.belongsTo( User, { foreignKey: 'u' })
SomeConnection.belongsTo( A, { foreignKey: 'fk' })
SomeConnection.belongsTo( B, { foreignKey: 'fk' })
SomeConnection.belongsTo( C, { foreignKey: 'fk' })
A.hasMany( SomeConnection, { foreignKey: 'fk' })
B.hasMany( SomeConnection, { foreignKey: 'fk' })
......
......@@ -20,21 +20,17 @@ describe(Support.getTestDialectTeaser("Paranoid"), function () {
C = this.C = S.define( 'C', { name: DT.STRING }, { paranoid: true }),
D = this.D = S.define( 'D', { name: DT.STRING }, { paranoid: true })
A
.belongsTo( B )
.hasMany( D )
.hasMany( C )
A.belongsTo( B )
A.hasMany( D )
A.hasMany( C )
B
.hasMany( A )
.hasMany( C )
B.hasMany( A )
B.hasMany( C )
C
.belongsTo( A )
.belongsTo( B )
C.belongsTo( A )
C.belongsTo( B )
D
.hasMany( A )
D.hasMany( A )
S.sync({ force: true }).done(function ( err ) {
expect( err ).not.to.be.ok
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!