Code coverage report for upstream/lib/dao.js

Statements: 70.63% (214 / 303)      Branches: 65.73% (163 / 248)      Functions: 61.02% (36 / 59)      Lines: 70.9% (212 / 299)     

All files » upstream/lib/ » dao.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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 6701             1 1 791 791 791 791 791   791 791 791   791     1   1 1316     1 1004     1                 1   303       1   5       1   4     4 4     4       1   52       52 46     52 55     52       1     1       1 899 595 5   590     304 1     1 2 2       1 2 1     1   303   1 3472     3472 794 794   794   794         794 136     136     136     658 2365     658   119       2678 2678     2678         2678   36 36     2642 1       2641 65       2576 41       2576 46     2576 2576           1 43 33 8   25   10 28     10     1 2     1 36 36           36 40   36     36     36   36 39                     39 25 25 25   14 11 11     14 14               1 304       304   304 280     304 304 24   280       304         304 304 287 24     287           304 304     304 1452 698       304 1528 1528               1528                   1528               304 287                 287 245                   304       304 262 262 262   42   42       42 42 42     304 304       304   304   304       303     303 303   303 303       303   303 303   303                             1                                                     1                       1 332   332     1                   1       1 9 9   9     9 9 9       9         9 9     9 9     3     6 6       6             1                                                                                 1                                                       1                           1                 1       1 1         1   791     791   791 492 3 5 5         492 460         460         460           791 682 687 438         791     1    
var Utils        = require("./utils")
  , Mixin        = require("./associations/mixin")
  , DaoValidator = require("./dao-validator")
  , DataTypes    = require("./data-types")
  , hstore       = require('./dialects/postgres/hstore')
  , _            = require('lodash')
 
