Example #1
0
    _.each(args, function(arg) {
      if (_.isNumber(arg) || _.isString(arg)) {
        var criteria = {};
        criteria[self.table.pk] = args[0];
        return self.where(criteria);
      }

      var columns = arg.columns || arg;
      if (_.isArray(columns)) { self.sql = self.sql.replace("*", columns.join(",")); }
      if (_.isString(columns)) { self.sql = self.sql.replace("*", columns); }
      delete arg.columns;

      var where = arg.where || arg;
      if (!_.isArray(where) && _.isObject(where) && _.size(where) > 0) { self.where(where); }

    });
Example #2
0
Queryable.prototype.find = function(){
  var args = ArgTypes.findArgs(arguments);

  //set default options
  //if our inheriting object defines a primary key use that as the default order
  args.options.order = args.options.order || (this.hasOwnProperty("pk") ? util.format('"%s"', this.pk) : "1");
  args.options.limit = args.options.limit || "1000";
  args.options.offset = args.options.offset || "0";
  args.options.columns = args.options.columns || "*";

  if(_.isFunction(args.conditions)){
    //this is our callback as the only argument, caught by Args.ANY
    args.next = args.conditions;
  }

  var returnSingle = false;
  var where, order, limit, cols="*", offset;

  if(args.options.columns){
    if(_.isArray(args.options.columns)){
      cols = args.options.columns.join(',');
    }else{
      cols = args.options.columns;
    }
  }
  order = " order by " + args.options.order;
  limit = " limit " + args.options.limit;
  offset = " offset " + args.options.offset;

  if(_.isNumber(args.conditions) || isUUID(args.conditions)) {
    //a primary key search
    var newArgs = {};
    newArgs[this.primaryKeyName()] = args.conditions;
    args.conditions = newArgs;
    returnSingle = true;
  }

  where = _.isEmpty(args.conditions) ? {where : " "} : Where.forTable(args.conditions);

  var sql = "select " + cols + " from " + this.delimitedFullName + where.where + order + limit + offset;

  if (args.options.stream) {
    this.db.stream(sql, where.params, null, args.next);
  } else {
    this.db.query(sql, where.params, {single : returnSingle}, args.next);
  }
};
Example #3
0
SfDate.toDateTimeLiteral = function(date) {
  if (_.isNumber(date)) {
    date = new Date(date);
  } else if (_.isString(date)) {
    date = SfDate.parseDate(date);
  }
  var yy = date.getUTCFullYear();
  var mm = date.getUTCMonth()+1;
  var dd = date.getUTCDate();
  var hh = date.getUTCHours();
  var mi = date.getUTCMinutes();
  var ss = date.getUTCSeconds();
  var dtstr =
    [ yy, zeropad(mm), zeropad(dd) ].join("-") + "T" +
    [ zeropad(hh), zeropad(mi), zeropad(ss) ].join(":") + "Z";
  return new SfDate(dtstr);
};
Example #4
0
    _.each(conditions, function(value, key) {
      var parts = key.trim().split(/ +/);
      var property = parts[0];
      var operation = operationsMap[parts[1]] || '=';

      if (_.isBoolean(value) || _.isNumber(value)) {
        return _conditions.push(util.format('"%s" %s %d', property, operation, value));
      }

      if (!_.isArray(value)) {
        self.params.push(value);
        return _conditions.push(util.format('"%s" %s %s', property, operation, self.db.placeholder(self.params.length)));
      }

      var arrayConditions = [];
      _.each(value, function(v) {
        self.params.push(v);
        arrayConditions.push(self.db.placeholder(self.params.length));
      });
      _conditions.push(util.format('"%s" %s (%s)', property, operation == '!=' || operation == '<>' ? 'NOT IN' : 'IN', arrayConditions.join(', ')));
    });
