Code coverage report for upstream/lib/associations/has-many.js

Statements: 92.5% (148 / 160)      Branches: 86.79% (92 / 106)      Functions: 86.49% (32 / 37)      Lines: 92.45% (147 / 159)     

All files » upstream/lib/associations/ » has-many.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 3501         1     1 1 108   108 108 108 108 108 108 108 108 108 108 108               108 93         93 73     73                 108 108 26   82 62           108 1           107 107 40 40     40 13     40 17     40 30 30   30 30                 108 30 13       108 22       22     108   108   108                       1 108     108       108   31 1   30 30   30 29     30 29         31 31 31 31 31 31 31     31 99 31       31 31   31 31     77 77 77 77       108 108   108     1 108   108 87 87     108 4 4 4     4   6 6 6             4     108 6 6 6     6   3 3           6   108     1 108   108 46 5     46     46 46   46 46           108 10           10 10 10     10 10 10               108 1 1 1 1     1 2 1       1 1                           1 1       1     1     1           108                       1 60     60 6 2       60     1    
var Utils     = require("./../utils")
  , DataTypes = require('./../data-types')
  , Helpers   = require('./helpers')
  , _         = require('lodash')
 
var HasManySingleLinked = require("./has-many-single-linked")
  , HasManyMultiLinked  = require("./has-many-double-linked")
 
