Code coverage report for upstream/lib/utils.js

Statements: 69.47% (198 / 285)      Branches: 63.82% (157 / 246)      Functions: 72.58% (45 / 62)      Lines: 69.93% (193 / 276)     

All files » upstream/lib/ » utils.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 5971               1   1     1 1                       3162   3162       3162           60       60 130 130 127     60       1     1     63   63             510   510 510   510 9 9 9     501 6 6       501 2     501         501   32     32 4 4 5 4   1     5   4     32     32 32 32             501 51                     60         60     82 13 13 13 5 5             5     69     67 76 1             67 76 76   76     75       75 15 15   15   2 2 2                           9 9 9   4 4 4       60 60 60 2   58 58             60         60         60       60 88 13 13 5     75 74 74   2 1 1                                   9 9   9   64 64           60     35   9   6   2   2   2       1     5       4   2       1     1           38965                                       13 13 9 9 9 3   6         13     108       583       497                     443   443   443   443     443                       30806       69   69   69       69                                 338   338 338   338 270   270 978 791       270     338       242 154   154 188   188 127   61       154   88         39 39 39           2   2 2 2               2                             676 676 676       6566 6566               8100 8100     8100 8100             8 8     8                             12 372 372         678             1     1   1                   1 8 8 8             1 8       1 1 1  
var util               = require("util")
  , DataTypes          = require("./data-types")
  , SqlString          = require("./sql-string")
  , lodash             = require("lodash")
  , _string            = require('underscore.string')
  , ParameterValidator = require('./utils/parameter-validator')
  , uuid               = require('node-uuid')
 