exports.coerce = function(expectedType, value) {
	var types = {
		'string': '',
		'number': 0,
		'array': [],
		'boolean': false
	};
	if (_.isDate(value)) {
		return value;
	}
	if (expectedType === 'date' && !_.isDate(value)) {
		return (value && new Date(value)) || new Date('1970/1/1');
	}
	if (expectedType && typeof value === 'undefined') {
		return types[expectedType];
	}
	if (expectedType && typeof value !== 'undefined') {
		if (expectedType === 'string') {
			return (value && value.toString()) || '';						
		}
		if (expectedType === 'number') {
			return _.isNumber(_.toInt(value)) ? _.toInt(value) : types.number;
		}
		if (expectedType === 'array') {
			return _.isArray(value) ? value : [ value || '' ];
		}
		if (expectedType === 'boolean') {
			if (value === 'true') {
				return true;
			}
			if (value === 'false') {
				return false;
			}
			return _.isBoolean(value) ? value : types.boolean;
		}
	}
	return value || '';
};
Example #6
0
  self.where = function(conditions) {
    if (_.isUndefined(conditions)) { return self; }

    if(_.isNumber(conditions)) {
      return self._append(" \nWHERE \"%s\" = %d", self.table.pk, conditions);
    }
    if (_.isString(conditions)) {
      self.params.push(conditions);
      return self._append(" \nWHERE \"%s\" = %s", self.table.pk, self.db.placeholder(self.params.length));
    }

    var _conditions = [];
    _.each(conditions, function(value, key) {
      var parts = key.trim().split(/ +/);
      var property = parts[0];
      var operation = operationsMap[parts[1]] || '=';

      if (_.isBoolean(value) || _.isNumber(value)) {
        return _conditions.push(util.format('"%s" %s %d', property, operation, value));
      }

      if (!_.isArray(value)) {
        self.params.push(value);
        return _conditions.push(util.format('"%s" %s %s', property, operation, self.db.placeholder(self.params.length)));
      }

      var arrayConditions = [];
      _.each(value, function(v) {
        self.params.push(v);
        arrayConditions.push(self.db.placeholder(self.params.length));
      });
      _conditions.push(util.format('"%s" %s (%s)', property, operation == '!=' || operation == '<>' ? 'NOT IN' : 'IN', arrayConditions.join(', ')));
    });

    return self._append(' \nWHERE ' + _conditions.join(' \nAND '));
  };
Example #7
0
 number:  function() { return _.isNumber(this); },
Example #8
0
 function is_instance_and_has_id (v){
     return ((!_.isUndefined(v)) && (_.isNumber(v.__id__) || (!_.isUndefined(v.__data__) && _.isNumber(v.__data__.__id__))));
 }