module.exports = (function() {
  var DAO = function(values, options) {
    this.dataValues                  = {}
    this._previousDataValues         = {}
    this.__options                   = this.__factory.options
    this.options                     = options
    this.hasPrimaryKeys              = this.__factory.options.hasPrimaryKeys
    // What is selected values even used for? 
    this.selectedValues              = options.include ? _.omit(values, options.includeNames) : values
    this.__eagerlyLoadedAssociations = []
    this.isNewRecord                 = options.isNewRecord
 
    initValues.call(this, values, options)
  }
 
  Utils._.extend(DAO.prototype, Mixin.prototype)
 
  Object.defineProperty(DAO.prototype, 'sequelize', {
    get: function(){ return this.__factory.daoFactoryManager.sequelize }
  })
 
  Object.defineProperty(DAO.prototype, 'QueryInterface', {
    get: function(){ return this.sequelize.getQueryInterface() }
  })
 
  Object.defineProperty(DAO.prototype, 'isDeleted', {
    get: function() {
      var result = this.__options.timestamps && this.__options.paranoid
      result = result && this.dataValues[Utils._.underscoredIf(this.__options.deletedAt, this.__options.underscored)] !== null
 
      return result
    }
  })
 
  Object.defineProperty(DAO.prototype, 'values', {
    get: function() {
      return this.get()
    }
  })
 
  Object.defineProperty(DAO.prototype, 'isDirty', {
    get: function() {
      return !!this.changed()
    }
  })
 
  Object.defineProperty(DAO.prototype, 'primaryKeyValues', {
    get: function() {
      var result = {}
        , self   = this
 
      Utils._.each(this.__factory.primaryKeys, function(_, attr) {
        result[attr] = self.dataValues[attr]
      })
 
      return result
    }
  })
 
  Object.defineProperty(DAO.prototype, "identifiers", {
    get: function() {
      var primaryKeys = Object.keys(this.__factory.primaryKeys)
        , result      = {}
        , self        = this
 
      if (!this.__factory.hasPrimaryKeys) {
        primaryKeys = ['id']
      }
 
      primaryKeys.forEach(function(identifier) {
        result[identifier] = self.dataValues[identifier]
      })
 
      return result
    }
  })
 
  DAO.prototype.getDataValue = function(key) {
    return this.dataValues[key]
  }
  DAO.prototype.setDataValue = function(key, value) {
    this.dataValues[key] = value
  }
 
  DAO.prototype.get = function (key) {
    if (key) {
      if (this._customGetters[key]) {
        return this._customGetters[key].call(this, key)
      }
      return this.dataValues[key]
    }
 
    if (this._hasCustomGetters) {
      var values = {}
        , key
 
      for (key in this._customGetters) {
        Eif (this._customGetters.hasOwnProperty(key)) {
          values[key] = this.get(key)
        }
      }
 
      for (key in this.dataValues) {
        if (!values.hasOwnProperty(key) && this.dataValues.hasOwnProperty(key)) {
          values[key] = this.dataValues[key]
        }
      }
      return values
    }
    return this.dataValues
  }
  DAO.prototype.set = function (key, value, options) {
    var values
      , originalValue
 
    if (typeof key === "object") {
      values = key
      options = value
 
      options || (options = {})
 
      Iif (options.reset) {
        this.dataValues = {}
      }
 
      // If raw, and we're not dealing with includes, just set it straight on the dataValues object
      if (options.raw && !(this.options && this.options.include) && !this._hasBooleanAttributes) {
        Iif (Object.keys(this.dataValues).length) {
          this.dataValues = _.extend(this.dataValues, values)
        } else {
          this.dataValues = values
        }
        // If raw, .changed() shouldn't be true
        this._previousDataValues = _.clone(this.dataValues)
      } else {
        // Loop and call set
        for (key in values) {
          this.set(key, values[key], options)
        }
 
        if (options.raw) {
          // If raw, .changed() shouldn't be true
          this._previousDataValues = _.clone(this.dataValues)
        }
      }
    } else {
      options || (options = {})
      originalValue = this.dataValues[key]
 
      // If not raw, and there's a customer setter
      Iif (!options.raw && this._customSetters[key]) {
        this._customSetters[key].call(this, value, key)
      } else { 
        // Check if we have included models, and if this key matches the include model names/aliases
 
        if (this.options && this.options.include && this.options.includeNames.indexOf(key) !== -1) {
          // Pass it on to the include handler
          this._setInclude(key, value, options)
          return
        } else {
          // If attempting to set primary key and primary key is already defined, return
          if (this._hasPrimaryKeys && originalValue && this._isPrimaryKey(key)) {
            return
          }
 
          // If attempting to set read only attributes, return
          if (!options.raw && this._hasReadOnlyAttributes && this._isReadOnlyAttribute(key)) {
            return
          }
 
          // Convert boolean-ish values to booleans
          if (this._hasBooleanAttributes && this._isBooleanAttribute(key) && value !== null && value !== undefined) {
            value = !!value
          }
 
          // Convert date fields to real date objects
          if (this._hasDateAttributes && this._isDateAttribute(key) && value !== null && !(value instanceof Date)) {
            value = new Date(value)
          }
 
          if (originalValue !== value) this._previousDataValues[key] = originalValue
          this.dataValues[key] = value
        }
      }
    }
  }
 
  DAO.prototype.changed = function(key) {
    if (key) {
      if (this._isDateAttribute(key) && this._previousDataValues[key] && this.dataValues[key]) {
        return this._previousDataValues[key].valueOf() !== this.dataValues[key].valueOf()
      }
      return this._previousDataValues[key] !== this.dataValues[key]
    }
    var changed = Object.keys(this.dataValues).filter(function (key) {
      return this.changed(key)
    }.bind(this))
 
    return changed.length ? changed : false
  }
 
  DAO.prototype.previous = function(key) {
    return this._previousDataValues[key]
  }
 
  DAO.prototype._setInclude = function(key, value, options) {
    if (!Array.isArray(value)) value = [value]
    Iif (value[0] instanceof DAO) {
      value = value.map(function (instance) {
        return instance.dataValues
      })
    }
 
    var include = _.find(this.options.include, function (include) {
      return include.as === key || (include.as.slice(0,1).toLowerCase() + include.as.slice(1)) === key
    })
    var association          = include.association
      , self                 = this
 
    var accessor = Utils._.camelize(key)
 
    // downcase the first char
    accessor = accessor.slice(0,1).toLowerCase() + accessor.slice(1)
 
    value.forEach(function(data) {
      var daoInstance = include.daoFactory.build(data, {
            isNewRecord: false,
            isDirty: false,
            include: include.include,
            includeNames: include.includeNames,
            includeMap: include.includeMap,
            includeValidated: true,
            raw: options.raw
          })
        , isEmpty = !Utils.firstValueOfHash(daoInstance.identifiers)
 
      if (association.isSingleAssociation) {
        accessor = Utils.singularize(accessor, self.sequelize.language)
        self.dataValues[accessor] = isEmpty ? null : daoInstance
        self[accessor] = self.dataValues[accessor]
      } else {
        if (!self.dataValues[accessor]) {
          self.dataValues[accessor] = []
          self[accessor] = self.dataValues[accessor]
        }
 
        Eif (!isEmpty) {
          self.dataValues[accessor].push(daoInstance)
        }
      }
    }.bind(this))
  };
 
  // if an array with field names is passed to save()
  // only those fields will be updated
  DAO.prototype.save = function(fieldsOrOptions, options) {
    Iif (fieldsOrOptions instanceof Array) {
      fieldsOrOptions = { fields: fieldsOrOptions }
    }
 
    options = Utils._.extend({}, options, fieldsOrOptions)
 
    if (!options.fields) {
      options.fields = this.attributes
    }
 
    Eif (options.returning === undefined) {
      if (options.association) {
        options.returning = false
      } else {
        options.returning = true
      }
    }
 
    var self           = this
      , values         = {}
      , updatedAtAttr  = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored)
      , createdAtAttr  = Utils._.underscoredIf(this.__options.createdAt, this.__options.underscored)
 
    Eif (options.fields) {
      if (self.__options.timestamps) {
        if (options.fields.indexOf(updatedAtAttr) === -1) {
          options.fields.push(updatedAtAttr)
        }
 
        Iif (options.fields.indexOf(createdAtAttr) === -1 && this.isNewRecord === true) {
          options.fields.push(createdAtAttr)
        }
      }
    }
 
    return new Utils.CustomEventEmitter(function(emitter) {
      self.hookValidate().error(function(err) {
        emitter.emit('error', err)
      }).success(function() {
        options.fields.forEach(function(field) {
          if (self.dataValues[field] !== undefined) {
            values[field] = self.dataValues[field]
          }
        })
 
        for (var attrName in self.daoFactory.rawAttributes) {
          Eif (self.daoFactory.rawAttributes.hasOwnProperty(attrName)) {
            var definition = self.daoFactory.rawAttributes[attrName]
              , isHstore   = !!definition.type && !!definition.type.type && definition.type.type === DataTypes.HSTORE.type
              , isEnum          = definition.type && (definition.type.toString() === DataTypes.ENUM.toString())
              , isMySQL         = ['mysql', 'mariadb'].indexOf(self.daoFactory.daoFactoryManager.sequelize.options.dialect) !== -1
              , ciCollation     = !!self.daoFactory.options.collate && self.daoFactory.options.collate.match(/_ci$/i)
              , valueOutOfScope
 
            // Unfortunately for MySQL CI collation we need to map/lowercase values again
            Iif (isEnum && isMySQL && ciCollation && (attrName in values) && values[attrName]) {
              var scopeIndex = (definition.values || []).map(function(d) { return d.toLowerCase() }).indexOf(values[attrName].toLowerCase())
              valueOutOfScope = scopeIndex === -1
 
              // We'll return what the actual case will be, since a simple SELECT query would do the same...
              if (!valueOutOfScope) {
                values[attrName] = definition.values[scopeIndex]
              }
            }
 
            Iif (isHstore) {
              if (typeof values[attrName] === "object") {
                values[attrName] = hstore.stringify(values[attrName])
              }
            }
          }
        }
 
        if (self.__options.timestamps) {
          values[updatedAtAttr] = (
            (
              self.isNewRecord
              && !!self.daoFactory.rawAttributes[updatedAtAttr]
              && !!self.daoFactory.rawAttributes[updatedAtAttr].defaultValue
            )
            ? self.daoFactory.rawAttributes[updatedAtAttr].defaultValue
            : Utils.now(self.sequelize.options.dialect))
 
          if (self.isNewRecord && !values[createdAtAttr]) {
            values[createdAtAttr] = (
              (
                !!self.daoFactory.rawAttributes[createdAtAttr]
                && !!self.daoFactory.rawAttributes[createdAtAttr].defaultValue
              )
              ? self.daoFactory.rawAttributes[createdAtAttr].defaultValue
              : values[updatedAtAttr])
            }
        }
 
        var query = null
          , args  = []
          , hook  = ''
 
        if (self.isNewRecord) {
          query         = 'insert'
          args          = [self, self.QueryInterface.QueryGenerator.addSchema(self.__factory), values, options]
          hook          = 'Create'
        } else {
          var identifier = self.__options.hasPrimaryKeys ? self.primaryKeyValues : { id: self.id }
 
          Iif (identifier === null && self.__options.whereCollection !== null) {
            identifier = self.__options.whereCollection;
          }
 
          query         = 'update'
          args          = [self, self.QueryInterface.QueryGenerator.addSchema(self.__factory), values, identifier, options]
          hook          = 'Update'
        }
 
        self.__factory.runHooks('before' + hook, values, function(err, newValues) {
          Iif (!!err) {
            return emitter.emit('error', err)
          }
 
          args[2] = values = newValues || values
          // Newest values need to be on the dao since the dao is returned from the query interface
          self.dataValues = _.extend(self.dataValues, values)
 
          self.QueryInterface[query].apply(self.QueryInterface, args)
            .proxy(emitter, {events: ['sql', 'error']})
            .success(function(result) {
              // Transfer database generated values (defaults, autoincrement, etc)
              values = _.extend(values, result.values) 
 
              // Ensure new values are on DAO, and reset previousDataValues
              result.dataValues = _.extend(result.dataValues, values)
              result._previousDataValues = _.clone(result.dataValues)
 
              self.__factory.runHooks('after' + hook, values, function(err, newValues) {
                Iif (!!err) {
                  return emitter.emit('error', err)
                }
 
                Eif (newValues) {
                  // Repeat value assignment incase afterHook changed anything
                  result.dataValues = _.extend(result.dataValues, newValues)
                  result._previousDataValues = _.clone(result.dataValues)
                }
                emitter.emit('success', result)
              })
            })
        })
      })
    }).run()
  }
 
 /*
  * 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 object. With this method,
  * all references to the DAO are updated with the new data and no new objects are created.
  *
  * @return {Object}         A promise which fires `success`, `error`, `complete` and `sql`.
  */
  DAO.prototype.reload = function(options) {
    var where = [
      this.QueryInterface.quoteIdentifier(this.__factory.tableName) + '.' + this.QueryInterface.quoteIdentifier('id')+'=?',
      this.id
    ]
 
    return new Utils.CustomEventEmitter(function(emitter) {
      this.__factory.find({
        where:   where,
        limit:   1,
        include: this.options.include || null
      }, options)
      .on('sql', function(sql) { emitter.emit('sql', sql) })
      .on('error', function(error) { emitter.emit('error', error) })
      .on('success', function(obj) {
        this.set(obj.dataValues, {raw: true, reset: true})
        this.isDirty = false
        emitter.emit('success', this)
      }.bind(this))
    }.bind(this)).run()
  }
 
  /*
   * Validate this dao's attribute values according to validation rules set in the dao definition.
   *
   * @return null if and only if validation successful; otherwise an object containing { field name : [error msgs] } entries.
   */
  DAO.prototype.validate = function(object) {
    var validator = new DaoValidator(this, object)
      , errors    = validator.validate()
 
    return (Utils._.isEmpty(errors) ? null : errors)
  }
 
  /*
   * Validate this dao's attribute values according to validation rules set in the dao definition.
   *
   * @return CustomEventEmitter with null if validation successful; otherwise an object containing { field name : [error msgs] } entries.
   */
  DAO.prototype.hookValidate = function(object) {
    var validator = new DaoValidator(this, object)
 
    return validator.hookValidate()
  }
 
  DAO.prototype.updateAttributes = function(updates, fieldsOrOptions) {
    if (fieldsOrOptions instanceof Array) {
      fieldsOrOptions = { fields: fieldsOrOptions }
    }
 
    this.setAttributes(updates)
 
    return this.save(fieldsOrOptions)
  }
 
  DAO.prototype.setAttributes = function(updates) {
    this.set(updates)
  }
 
  DAO.prototype.destroy = function(options) {
    options = options || {}
    options.force = options.force === undefined ? false : Boolean(options.force)
 
    var self  = this
      , query = null
 
    return new Utils.CustomEventEmitter(function(emitter) {
      self.daoFactory.runHooks(self.daoFactory.options.hooks.beforeDestroy, self.dataValues, function(err) {
        Iif (!!err) {
          return emitter.emit('error', err)
        }
 
        Iif (self.__options.timestamps && self.__options.paranoid && options.force === false) {
          var attr = Utils._.underscoredIf(self.__options.deletedAt, self.__options.underscored)
          self.dataValues[attr] = new Date()
          query = self.save(options)
        } else {
          var identifier = self.__options.hasPrimaryKeys ? self.primaryKeyValues : { id: self.id };
          query = self.QueryInterface.delete(self, self.QueryInterface.QueryGenerator.addSchema(self.__factory.tableName, self.__factory.options.schema), identifier, options)
        }
 
        query.on('sql', function(sql) {
          emitter.emit('sql', sql)
        })
        .error(function(err) {
          emitter.emit('error', err)
        })
        .success(function(results) {
          self.daoFactory.runHooks(self.daoFactory.options.hooks.afterDestroy, self.dataValues, function(err) {
            Iif (!!err) {
              return emitter.emit('error', err)
            }
 
            emitter.emit('success', results)
          })
        })
      })
    }).run()
  }
 
  DAO.prototype.increment = function(fields, countOrOptions) {
    Utils.validateParameter(countOrOptions, Object, {
      optional:           true,
      deprecated:         'number',
      deprecationWarning: "Increment expects an object as second parameter. Please pass the incrementor as option! ~> instance.increment(" + JSON.stringify(fields) + ", { by: " + countOrOptions + " })"
    })
 
    var identifier    = this.__options.hasPrimaryKeys ? this.primaryKeyValues : { id: this.id }
      , updatedAtAttr = Utils._.underscoredIf(this.__options.updatedAt, this.__options.underscored)
      , values        = {}
 
    if (countOrOptions === undefined) {
      countOrOptions = { by: 1, transaction: null }
    } else if (typeof countOrOptions === 'number') {
      countOrOptions = { by: countOrOptions, transaction: null }
    }
 
    countOrOptions = Utils._.extend({
      by:         1,
      attributes: {}
    }, countOrOptions)
 
    if (Utils._.isString(fields)) {
      values[fields] = countOrOptions.by
    } else if (Utils._.isArray(fields)) {
      Utils._.each(fields, function (field) {
        values[field] = countOrOptions.by
      })
    } else { // Assume fields is key-value pairs
      values = fields
    }
 
    if (this.__options.timestamps) {
      if (!values[updatedAtAttr]) {
        countOrOptions.attributes[updatedAtAttr] = Utils.now(this.daoFactory.daoFactoryManager.sequelize.options.dialect)
      }
    }
 
    return this.QueryInterface.increment(this, this.QueryInterface.QueryGenerator.addSchema(this.__factory.tableName, this.__factory.options.schema), values, identifier, countOrOptions)
  }
 
  DAO.prototype.decrement = function (fields, countOrOptions) {
    Utils.validateParameter(countOrOptions, Object, {
      optional:           true,
      deprecated:         'number',
      deprecationWarning: "Decrement expects an object as second parameter. Please pass the decrementor as option! ~> instance.decrement(" + JSON.stringify(fields) + ", { by: " + countOrOptions + " })"
    })
 
    if (countOrOptions === undefined) {
      countOrOptions = { by: 1, transaction: null }
    } else if (typeof countOrOptions === 'number') {
      countOrOptions = { by: countOrOptions, transaction: null }
    }
 
    if (countOrOptions.by === undefined) {
      countOrOptions.by = 1
    }
 
    if (!Utils._.isString(fields) && !Utils._.isArray(fields)) { // Assume fields is key-value pairs
      Utils._.each(fields, function (value, field) {
        fields[field] = -value
      })
    }
 
    countOrOptions.by = 0 - countOrOptions.by
 
    return this.increment(fields, countOrOptions)
  }
 
  DAO.prototype.equals = function(other) {
    var result = true
 
    Utils._.each(this.dataValues, function(value, key) {
      if(Utils._.isDate(value) && Utils._.isDate(other[key])) {
        result = result && (value.getTime() == other[key].getTime())
      } else {
        result = result && (value == other[key])
      }
    })
 
    return result
  }
 
  DAO.prototype.equalsOneOf = function(others) {
    var result = false
      , self   = this
 
    others.forEach(function(other) { result = result || self.equals(other) })
 
    return result
  }
 
  DAO.prototype.setValidators = function(attribute, validators) {
    this.validators[attribute] = validators
  }
 
  DAO.prototype.toJSON = function() {
    return this.get();
  }
 
  // private
 
  var initValues = function(values, options) {
    // set id to null if not passed as value, a newly created dao has no id
    var defaults = this.hasPrimaryKeys ? {} : { id: null },
        key;
 
    values = values && _.clone(values) || {}
 
    if (options.isNewRecord) {
      if (this.hasDefaultValues) {
        Utils._.each(this.defaultValues, function(valueFn, key) {
          Eif (!defaults.hasOwnProperty(key)) {
            defaults[key] = valueFn()
          }
        })
      }
 
      if (this.__options.timestamps) {
        Iif (defaults[this._timestampAttributes.createdAt]) {
          this.dataValues[this._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this._timestampAttributes.createdAt]);
          delete defaults[this._timestampAttributes.createdAt];
        }
 
        Iif (defaults[this._timestampAttributes.updatedAt]) {
          this.dataValues[this._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this._timestampAttributes.updatedAt]);
          delete defaults[this._timestampAttributes.updatedAt];
        }
 
        Iif (defaults[this._timestampAttributes.deletedAt]) {
          this.dataValues[this._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this._timestampAttributes.deletedAt]);
          delete defaults[this._timestampAttributes.deletedAt];
        }
      }
    }
    if (Object.keys(defaults).length) {
      for (key in defaults) {
        if (!values.hasOwnProperty(key)) {
          values[key] = Utils.toDefaultValue(defaults[key])
        }
      }
    }
 
    this.set(values, options)
  }
 
  return DAO
})()