var Utils = module.exports = {
  _: (function() {
    var _  = lodash
      , _s = _string
 
    _.mixin(_s.exports())
    _.mixin({
      includes: _s.include,
      camelizeIf: function(string, condition) {
        var result = string
 
        if (condition) {
          result = _.camelize(string)
        }
 
        return result
      },
      underscoredIf: function(string, condition) {
        var result = string
 
        Iif (condition) {
          result = _.underscored(string)
        }
 
        return result
      },
      /*
       * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey.
       */
      compactLite: function(array) {
        var index = -1,
          length = array ? array.length : 0,
          result = [];
 
        while (++index < length) {
          var value = array[index];
          if (typeof value === "boolean" || value === 0 || value) {
            result.push(value);
          }
        }
        return result;
      }
    })
 
    return _
  })(),
  addEventEmitter: function(_class) {
    util.inherits(_class, require('events').EventEmitter)
  },
  format: function(arr, dialect) {
    var timeZone = null;
    // Make a clone of the array beacuse format modifies the passed args
    return SqlString.format(arr[0], arr.slice(1), timeZone, dialect)
  },
  formatNamedParameters: function(sql, parameters, dialect) {
    var timeZone = null;
    return SqlString.formatNamedParameters(sql, parameters, timeZone, dialect)
  },
  injectScope: function(scope, merge) {
    var self = this
 
    scope = scope || {}
    self.scopeObj = self.scopeObj || {}
 
    if (Array.isArray(scope.where)) {
      self.scopeObj.where = self.scopeObj.where || []
      self.scopeObj.where.push(scope.where)
      return true
    }
 
    if (typeof scope.order === "string") {
      self.scopeObj.order = self.scopeObj.order || []
      self.scopeObj.order[self.scopeObj.order.length] = scope.order
    }
 
    // Limit and offset are *always* merged.
    if (!!scope.limit) {
      self.scopeObj.limit = scope.limit
    }
 
    Iif (!!scope.offset) {
      self.scopeObj.offset = scope.offset
    }
 
    // Where objects are a mixed variable. Possible values are arrays, strings, and objects
    if (!!scope.where) {
      // Begin building our scopeObj
      self.scopeObj.where = self.scopeObj.where || []
 
      // Reset if we're merging!
      if (merge === true && !!scope.where && !!self.scopeObj.where) {
        var scopeKeys = Object.keys(scope.where)
        self.scopeObj.where = self.scopeObj.where.map(function(scopeObj) {
          if (!Array.isArray(scopeObj) && typeof scopeObj === "object") {
            return lodash.omit.apply(undefined, [scopeObj].concat(scopeKeys))
          } else {
            return scopeObj
          }
        }).filter(function(scopeObj) {
          return !lodash.isEmpty(scopeObj)
        })
        self.scopeObj.where = self.scopeObj.where.concat(scope.where)
      }
 
      Iif (Array.isArray(scope.where)) {
        self.scopeObj.where.push(scope.where)
      }
      else Eif (typeof scope.where === "object") {
        Object.keys(scope.where).forEach(function(){
          self.scopeObj.where.push(scope.where)
        })
      } else { // Assume the value is a string
        self.scopeObj.where.push([scope.where])
      }
    }
 
    if (!!self.scopeObj.where) {
      self.scopeObj.where = lodash.uniq(self.scopeObj.where)
    }
  },
  // smartWhere can accept an array of {where} objects, or a single {where} object.
  // The smartWhere function breaks down the collection of where objects into a more
  // centralized object for each column so we can avoid duplicates
  // e.g. WHERE username='dan' AND username='dan' becomes WHERE username='dan'
  // All of the INs, NOT INs, BETWEENS, etc. are compressed into one key for each column
  // This function will hopefully provide more functionality to sequelize in the future.
  // tl;dr It's a nice way to dissect a collection of where objects and compress them into one object
  smartWhere: function(whereArg, dialect) {
    var self = this
      , _where = {}
      , logic
      , type
 
    (Array.isArray(whereArg) ? whereArg : [whereArg]).forEach(function(where) {
      // If it's an array we're already good... / it's in a format that can't be broken down further
      // e.g. Util.format['SELECT * FROM world WHERE status=?', 'hello']
      if (Array.isArray(where)) {
        _where._ = where._ || {queries: [], bindings: []}
        _where._.queries[_where._.queries.length] = where[0]
        if (where.length > 1) {
          var values = where.splice(1)
          Iif (dialect === "sqlite") {
            values.forEach(function(v, i) {
              if (typeof v === "boolean") {
                values[i] = (v === true ? 1 : 0)
              }
            })
          }
          _where._.bindings = _where._.bindings.concat(values)
        }
      }
      else if (typeof where === "object") {
        // First iteration is trying to compress IN and NOT IN as much as possible...
        // .. reason being is that WHERE username IN (?) AND username IN (?) != WHERE username IN (?,?)
        Object.keys(where).forEach(function(i) {
          if (Array.isArray(where[i])) {
            where[i] = {
              in: where[i]
            }
          }
        })
 
        // Build our smart object
        Object.keys(where).forEach(function(i) {
          type = typeof where[i]
          _where[i] = _where[i] || {}
 
          if (where[i] === null) {
            // skip nulls
          }
          else Iif (Array.isArray(where[i])) {
            _where[i].in = _where[i].in || []
            _where[i].in.concat(where[i])
          }
          else if (type === "object") {
            Object.keys(where[i]).forEach(function(ii) {
              logic = self.getWhereLogic(ii, where[i][ii]);
 
              switch(logic) {
              case 'IN':
                _where[i].in = _where[i].in || []
                _where[i].in = _where[i].in.concat(where[i][ii]);
                break
              case 'NOT':
                _where[i].not = _where[i].not || []
                _where[i].not = _where[i].not.concat(where[i][ii]);
                break
              case 'BETWEEN':
                _where[i].between = _where[i].between || []
                _where[i].between[_where[i].between.length] = [where[i][ii][0], where[i][ii][1]]
                break
              case 'NOT BETWEEN':
                _where[i].nbetween = _where[i].nbetween || []
                _where[i].nbetween[_where[i].nbetween.length] = [where[i][ii][0], where[i][ii][1]]
                break
              case 'JOIN':
                _where[i].joined = _where[i].joined || []
                _where[i].joined[_where[i].joined.length] = where[i][ii]
                break
              default:
                _where[i].lazy = _where[i].lazy || {conditions: [], bindings: []}
                _where[i].lazy.conditions[_where[i].lazy.conditions.length] = logic + ' ?'
                _where[i].lazy.bindings = _where[i].lazy.bindings.concat(where[i][ii])
              }
            })
          }
          else Eif (type === "string" || type === "number" || type === "boolean") {
            _where[i].lazy = _where[i].lazy || {conditions: [], bindings: []}
            if (type === "boolean") {
              _where[i].lazy.conditions[_where[i].lazy.conditions.length] = '= ' + SqlString.escape(where[i], false, null, dialect) // sqlite is special
            } else {
              _where[i].lazy.conditions[_where[i].lazy.conditions.length] = '= ?'
              _where[i].lazy.bindings = _where[i].lazy.bindings.concat(where[i])
            }
          }
        })
      }
    })
 
    return _where
  },
  // Converts {smart where} object(s) into an array that's friendly for Utils.format()
  // NOTE: Must be applied/called from the QueryInterface
  compileSmartWhere: function(obj, dialect) {
    var self = this
      , whereArgs = []
      , text = []
      , columnName
 
    Iif (typeof obj !== "object") {
      return obj
    }
 
    for (var column in obj) {
      if (column === "_") {
        text[text.length] = obj[column].queries.join(' AND ')
        if (obj[column].bindings.length > 0) {
          whereArgs = whereArgs.concat(obj[column].bindings)
        }
      } else {
        Object.keys(obj[column]).forEach(function(condition) {
          columnName = self.QueryInterface.quoteIdentifiers(column)
          switch(condition) {
          case 'in':
            text[text.length] = columnName + ' IN (' + obj[column][condition].map(function(){ return '?' }) + ')'
            whereArgs = whereArgs.concat(obj[column][condition])
            break
          case 'not':
            text[text.length] = columnName + ' NOT IN (' + obj[column][condition].map(function(){ return '?' }) + ')'
            whereArgs = whereArgs.concat(obj[column][condition])
            break
          case 'between':
            Object.keys(obj[column][condition]).forEach(function(row) {
              text[text.length] = columnName + ' BETWEEN ? AND ?'
              whereArgs = whereArgs.concat(obj[column][condition][row][0], obj[column][condition][row][1])
            })
            break
          case 'nbetween':
            Object.keys(obj[column][condition]).forEach(function(row) {
              text[text.length] = columnName + ' BETWEEN ? AND ?'
              whereArgs = whereArgs.concat(obj[column][condition][row][0], obj[column][condition][row][1])
            })
            break
          case 'joined':
            Object.keys(obj[column][condition]).forEach(function(row) {
              text[text.length] = columnName + ' = ' + self.QueryInterface.quoteIdentifiers(obj[column][condition][row])
            })
            break
          default: // lazy
            text = text.concat(obj[column].lazy.conditions.map(function(val){ return columnName + ' ' + val }))
            whereArgs = whereArgs.concat(obj[column].lazy.bindings)
          }
        })
      }
    }
 
    return Utils._.compactLite([text.join(' AND ')].concat(whereArgs))
  },
  getWhereLogic: function(logic, val) {
    switch (logic) {
    case 'join':
      return 'JOIN'
    case 'gte':
      return '>='
    case 'gt':
      return '>'
    case 'lte':
      return '<='
    case 'lt':
      return '<'
    case 'eq':
      return '='
    case 'ne':
      return val ? '!=' : 'IS NOT'
    case 'between':
    case '..':
      return 'BETWEEN'
    case 'nbetween':
    case 'notbetween':
    case '!..':
      return 'NOT BETWEEN'
    case 'in':
      return 'IN'
    case 'not':
      return 'NOT IN'
    case 'like':
      return 'LIKE'
    case 'nlike':
    case 'notlike':
      return 'NOT LIKE'
    default:
      return ''
    }
  },
  isHash: function(obj) {
    return Utils._.isObject(obj) && !Array.isArray(obj);
  },
  hasChanged: function(attrValue, value) {
    //If attribute value is Date, check value as a date
    if (Utils._.isDate(attrValue) && !Utils._.isDate(value)) {
      value = new Date(value)
    }
 
    if (Utils._.isDate(attrValue)) {
      return attrValue.valueOf() !== value.valueOf()
    }
 
    //If both of them are empty, don't set as changed
    if ((attrValue === undefined || attrValue === null || attrValue === '') && (value === undefined || value === null || value === '')) {
      return false
    }
 
    return attrValue !== value
  },
  argsArePrimaryKeys: function(args, primaryKeys) {
    var result = (args.length == Object.keys(primaryKeys).length)
    if (result) {
      Utils._.each(args, function(arg) {
        Eif (result) {
          if (['number', 'string'].indexOf(typeof arg) !== -1) {
            result = true
          } else {
            result = (arg instanceof Date)
          }
        }
      })
    }
    return result
  },
  combineTableNames: function(tableName1, tableName2) {
    return (tableName1.toLowerCase() < tableName2.toLowerCase()) ? (tableName1 + tableName2) : (tableName2 + tableName1)
  },
 
  singularize: function(s, language) {
    return Utils.Lingo[language || 'en'].isSingular(s) ? s : Utils.Lingo[language || 'en'].singularize(s)
  },
 
  pluralize: function(s, language) {
    return Utils.Lingo[language || 'en'].isPlural(s) ? s : Utils.Lingo[language || 'en'].pluralize(s)
  },
 
  removeCommentsFromFunctionString: function(s) {
    s = s.replace(/\s*(\/\/.*)/g, '')
    s = s.replace(/(\/\*[\n\r\s\S]*?\*\/)/mg, '')
 
    return s
  },
 
  toDefaultValue: function(value) {
    Iif (lodash.isFunction(value)) {
      return value()
    } else Iif (value === DataTypes.UUIDV1) {
      return uuid.v1()
    } else Iif (value === DataTypes.UUIDV4) {
      return uuid.v4()
    } else Iif (value === DataTypes.NOW) {
      return Utils.now()
    } else {
      return value
    }
  },
 
  /**
   * Determine if the default value provided exists and can be described
   * in a db schema using the DEFAULT directive.
   *
   * @param  {*} value Any default value.
   * @return {boolean} yes / no.
   */
  defaultValueSchemable: function(value) {
    if (typeof value === 'undefined') {return false}
 
    // TODO this will be schemable when all supported db
    // have been normalized for this case
    Iif (value === DataTypes.NOW) {return false}
 
    Iif (value === DataTypes.UUIDV1 || value === DataTypes.UUIDV4) {return false}
 
    Iif (lodash.isFunction(value)) {
      return false
    }
 
    return true
  },
 
  setAttributes: function(hash, identifier, instance, prefix) {
    prefix = prefix || ''
    if (this.isHash(identifier)) {
      this._.each(identifier, function(elem, key) {
        hash[prefix + key] = Utils._.isString(instance) ? instance : Utils._.isObject(instance) ? instance[elem.key || elem] : null
      })
    } else {
      hash[prefix + identifier] = Utils._.isString(instance) ? instance : Utils._.isObject(instance) ? instance.id : null
    }
 
    return hash
  },
 
  removeNullValuesFromHash: function(hash, omitNull, options) {
    var result = hash
 
    options = options || {}
    options.allowNull = options.allowNull || []
 
    if (omitNull) {
      var _hash = {}
 
      Utils._.each(hash, function(val, key) {
        if (options.allowNull.indexOf(key) > -1 || key.match(/Id$/) || ((val !== null) && (val !== undefined))) {
          _hash[key] = val
        }
      })
 
      result = _hash
    }
 
    return result
  },
 
  prependTableNameToHash: function(tableName, hash) {
    if (tableName) {
      var _hash = {}
 
      for (var key in hash) {
        Iif (key instanceof Utils.literal) {
          _hash[key] = hash[key]          
        } else if (key.indexOf('.') === -1) {
          _hash[tableName + '.' + key] = hash[key]
        } else {
          _hash[key] = hash[key]
        }
      }
 
      return _hash
    } else {
      return hash
    }
  },
 
  firstValueOfHash: function(obj) {
    for (var key in obj) {
      Eif (obj.hasOwnProperty(key))
        return obj[key]
    }
    return null
  },
 
  inherit: function(subClass, superClass) {
    Eif (superClass.constructor == Function) {
      // Normal Inheritance
      subClass.prototype = new superClass();
      subClass.prototype.constructor = subClass;
      subClass.prototype.parent = superClass.prototype;
    } else {
      // Pure Virtual Inheritance
      subClass.prototype = superClass;
      subClass.prototype.constructor = subClass;
      subClass.prototype.parent = superClass;
    }
 
    return subClass;
  },
 
 
  stack: function() {
    var orig = Error.prepareStackTrace;
    Error.prepareStackTrace = function(_, stack){ return stack; };
    var err = new Error();
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack;
    Error.prepareStackTrace = orig;
    return stack;
  },
 
  now: function(dialect) {
    var now = new Date()
    Eif(dialect != "postgres") now.setMilliseconds(0)
    return now
  },
 
  tick: function(func) {
    var tick = (typeof setImmediate !== "undefined" ? setImmediate : process.nextTick)
    tick(func)
  },
 
  // Note: Use the `quoteIdentifier()` and `escape()` methods on the
  // `QueryInterface` instead for more portable code.
 
  TICK_CHAR: '`',
  addTicks: function(s, tickChar) {
    tickChar = tickChar || Utils.TICK_CHAR
    return tickChar + Utils.removeTicks(s, tickChar) + tickChar
  },
  removeTicks: function(s, tickChar) {
    tickChar = tickChar || Utils.TICK_CHAR
    return s.replace(new RegExp(tickChar, 'g'), "")
  },
  /*
   * Utility functions for representing SQL functions, and columns that should be escaped.
   * Please do not use these functions directly, use Sequelize.fn and Sequelize.col instead.
   */
  fn: function (fn, args) {
    this.fn = fn
    this.args = args
  },
  col: function (col) {
    this.col = col
  },
  cast: function (val, type) {
    this.val  = val
    this.type = (type || '').trim()
  },
  literal: function (val) {
    this.val = val
  },
 
  asIs: function(val) {
    this.val = val
  },
 
  generateUUID: function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8)
      return v.toString(16)
    })
  },
 
  validateParameter: function(value, expectation, options) {
    return ParameterValidator.check(value, expectation, options)
  }
}
 