exports.isPkSearch = function(conditions) {
  return _.isNumber(conditions) || (_.isString(conditions) && isUuid.test(conditions));
};
exports.docPredicate = function (result, condition, value, conditions) {
  //if we have an array of objects, this is a deep traversal
  //we'll need to use a contains query to be sure we flex the index
  if(_.isArray(value) && _.isObject(value[0])) {
    //stringify the passed-in params
    result.params.push(JSON.stringify(conditions));
    result.predicates.push(util.format("body @> $%s", result.params.length + result.offset));
  }

  //if we have equality here, just use a JSON contains
  else if (condition.operator === '=' && !_.isArray(value)) {
    //parse the value into stringy JSON
    var param = {};
    param[condition.field]=value;
    result.params.push(JSON.stringify(param));
    result.predicates.push(util.format("body @> $%s", result.params.length + result.offset));
    return result;
  }

  //comparison stuff - same as method above but this time
  //we'll be coercing the document key values using pg's ::
  //not ideal, but it works nicely
  else if (_.isBoolean(value)) {
    result.predicates.push(
      util.format("(body ->> '%s')::boolean %s %s", condition.field, condition.operator, value)
    );
  } else if(_.isDate(value)) {
    result.params.push(value);
    result.predicates.push(
      util.format("(body ->> '%s')::timestamp %s $%d",
        condition.field,
        condition.operator,
        result.params.length + result.offset)
    );
  } else if(_.isNumber(value)) {
    result.predicates.push(
      util.format("(body ->> '%s')::decimal %s %d", condition.field, condition.operator, value)
    );
  }

  //anything non-array handling
  else if (!_.isArray(value)) {
    result.params.push(value);
    result.predicates.push(
      util.format("(body ->> '%s') %s $%s",
        condition.field,
        condition.operator,
        result.params.length + result.offset)
    );
  } else {
    var arrayConditions = [];

    _.each(value, function(v) {
      result.params.push(v);
      arrayConditions.push("$" + (result.params.length + result.offset));
    });

    condition.operator = condition.operator === '=' ? 'IN' : 'NOT IN';

    result.predicates.push(
      util.format("(body ->> '%s') %s (%s)",
        condition.field,
        condition.operator,
        arrayConditions.join(', '))
    );
  }

  return result;
};
Example #11
0
    getState: function() {
        // There are five parameters that contribute to the state:
        // `hangout-start-time`, `hangout-url`, `hangout-pending`,
        // `hangout-stop-request-time`, and `connectedParticipants`.  However, there
        // are only two fully valid and two limbo combinations of these:
        // valid:
        //  "started", "stopped"
        // limbo:
        //  "pending", "stopping"
        //
        // "started": {
        //     "hangout-start-time": <int>,
        //     "hangout-url": <string>,
        //     "hangout-pending": null,
        //     "hangout-stop-request-time": null,
        //     "connectedParticipants": [list of length more than 0],
        // }
        // "stopped": {
        //     "hangout-start-time": null,
        //     "hangout-url": null,
        //     "hangout-pending": null,
        //     "hangout-stop-request-time": null,
        //     "connectedParticipants": []
        // }
        // "pending": {
        //     "hangout-start-time": null,
        //     "hangout-url": null,
        //     "hangout-pending": null,
        //     "hangout-stop-request-time": null,
        //     "connectedParticipants": []
        // }
        // "stopping": {
        //     "hangout-start-time": <int>,
        //     "hangout-url": <string>,
        //     "hangout-pending": null,
        //     "hangout-stop-request-time": <timestamp integer>,
        //     "connectedParticipants": []
        // }
        //
        // Any other combination of values -- a hangout-url with zero
        // participants, a hangout-start-time with no hangout-url, etc. is an
        // error condition.

        var pending = !_.isNull(this.get("hangout-pending"));
        var pendingStale = pending && (
            (new Date().getTime() - this.get("hangout-pending").time) > this.HANGOUT_CREATION_TIMEOUT
        );
        var stopping = !_.isNull(this.get("hangout-stop-request-time"));
        var stoppingStale = stopping && (
            (new Date().getTime() - this.get("hangout-stop-request-time")) > this.HANGOUT_LEAVE_STOP_TIMEOUT
        );
        var hasUrl = _.isString(this.get("hangout-url"));
        var hasStartTime = _.isNumber(this.get("hangout-start-time"));
        var hasParticipants = this.getNumConnectedParticipants();

        //
        // Valid states
        //
        if (!pending && hasUrl && hasStartTime && hasParticipants && !stopping) {
            return "started";
        }
        if (!pending && !hasUrl && !hasStartTime && !hasParticipants && !stopping) {
            return "stopped";
        }
        if (pending && !pendingStale && !hasUrl && !hasStartTime && !hasParticipants && !stopping) {
            return "pending";
        }
        if (!pending && hasUrl && hasStartTime && !hasParticipants && stopping && !stoppingStale) {
            return "stopping";
        }

        //
        // Problem states
        //
        var problems = [];
        if (pendingStale) { problems.push("pending overdue"); }
        if (stoppingStale) { problems.push("stopping overdue"); }
        if (pending) { problems.push("uncleared pending"); }
        if (stopping) { problems.push("uncleared stopping"); }
        if (hasParticipants) {
            if (!hasUrl) { problems.push("no url"); }
            if (!hasStartTime) { problems.push("no start time"); }
        } else {
            if (hasUrl) { problems.push("stale url"); }
            if (hasStartTime) { problems.push("unstopped"); }
        }
        return problems.join("; ");
    },
