Code coverage report for upstream/lib/sequelize.js

Statements: 60.84% (101 / 166)      Branches: 46.32% (44 / 95)      Functions: 43.59% (17 / 39)      Lines: 61.35% (100 / 163)     

All files » upstream/lib/ » sequelize.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 4351                   1                                                                               1 8 8   8 3 3 3 3 3 3   3 2     3 1 1       8                                       8         8                                 8 8 7   1   7 7   7           1   1 16           1                     1 16                 1 10118 10118                     1                       1 435 435     435 435 435 870             435 435     435 991 770     991       991                                                 435 14     435 435   435                 1               1 435 435     1                                   1       1 2569             2569 2172 397     397     2569 2569         2569     1               1               1               1               1 59   59 59     59   59         59 155     59     1                             1                               1 8     1 8     1       1       1       1 12         12 12 12       12     1    
var url                = require("url")
  , Path               = require("path")
  , Utils              = require("./utils")
  , DAOFactory         = require("./dao-factory")
  , DataTypes          = require('./data-types')
  , DAOFactoryManager  = require("./dao-factory-manager")
  , QueryInterface     = require("./query-interface")
  , Transaction        = require("./transaction")
  , TransactionManager = require('./transaction-manager')
 
module.exports = (function() {
  /**
    Main class of the project.
 
    @param {String} database The name of the database.
    @param {String} username The username which is used to authenticate against the database.
    @param {String} [password=null] The password which is used to authenticate against the database.
    @param {Object} [options={}] An object with options.
      @param {String} [options.dialect='mysql'] The dialect of the relational database.
      @param {String} [options.dialectModulePath=null] If specified, load the dialect library from this path.
      @param {String} [options.host='localhost'] The host of the relational database.
      @param {Integer} [options.port=3306] The port of the relational database.
      @param {String} [options.protocol='tcp'] The protocol of the relational database.
      @param {Object} [options.define={}] Options, which shall be default for every model definition.
      @param {Object} [options.query={}] I have absolutely no idea.
      @param {Object} [options.sync={}] Options, which shall be default for every `sync` call.
      @param {Function} [options.logging=console.log] A function that gets executed everytime Sequelize would log something.
      @param {Boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
      @param {Boolean} [options.queue=true] I have absolutely no idea.
      @param {Boolean} [options.native=false] A flag that defines if native library shall be used or not.
      @param {Boolean} [options.replication=false] I have absolutely no idea.
      @param {Object} [options.pool={}] Something.
      @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them.
 
    @example
        // without password and options
        var sequelize = new Sequelize('database', 'username')
 
        // without options
        var sequelize = new Sequelize('database', 'username', 'password')
 
        // without password / with blank password
        var sequelize = new Sequelize('database', 'username', null, {})
 
        // with password and options
        var sequelize = new Sequelize('my_database', 'john', 'doe', {})
 
    @class Sequelize
    @constructor
  */
  var Sequelize = function(database, username, password, options) {
    var urlParts
    options = options || {}
 
    if (arguments.length === 1 || (arguments.length === 2 && typeof username === 'object')) {
      options = username || {}
      urlParts = url.parse(arguments[0])
      database = urlParts.path.replace(/^\//,  '')
      dialect = urlParts.protocol
      options.dialect = urlParts.protocol.replace(/:$/, '')
      options.host = urlParts.hostname
 
      if (urlParts.port) {
        options.port = urlParts.port
      }
 
      if (urlParts.auth) {
        username = urlParts.auth.split(':')[0]
        password = urlParts.auth.split(':')[1]
      }
    }
 
    this.options = Utils._.extend({
      dialect: 'mysql',
      dialectModulePath: null,
      host: 'localhost',
      port: 3306,
      protocol: 'tcp',
      define: {},
      query: {},
      sync: {},
      logging: false,
      omitNull: false,
      queue: true,
      native: false,
      replication: false,
      ssl: undefined,
      pool: {},
      quoteIdentifiers: true,
      language: 'en'
    }, options || {})
 
    Iif (this.options.logging === true) {
      console.log('DEPRECATION WARNING: The logging-option should be either a function or false. Default: console.log')
      this.options.logging = console.log
    }
 
    this.config = {
      database: database,
      username: username,
      password: (( (["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
      host    : this.options.host,
      port    : this.options.port,
      pool    : this.options.pool,
      protocol: this.options.protocol,
      queue   : this.options.queue,
      native  : this.options.native,
      ssl     : this.options.ssl,
      replication: this.options.replication,
      dialectModulePath: this.options.dialectModulePath,
      maxConcurrentQueries: this.options.maxConcurrentQueries,
      dialectOptions: this.options.dialectOptions,
    }
 
    try {
      var Dialect = require("./dialects/" + this.getDialect())
      this.dialect = new Dialect(this)
    } catch(err) {
      throw new Error("The dialect " + this.getDialect() + " is not supported.")
    }
    this.daoFactoryManager  = new DAOFactoryManager(this)
    this.transactionManager = new TransactionManager(this)
 
    this.importCache = {}
  }
 
  /**
    Reference to Utils
  */
  Sequelize.Utils = Utils
 
  for (var dataType in DataTypes) {
    Sequelize[dataType] = DataTypes[dataType]
  }
 
  /**
   * Polyfill for the default connector manager.
   */
  Object.defineProperty(Sequelize.prototype, 'connectorManager', {
    get: function() {
      return this.transactionManager.getConnectorManager()
    }
  })
 
  /**
   * Returns the specified dialect.
   *
   * @return {String} The specified dialect.
   */
  Sequelize.prototype.getDialect = function() {
    return this.options.dialect
  }
 
  /**
   Returns an instance of QueryInterface.
 
   @method getQueryInterface
   @return {QueryInterface} An instance (singleton) of QueryInterface.
   */
  Sequelize.prototype.getQueryInterface = function() {
    this.queryInterface = this.queryInterface || new QueryInterface(this)
    return this.queryInterface
  }
 
  /**
   Returns an instance (singleton) of Migrator.
 
   @method getMigrator
   @param {Object} [options={}] Some options
   @param {Boolean} [force=false] A flag that defines if the migrator should get instantiated or not.
   @return {Migrator} An instance of Migrator.
   */
  Sequelize.prototype.getMigrator = function(options, force) {
    var Migrator = require("./migrator")
 
    if (force) {
      this.migrator = new Migrator(this, options)
    } else {
      this.migrator = this.migrator || new Migrator(this, options)
    }
 
    return this.migrator
  }
 
  Sequelize.prototype.define = function(daoName, attributes, options) {
    options = options || {}
    var self = this
      , globalOptions = this.options
 
    Eif (globalOptions.define) {
      options = Utils._.extend({}, globalOptions.define, options)
      Utils._(['classMethods', 'instanceMethods']).each(function(key) {
        Iif (globalOptions.define[key]) {
          options[key] = options[key] || {}
          Utils._.extend(options[key], globalOptions.define[key])
        }
      })
    }
 
    options.omitNull = globalOptions.omitNull
    options.language = globalOptions.language
 
    // If you don't specify a valid data type lets help you debug it
    Utils._.each(attributes, function(dataType, name) {
      if (Utils.isHash(dataType)) {
        dataType = dataType.type
      }
 
      Iif (dataType === undefined) {
        throw new Error('Unrecognized data type for field '+ name)
      }
 
      Iif (dataType.toString() === "ENUM") {
        attributes[name].validate = attributes[name].validate || {
          _checkEnum: function(value) {
            var hasValue        = value !== undefined
              , isMySQL         = ['mysql', 'mariadb'].indexOf(self.options.dialect) !== -1
              , ciCollation     = !!options.collate && options.collate.match(/_ci$/i) !== null
              , valueOutOfScope
 
 
            if (isMySQL && ciCollation && hasValue) {
              var scopeIndex = (attributes[name].values || []).map(function(d) { return d.toLowerCase() }).indexOf(value.toLowerCase())
              valueOutOfScope = scopeIndex === -1
            } else {
              valueOutOfScope = ((attributes[name].values || []).indexOf(value) === -1)
            }
 
            if (hasValue && valueOutOfScope && !(attributes[name].allowNull === true && values[attrName] === null)) {
              throw new Error('Value "' + value + '" for ENUM ' + name + ' is out of allowed scope. Allowed values: ' + attributes[name].values.join(', '))
            }
          }
        }
      }
    })
 
    // 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))
    }
 
    var factory = new DAOFactory(daoName, attributes, options)
    this.daoFactoryManager.addDAO(factory.init(this.daoFactoryManager))
 
    return factory
  }
 
  /**
   Fetch a DAO factory
 
   @param {String} daoName The name of a model defined with Sequelize.define
   @returns {DAOFactory} The DAOFactory for daoName
   */
  Sequelize.prototype.model = function(daoName) {
    if(!this.isDefined(daoName)) {
      throw new Error(daoName + ' has not been defined')
    }
 
    return this.daoFactoryManager.getDAO(daoName)
  }
 
  Sequelize.prototype.isDefined = function(daoName) {
    var daos = this.daoFactoryManager.daos
    return (daos.filter(function(dao) { return dao.name === daoName }).length !== 0)
  }
 
  Sequelize.prototype.import = function(path) {
    // is it a relative path?
    if (Path.normalize(path).indexOf(path.sep) !== 0) {
      // make path relative to the caller
      var callerFilename = Utils.stack()[1].getFileName()
        , callerPath     = Path.dirname(callerFilename)
 
      path = Path.resolve(callerPath, path)
    }
 
    if (!this.importCache[path]) {
      var defineCall = (arguments.length > 1 ? arguments[1] : require(path))
      this.importCache[path] = defineCall(this, DataTypes)
    }
 
    return this.importCache[path]
  }
 
  Sequelize.prototype.migrate = function(options) {
    return this.getMigrator().migrate(options)
  }
 
  Sequelize.prototype.query = function(sql, callee, options, replacements) {
    Iif (arguments.length === 4) {
      if (Array.isArray(replacements)) {
        sql = Utils.format([sql].concat(replacements), this.options.dialect)
      }
      else {
        sql = Utils.formatNamedParameters(sql, replacements, this.options.dialect)
      }
    } else if (arguments.length === 3) {
      options = options
    } else Iif (arguments.length === 2) {
      options = {}
    } else {
      options = { raw: true }
    }
 
    options = Utils._.extend(Utils._.clone(this.options.query), options)
    options = Utils._.defaults(options, {
      logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
      type: (sql.toLowerCase().indexOf('select') === 0) ? 'SELECT' : false
    })
 
    return this.transactionManager.query(sql, callee, options)
  }
 
  Sequelize.prototype.createSchema = function(schema) {
    var chainer = new Utils.QueryChainer()
 
    chainer.add(this.getQueryInterface().createSchema(schema))
 
    return chainer.run()
  }
 
  Sequelize.prototype.showAllSchemas = function() {
    var chainer = new Utils.QueryChainer()
 
    chainer.add(this.getQueryInterface().showAllSchemas())
 
    return chainer.run()
  }
 
  Sequelize.prototype.dropSchema = function(schema) {
    var chainer = new Utils.QueryChainer()
 
    chainer.add(this.getQueryInterface().dropSchema(schema))
 
    return chainer.run()
  }
 
  Sequelize.prototype.dropAllSchemas = function() {
    var self = this
 
    var chainer = new Utils.QueryChainer()
    chainer.add(self.getQueryInterface().dropAllSchemas())
    return chainer.run()
  }
 
  Sequelize.prototype.sync = function(options) {
    options = options || {}
 
    Eif (this.options.sync) {
      options = Utils._.extend({}, this.options.sync, options)
    }
 
    options.logging = options.logging === undefined ? false : Boolean(options.logging)
 
    var chainer = new Utils.QueryChainer()
 
    // Topologically sort by foreign key constraints to give us an appropriate
    // creation order
 
    this.daoFactoryManager.forEachDAO(function(dao) {
      chainer.add(dao, 'sync', [options])
    })
 
    return chainer.runSerially()
  }
 
  Sequelize.prototype.drop = function() {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer
 
      self.daoFactoryManager.daos.forEach(function(dao) { chainer.add(dao.drop()) })
 
      chainer
        .run()
        .success(function() { emitter.emit('success', null) })
        .error(function(err) { emitter.emit('error', err) })
    }).run()
  }
 
  Sequelize.prototype.authenticate = function() {
    var self = this
 
    return new Utils.CustomEventEmitter(function(emitter) {
      self
        .query('SELECT 1+1 AS result', null, { raw: true, plain: true })
        .complete(function(err, result) {
          if (!!err) {
            emitter.emit('error', new Error('Invalid credentials.'))
          } else {
            emitter.emit('success')
          }
        })
    }).run()
  }
 
  Sequelize.fn = Sequelize.prototype.fn = function (fn) {
    return new Utils.fn(fn, Array.prototype.slice.call(arguments, 1))
  }
 
  Sequelize.col = Sequelize.prototype.col = function (col) {
    return new Utils.col(col)
  }
 
  Sequelize.cast = Sequelize.prototype.cast = function (val, type) {
    return new Utils.cast(val, type)
  }
 
  Sequelize.literal = Sequelize.prototype.literal = function (val) {
    return new Utils.literal(val)
  }
 
  Sequelize.asIs = Sequelize.prototype.asIs = function (val) {
    return new Utils.asIs(val)
  }
 
  Sequelize.prototype.transaction = function(_options, _callback) {
    var options     = (typeof _options === 'function') ? {} : _options
      , callback    = (typeof _options === 'function') ? _options : _callback
      , transaction = new Transaction(this, options)
      , self        = this
 
    Utils.tick(function() {
      transaction.prepareEnvironment(function() {
        callback(transaction)
      })
    })
 
    return transaction
  }
 
  return Sequelize
})()