// I know this may seem silly, but this gives us the ability to recognize whether
// or not we should be escaping or if we should trust the user. Basically, it
// keeps things in perspective and organized.
Utils.literal.prototype.toString = function() {
  return this.val
}
Utils.asIs.prototype = Utils.literal.prototype
 
Utils.cast.prototype.toString = function(queryGenerator) {
  if (!this.val instanceof Utils.fn && !this.val instanceof Utils.col && !this.val instanceof Utils.literal) {
    this.val = queryGenerator.escape(this.val)
  } else {
    this.val = this.val.toString(queryGenerator)
  }
 
  return 'CAST(' + this.val + ' AS ' + this.type.toUpperCase() + ')'
}
 
Utils.fn.prototype.toString = function(queryGenerator) {
  return this.fn + '(' + this.args.map(function (arg) {
    Eif (arg instanceof Utils.fn || arg instanceof Utils.col) {
      return arg.toString(queryGenerator)
    } else {
      return queryGenerator.escape(arg)
    }
  }).join(', ') + ')'
}
 
Utils.col.prototype.toString = function (queryGenerator) {
  Eif (this.col.indexOf('*') !== -1) return '*'
  return queryGenerator.quote(this.col)
}
 
Utils.CustomEventEmitter = require(__dirname + "/emitters/custom-event-emitter")
Utils.QueryChainer = require(__dirname + "/query-chainer")
Utils.Lingo = require("lingo")