Example #12
0
console.log(_.omit({name:'tom', age:4}, 'name'));//{ age: 4 }
// has 判断对象是否包含指定的属性名
console.log(_.has({a:1, b:2, c:3}, 'b')); //true
// isEqual: 判断两个对象是值相等
var moe = {name:'moe', b:[1,2,3]};
var clone = {name:'moe', b:[1,2,3]};
console.log(moe==clone);//false
console.log(_.isEqual(moe, clone));//true
//判断对象类型以下都为空
console.log(_.isEmpty({})); //如果object里没包含任何东西,将返回true
console.log(_.isArray([1,2,3]));
console.log(_.isObject({}));
console.log((function(){ return _.isArguments(arguments); })(1, 2, 3));
console.log(_.isFunction(console.log));
console.log(_.isString("moe"));
console.log(_.isNumber(8.4 * 5));
console.log(_.isFinite(-101));
console.log(_.isBoolean(true));
console.log(_.isDate(new Date()));
console.log(_.isNaN(NaN));
console.log(_.isNull(null));
console.log(_.isUndefined(undefined));

// invert _.invert(object)
// 返回一个object的副本,并且里面的键和值是对调的,要使之有效,必须确保object里所有的值都是唯一的且可以序列号成字符串
console.log(_.invert({a:'b', c:'d', e:'f'})); // { b: 'a', d: 'c', f: 'e' }

// pairs _.pairs(object)
// 把一个对象转换成一个[key, value]形式的数组
console.log(_.pairs({one:1, two:2, three: 3})); // [ [ 'one', 1 ], [ 'two', 2 ], [ 'three', 3 ] ]
Example #13
0
 var getQueuedLoop = function(offset) {
     return loops[loops.length - (1 + (_.isNumber(offset) ? offset : 0))];
 };