module.exports = (function() {
  var HasMany = function(source, target, options) {
    var self = this
 
    this.associationType = 'HasMany'
    this.source = source
    this.target = target
    this.targetAssociation = null
    this.options = options
    this.sequelize = source.daoFactoryManager.sequelize
    this.through = options.through
    this.isMultiAssociation = true
    this.isSelfAssociation = (this.source.tableName === this.target.tableName)
    this.doubleLinked = false
    this.combinedTableName = Utils.combineTableNames(
      this.source.tableName,
      this.isSelfAssociation ? (this.options.as || this.target.tableName) : this.target.tableName
    )
 
    /*
     * Map joinTableModel/Name to through for BC
     */
    if (this.through === undefined) {
      this.through = this.options.joinTableModel || this.options.joinTableName;
 
      /*
       * If both are undefined, see if useJunctionTable was false (for self associations) - else assume through to be true
       */
      if (this.through === undefined) {
        Iif (this.options.useJunctionTable === false) {
          this.through = null;
        } else {
          this.through = true;
        }
      }
    }
 
    /*
     * Determine associationAccessor, especially for include options to identify the correct model
     */
 
    this.associationAccessor = this.options.as
    if (!this.associationAccessor && (typeof this.through === "string" || Object(this.through) === this.through)) {
      this.associationAccessor = this.through.tableName || this.through
    } 
    else if (!this.associationAccessor) {
      this.associationAccessor = this.combinedTableName
    }
 
    /*
     * If self association, this association is target association
     */
    if (this.isSelfAssociation) {
      this.targetAssociation = this
    }
 
    /*
     * Else find partner DAOFactory if present, to identify double linked association
     */
    else Eif (this.through) {
    _.each(this.target.associations, function (association, accessor) {
      Eif (self.source === association.target) {
        var paired = false
 
        // If through is default, we determine pairing by the accesor value (i.e. DAOFactory's using as won't pair, but regular ones will)
        if (self.through === true && accessor === self.associationAccessor) {
          paired = true
        }
        // If through is not default, determine pairing by through value (model/string)
        if (self.through !== true && self.options.through === association.options.through) {
          paired = true
        }
        // If paired, set properties identifying both associations as double linked, and allow them to each eachtoerh
        if (paired) {
          self.doubleLinked = true
          association.doubleLinked = true
          
          self.targetAssociation = association
          association.targetAssociation = self
        }
      }
    })
    }
 
    /*
     * If we are double linked, and through is either default or a string, we create the through model and set it on both associations
     */
    if (this.doubleLinked) {
      if (this.through === true) {
        this.through = this.combinedTableName
      }
    }
 
    if (typeof this.through === "string") {
      this.through = this.sequelize.define(this.through, {}, _.extend(this.options, {
        tableName: this.through
      }))
 
      if (this.targetAssociation) this.targetAssociation.through = this.through
    }
 
    this.options.tableName = this.combinedName = (this.through === Object(this.through) ? this.through.tableName : this.through)
 
    var as = (this.options.as || Utils.pluralize(this.target.tableName, this.target.options.language))
 
    this.accessors = {
      get: Utils._.camelize('get_' + as),
      set: Utils._.camelize('set_' + as),
      add: Utils._.camelize(Utils.singularize('add_' + as, this.target.options.language)),
      remove: Utils._.camelize(Utils.singularize('remove_' + as, this.target.options.language)),
      hasSingle: Utils._.camelize(Utils.singularize('has_' + as, this.target.options.language)),
      hasAll: Utils._.camelize('has_' + as)
    }
  }
 
  // the id is in the target table
  // or in an extra table which connects two tables
  HasMany.prototype.injectAttributes = function() {
    var doubleLinked = this.doubleLinked
      , self         = this
 
    this.identifier = this.options.foreignKey || Utils._.underscoredIf(Utils.singularize(this.source.tableName, this.source.options.language) + "Id", this.options.underscored)
 
    // is there already a single sided association between the source and the target?
    // or is the association on the model itself?
    if ((this.isSelfAssociation && this.through) || doubleLinked) {
      // remove the obsolete association identifier from the source
      if (this.isSelfAssociation) {
        this.foreignIdentifier = Utils._.underscoredIf((this.options.as || this.target.tableName) + 'Id', this.options.underscored)
      } else {
        this.foreignIdentifier = this.targetAssociation.identifier
        this.targetAssociation.foreignIdentifier = this.identifier
 
        if (isForeignKeyDeletionAllowedFor.call(this, this.source, this.foreignIdentifier)) {
          delete this.source.rawAttributes[this.foreignIdentifier]
        }
 
        if (isForeignKeyDeletionAllowedFor.call(this, this.target, this.identifier)) {
          delete this.targetAssociation.source.rawAttributes[this.identifier]
        }
      }
 
      // define a new model, which connects the models
      var combinedTableAttributes = {}
      var sourceKeys = Object.keys(this.source.primaryKeys);
      var sourceKeyType = ((!this.source.hasPrimaryKeys || sourceKeys.length !== 1) ? DataTypes.INTEGER : this.source.rawAttributes[sourceKeys[0]].type)
      var targetKeys = Object.keys(this.target.primaryKeys);
      var targetKeyType = ((!this.target.hasPrimaryKeys || targetKeys.length !== 1) ? DataTypes.INTEGER : this.target.rawAttributes[targetKeys[0]].type)
      combinedTableAttributes[this.identifier] = {type: sourceKeyType, primaryKey: true}
      combinedTableAttributes[this.foreignIdentifier] = {type: targetKeyType, primaryKey: true}
 
      // remove any previously defined PKs
      Utils._.each(this.through.attributes, function(dataTypeString, attributeName) {
        if (dataTypeString.toString().indexOf('PRIMARY KEY') !== -1) {
          delete self.through.rawAttributes[attributeName]
        }
      })
 
      this.through.rawAttributes = Utils._.merge(this.through.rawAttributes, combinedTableAttributes)
      this.through.init(this.through.daoFactoryManager)
 
      Eif (this.options.syncOnAssociation) {
        this.through.sync()
      }
    } else {
      var newAttributes = {}
      newAttributes[this.identifier] = { type: this.options.keyType || DataTypes.INTEGER }
      Helpers.addForeignKeyConstraints(newAttributes[this.identifier], this.source, this.target, this.options)
      Utils._.defaults(this.target.rawAttributes, newAttributes)
    }
 
    // Sync attributes and setters/getters to DAO prototype
    this.target.refreshAttributes()
    this.source.refreshAttributes()
 
    return this
  }
 
  HasMany.prototype.injectGetter = function(obj) {
    var self = this
 
    obj[this.accessors.get] = function(options) {
      var Class = Object(self.through) === self.through ? HasManyMultiLinked : HasManySingleLinked
      return new Class(self, this).injectGetter(options)
    }
 
    obj[this.accessors.hasAll] = function(objects, options) {
      var instance = this;
      var customEventEmitter = new Utils.CustomEventEmitter(function() {
        instance[self.accessors.get](options)
          .error(function(err) { customEventEmitter.emit('error', err) })
          .success(function(associatedObjects) {
            customEventEmitter.emit('success',
              Utils._.all(objects, function(o) {
                return Utils._.any(associatedObjects, function(associatedObject) {
                  return Utils._.all(associatedObject.identifiers, function(key, identifier) {
                    return o[identifier] == associatedObject[identifier];
                  });
                })
              })
            )
          })
      })
      return customEventEmitter.run()
    }
 
    obj[this.accessors.hasSingle] = function(o, options) {
      var instance           = this
      var customEventEmitter = new Utils.CustomEventEmitter(function() {
        instance[self.accessors.get](options)
        .error(function(err){ customEventEmitter.emit('error', err)})
        .success(function(associatedObjects) {
          customEventEmitter.emit('success',
            Utils._.any(associatedObjects, function(associatedObject) {
              return Utils._.all(associatedObject.identifiers, function(key, identifier) {
                return o[identifier] == associatedObject[identifier];
              });
            })
          )
        })
      })
      return customEventEmitter.run()
    }
    return this
  }
 
  HasMany.prototype.injectSetter = function(obj) {
    var self = this
 
    obj[this.accessors.set] = function(newAssociatedObjects, defaultAttributes) {
      if (newAssociatedObjects === null) {
        newAssociatedObjects = []
      }
 
      var instance = this
 
      // define the returned customEventEmitter, which will emit the success event once everything is done
      return new Utils.CustomEventEmitter(function(emitter) {
        instance[self.accessors.get]()
          .success(function(oldAssociatedObjects) {
            var Class = Object(self.through) === self.through ? HasManyMultiLinked : HasManySingleLinked
            new Class(self, instance).injectSetter(emitter, oldAssociatedObjects, newAssociatedObjects, defaultAttributes)
          })
          .proxy(emitter, {events: ['error', 'sql']})
      }).run()
    }
 
    obj[this.accessors.add] = function(newAssociatedObject, additionalAttributes) {
      var instance = this
        , primaryKeys = Object.keys(newAssociatedObject.daoFactory.primaryKeys || {})
        , primaryKey = primaryKeys.length === 1 ? primaryKeys[0] : 'id'
        , where = {}
 
 
      where[newAssociatedObject.daoFactory.tableName+'.'+primaryKey] = newAssociatedObject[primaryKey]
      return new Utils.CustomEventEmitter(function(emitter) {
        instance[self.accessors.get]({ where: where })
          .proxy(emitter, {events: ['error', 'sql']})
          .success(function(currentAssociatedObjects) {
            Eif (currentAssociatedObjects.length === 0 || Object(self.through) === self.through) {
              var Class = Object(self.through) === self.through ? HasManyMultiLinked : HasManySingleLinked
              new Class(self, instance).injectAdder(emitter, newAssociatedObject, additionalAttributes, !!currentAssociatedObjects.length)
            } else {
              emitter.emit('success', newAssociatedObject);
            }
          })
      }).run()
    }
 
    obj[this.accessors.remove] = function(oldAssociatedObject) {
      var instance = this
      return new Utils.CustomEventEmitter(function(emitter) {
        instance[self.accessors.get]().success(function(currentAssociatedObjects) {
          var newAssociations = []
            , oldAssociations = []
 
          currentAssociatedObjects.forEach(function(association) {
            if (!Utils._.isEqual(oldAssociatedObject.identifiers, association.identifiers)) {
              newAssociations.push(association)
            }
          })
 
          var tick = 0
          var next = function(err, i) {
            if (!!err || i >= oldAssociations.length) {
              return run(err)
            }
 
            oldAssociations[i].destroy().error(function(err) {
              next(err)
            })
            .success(function() {
              tick++
              next(null, tick)
            })
          }
 
          var run = function(err) {
            Iif (!!err) {
              return emitter.emit('error', err)
            }
 
            instance[self.accessors.set](newAssociations).proxy(emitter)
          }
 
          Iif (oldAssociations.length > 0) {
            next(null, tick)
          } else {
            run()
          }
        })
      }).run()
    }
 
    return this
  }
 
  /**
   * The method checks if it is ok to delete the previously defined foreign key.
   * This is done because we need to keep the foreign key if another association
   * is depending on it.
   *
   * @param  {DaoFactory}  daoFactory The source or target DaoFactory of this assocation
   * @param  {[type]}  identifier     The name of the foreign key identifier
   * @return {Boolean}                Whether or not the deletion of the foreign key is ok.
   */
  var isForeignKeyDeletionAllowedFor = function(daoFactory, identifier) {
    var isAllowed        = true
      , associationNames = Utils._.without(Object.keys(daoFactory.associations), this.associationAccessor)
 
    associationNames.forEach(function(associationName) {
      if (daoFactory.associations[associationName].identifier === identifier) {
        isAllowed = false
      }
    })
 
    return isAllowed
  }
 
  return HasMany
})()