Example #14
0
var typecast = function(value, originalValue, properties) {
  // Allow transform to manipulate raw properties.
  if(properties.transform) {
    value = properties.transform.call(this, value, originalValue, properties);
  }

  switch(properties.type) {
    case 'string':
      // Reject if object or array.
      if(_.isObject(value) || _.isArray(value)) {
        throw new SetterError('String type cannot typecast Object or Array types.', value, originalValue, properties);
      }

      // If index is being set with null or undefined, set value and end.
      if(_.isUndefined(value) || value === null) {
        return value;
      }

      // Typecast to String.
      value = value + '';

      // If stringTransform function is defined, use.
      // This is used before we do validation checks (except to be sure we have a string at all).
      if(properties.stringTransform) {
        value = properties.stringTransform.call(this, value, originalValue, properties);
      }

      // If clip property & maxLength properties are set, the string should be clipped.
      // This is basically a shortcut property that could be done with stringTransform.
      if(properties.clip && !_.isUndefined(properties.maxLength)) {
        value = value.substr(0, properties.maxLength);
      }

      // If enum is being used, be sure the value is within definition.
      if(_.isArray(properties.enum) && properties.enum.indexOf(value) === -1) {
        throw new SetterError('String does not exist in enum list.', value, originalValue, properties);
      }

      // If minLength is defined, check to be sure the string is > minLength.
      if(!_.isUndefined(properties.minLength) && value.length < properties.minLength) {
        throw new SetterError('String length too short to meet minLength requirement.', value, originalValue, properties);
      }

      // If maxLength is defined, check to be sure the string is < maxLength.
      if(!_.isUndefined(properties.maxLength) && value.length > properties.maxLength) {
        throw new SetterError('String length too long to meet maxLength requirement.', value, originalValue, properties);
      }

      // If regex is defined, check to be sure the string matches the regex pattern.
      if(properties.regex && !properties.regex.test(value)) {
        throw new SetterError('String does not match regular expression pattern.', value, originalValue, properties);
      }

      return value;
      break;

    case 'number':
      // Set values for boolean.
      if(_.isBoolean(value)) {
        value = value ? 1 : 0;
      }

      // Reject if array, object, or not numeric.
      if( _.isArray(value) || _.isObject(value) || !isNumeric(value)) {
        throw new SetterError('Number type cannot typecast Array or Object types.', value, originalValue, properties);
      }

      // Typecast to number.
      value = value * 1;

      // Transformation after typecasting but before validation and filters.
      if(properties.numberTransform) {
        value = properties.numberTransform.call(this, value, originalValue, properties);
      }

      if(!_.isUndefined(properties.min) && value < properties.min) {
        throw new SetterError('Number is too small to meet min requirement.', value, originalValue, properties);
      }

      if(!_.isUndefined(properties.max) && value > properties.max) {
        throw new SetterError('Number is too big to meet max requirement.', value, originalValue, properties);
      }

      return value;
      break;

    case 'boolean':
      // If is String and is 'false', return false.
      if(value === 'false') {
        return false;
      }

      // If is Number, <0 is true and >0 is false.
      if(isNumeric(value)) {
        return (value * 1) > 0 ? true : false;
      }

      // Use Javascript to eval and return boolean.
      value = value ? true : false;

      // Transformation after typecasting but before validation and filters.
      if(properties.booleanTransform) {
        value = properties.booleanTransform.call(this, value, originalValue, properties);
      }

      return value;
      break;

    case 'array':
      // If it's an object, typecast to an array and return array.
      if(_.isObject(value)) {
        value = _.toArray(value);
      }

      // Reject if not array.
      if(!_.isArray(value)) {
        throw new SetterError('Array type cannot typecast non-Array types.', value, originalValue, properties);
      }

      // Arrays are never set directly.
      // Instead, the values are copied over to the existing SchemaArray instance.
      // The SchemaArray is initialized immediately and will always exist.
      originalValue.length = 0;
      _.each(value, function(arrayValue) {
        originalValue.push(arrayValue);
      });

      return originalValue;
      break;

    case 'object':
      // If it's not an Object, reject.
      if(!_.isObject(value)) {
        throw new SetterError('Object type cannot typecast non-Object types.', value, originalValue, properties);
      }

      // If object is schema object and an entirely new object was passed, clear values and set.
      // This preserves the object instance.
      if(properties.objectType) {
        // The object will usually exist because it's initialized immediately for deep access within SchemaObjects.
        // However, in the case of Array elements, it will not exist.
        var schemaObject;
        if(!_.isUndefined(originalValue)) {
          // Clear existing values.
          schemaObject = originalValue;
          schemaObject.clear();
        } else {
          // The SchemaObject doesn't exist yet. Let's initialize a new one.
          // This is used for Array types.
          schemaObject = new properties.objectType;
        }

        // Copy value to SchemaObject and set value to SchemaObject.
        _.each(value, function(v, k) {
          schemaObject[k] = v;
        });
        value = schemaObject;
      }

      // Otherwise, it's OK.
      return value;
      break;

    case 'date':
      // Reject if object, array or boolean.
      if(!_.isDate(value) && !_.isString(value) && !_.isNumber(value)) {
        throw new SetterError('Date type cannot typecast Array or Object types.', value, originalValue, properties);
      }

      // Attempt to parse string value with Date.parse (which returns number of milliseconds).
      if(_.isString(value)) {
        value = Date.parse(value);
      }

      // If is timestamp, convert to Date.
      if(_.isNumber(value)) {
        value = new Date((value + '').length > 10 ? value : value * 1000);
      }

      // If the date couldn't be parsed, do not modify index.
      if(value == 'Invalid Date' || !_.isDate(value)) {
        throw new SetterError('Could not parse date.', value, originalValue, properties);
      }

      // Transformation after typecasting but before validation and filters.
      if(properties.dateTransform) {
        value = properties.dateTransform.call(this, value, originalValue, properties);
      }

      return value;
      break;

    default:
      return value;
      break;
  }
};
Example #15
0
Then(/^the argument should be (.*)$/, function(step, stepArgNumber) {
  _.isNumber(stepArgNumber).should.be.true;
  this.stepArgNumber.should.eql(stepArgNumber);
  step.done();
});