Given a valid datetime or slace, return the predicate portion
        of the SQL query, a boolean indicating whether multiple items are
        expected from the result, and a dictionary of parameters for the query
327553
def _predicate(self, i):
        
        if isinstance(i, slice):
            if i.step is not None:
                raise TypeError("Slice step not permitted")
            if ( (i.start is not None and not isinstance(i.start, datetime))
                or (i.stop is not None and not isinstance(i.stop, datetime))
            ):
                raise TypeError(
                    "Slice indices must be {} or None".format(datetime)
                )
            if i.start is not None and i.stop is not None:
                if i.start > i.stop:
                    raise ValueError(
                        "Start index is greater than the End index"
                    )
                else:
                    # Substitution of the key coloumn, but the
                    # parameters themselves will be substituted by sqlite3
                    predicate = "WHERE {} BETWEEN :start AND :stop".format(
                        self._keycol
                    )
            elif i.start is not None:
                # i.stop will also be None
                predicate = "WHERE {} >= :start".format(self._keycol)
            elif i.stop is not None:
                # i.start will also be None
                predicate = "WHERE {} <= :stop".format(self._keycol)
            else:
                # both are None, so equivelent to wanting everything
                predicate = ""
            multi = True
            pred = {"start": i.start, "stop": i.stop}
        elif isinstance(i, datetime):
            # Substitution of the key coloumn, but the
            # parameters themselves will be substituted by sqlite3
            predicate = "WHERE {} = :key".format(self._keycol)
            multi = False
            pred = {"key": i}
        else:
            # not a slice or a datetime object
            raise TypeError("List indices must be {}".format(datetime))
        # predicate is the end of the query string.
        # multi is a boolean indicating whether the result should be iterable
        # or not. pred is a dict of the parameters for substitution
        return (predicate, multi, pred)
238842
def get_where_clause_from_dict(dictionary, join_operator='AND'):
        
        CoyoteDb.escape_dictionary(dictionary)
        clause = join_operator.join(
            (' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v)  # IS should be the operator for null values
            for k, v in dictionary.iteritems())
        return clause
603493
def predicates_for_and_conditions(conditions)
      return nil if conditions.empty?

      predicates = conditions.map do |q|
        q = HashWithIndifferentAccess.new(Netzke::Support.permit_hash_params(q))

        attr = q[:attr]
        method, assoc = method_and_assoc(attr)

        arel_table = assoc ? Arel::Table.new(assoc.klass.table_name.to_sym) :
                       @model.arel_table

        value = q['value']
        op = q['operator']

        attr_type = attr_type(attr)

        case attr_type
        when :datetime
          update_predecate_for_datetime(arel_table[method], op, value.to_date)
        when :string, :text
          update_predecate_for_string(arel_table[method], op, value)
        when :boolean
          update_predecate_for_boolean(arel_table[method], op, value)
        when :date
          update_predecate_for_rest(arel_table[method], op, value.to_date)
        when :enum
          # HACKY! monkey patching happens here...
          update_predecate_for_enum(arel_table[method], op, value)
        else
          update_predecate_for_rest(arel_table[method], op, value)
        end
      end

      # join them by AND
      predicates[1..-1].inject(predicates.first) { |r, p| r.and(p)  }
    end
617332
def And(*predicates, **kwargs):
    
    if kwargs:
        predicates += Query(**kwargs),
    return _flatten(_And, *predicates)
704556
def query_filter_date(start, end):
    
    sdate = datetime.datetime.strptime(start, "%Y-%m-%d")
    edate = datetime.datetime.strptime(end, "%Y-%m-%d")
    startdate = "%s/%s/%s" % (sdate.month, sdate.day, sdate.year)
    enddate = "%s/%s/%s" % (edate.month, edate.day, edate.year)
    return {
        'operation': 'betweenDate',
        'options': [
            {'name': 'startDate', 'value': [startdate + ' 0:0:0']},
            {'name': 'endDate', 'value': [enddate + ' 0:0:0']}
        ]
    }
939873
def query(cls, resources, time_range, query, resource_type, sampler):
        """"""
        if not isinstance(resources, (list, tuple)):
            resources = [resources]

        now = time.time()
        start_utc = datetime.utcfromtimestamp(now - time_range)
        end_utc = datetime.utcfromtimestamp(now)
        date_format = '%Y-%m-%d %H:%M:%S'
        start = start_utc.strftime(date_format)
        end = end_utc.strftime(date_format)
        query = {'start': start,
                 'end': end,
                 'query': query,
                 'resource_id': resources,
                 'resource_type': resource_type,
                 'sampler': sampler}
        return cls.call('hosting.metric.query', query)
1112784
function containsRelationships(query) {
  let contains = false;
  if (query.predicate instanceof SimplePredicate || query.predicate instanceof StringPredicate || query.predicate instanceof DatePredicate) {
    contains = Information.parseAttributePath(query.predicate.attributePath).length > 1;
  }

  if (query.predicate instanceof DetailPredicate) {
    return true;
  }

  if (query.predicate instanceof ComplexPredicate) {
    query.predicate.predicates.forEach((predicate) => {
      if (containsRelationships({ predicate })) {
        contains = true;
      }
    });
  }

  if (query.order) {
    for (let i = 0; i < query.order.length; i++) {
      let attributePath = query.order.attribute(i).name;
      if (Information.parseAttributePath(attributePath).length > 1) {
        contains = true;
      }
    }
  }

  return contains;
}
362932
def preprocess_query(query):
    
    # 1. remove aliases
    # FROM `dimension_wikis` `dw`
    # INNER JOIN `fact_wam_scores` `fwN`
    query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE)

    # 2. `database`.`table` notation -> database.table
    query = re.sub(r'`([^`]+)`\.`([^`]+)`', r'\1.\2', query)

    # 2. database.table notation -> table
    # query = re.sub(r'([a-z_0-9]+)\.([a-z_0-9]+)', r'\2', query, flags=re.IGNORECASE)

    return query
468020
def get_pks_from_query(self, query):
        """"""
        where = query.where
        sql = None
        if where.connector == 'AND' and not where.negated and len(where.children) == 1:
            # simple cases are optimized, especially because a suboptimal
            # nested query based on the same table is not allowed by SF
            child = where.children[0]
            if (child.lookup_name in ('exact', 'in') and child.lhs.target.column == 'Id'
                    and not child.bilateral_transforms and child.lhs.target.model is self.query.model):
                pks = child.rhs
                if child.lookup_name == 'exact':
                    assert isinstance(pks, text_type)
                    return [pks]
                # lookup_name 'in'
                assert not child.bilateral_transforms
                if isinstance(pks, (tuple, list)):
                    return pks
                if DJANGO_111_PLUS:
                    assert isinstance(pks, Query) and type(pks).__name__ == 'SalesforceQuery'
                    # # alternative solution:
                    # return list(salesforce.backend.query.SalesforceQuerySet(pk.model, query=pk, using=pk._db))

                    sql, params = pks.get_compiler('salesforce').as_sql()
                else:
                    assert isinstance(pks, salesforce.backend.query.SalesforceQuerySet)
                    return [x.pk for x in pks]
        if not sql:
            # a subquery is necessary in this case
            where_sql, params = where.as_sql(query.get_compiler('salesforce'), self.db.connection)
            sql = "SELECT Id FROM {} WHERE {}".format(query.model._meta.db_table, where_sql)
        with self.db.cursor() as cur:
            cur.execute(sql, params)
            assert len(cur.description) == 1 and cur.description[0][0] == 'Id'
            return [x[0] for x in cur]
385559
def match_query(query)
        query ||= {}
        
        if match_event(query) && (state_requirement = match_states(query))
          state_requirement.merge(:on => event_requirement)
        end
      end
968461
function pg_query(query, params) {
	return function(db) {
		var start_time = new Date();
		return do_query(db, query, params).then(function() {

			var end_time = new Date();

			db._record_sample({
				'event': 'query',
				'start': start_time,
				'end': end_time,
				'query': query,
				'params': params
			});

			return db;
		});
	};
}
641661
def querySQL(self, sql, args=()):
        
        if self.debug:
            result = timeinto(self.queryTimes, self._queryandfetch, sql, args)
        else:
            result = self._queryandfetch(sql, args)
        return result
1148334
def _filter_by_statement(self, statement):
        """"""
        self.__class__._check_conditional_statement(statement, 1)
        _filt_values, _filt_datetimes = [], []
        for i, a in enumerate(self._values):
            if eval(statement, {'a': a}):
                _filt_values.append(a)
                _filt_datetimes.append(self.datetimes[i])
        return _filt_values, _filt_datetimes
270475
@VisibleForTesting
    public static boolean checkInBloomFilter(BloomFilter bloomFilter, Object predicateValue, Type sqlType)
    {
        if (sqlType == TINYINT || sqlType == SMALLINT || sqlType == INTEGER || sqlType == BIGINT) {
            return bloomFilter.testLong(((Number) predicateValue).longValue());
        }

        if (sqlType == DOUBLE) {
            return bloomFilter.testDouble((Double) predicateValue);
        }

        if (sqlType instanceof VarcharType || sqlType instanceof VarbinaryType) {
            return bloomFilter.test(((Slice) predicateValue).getBytes());
        }

        // todo support DECIMAL, FLOAT, DATE, TIMESTAMP, and CHAR
        return true;
    }
447699
def __build_query(self, routine, parameters):
        """"""

        parameter_names = []
        replacements = {}
        for i, value in enumerate(parameters):
            name = 'arg' + str(i)

            parameter_names.append(name)
            replacements[name] = value

        parameter_pieces = []
        for i, name in enumerate(parameter_names):
            if i > 0:
                parameter_pieces.append(', ')

            # Embed encoded blobs directly.
            if issubclass(replacements[name].__class__, _BlobArgumentWrapper) is True:
                parameter_pieces.append(replacements[name].encoded)
                del replacements[name]
            else:
                parameter_pieces.append(':' + name)

        query = "CALL " + routine + "(" + ''.join(parameter_pieces) + ")"

        return (query, replacements)
854
def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
    """"""
    # Python datetime.datetime is a subclass of datetime.date,
    # but in this case, the two are not interchangeable.
    # Rather than using isinstance, we will therefore check for exact type equality.
    value_type = type(value)
    if not any(value_type == x for x in expected_python_types):
        raise GraphQLInvalidArgumentError(u'Expected value to be exactly one of '
                                          u'python types {}, but was {}: '
                                          u'{}'.format(expected_python_types, value_type, value))

    # The serialize() method of GraphQLDate and GraphQLDateTime produces the correct
    # ISO-8601 format that MATCH expects. We then simply represent it as a regular string.
    try:
        serialized_value = graphql_type.serialize(value)
    except ValueError as e:
        raise GraphQLInvalidArgumentError(e)

    return _safe_match_string(serialized_value)
526493
def ensure_datetime(dobj, time_part=None):
    
    if isinstance(dobj, dt.datetime):
        return dobj
    return dt.datetime.combine(dobj, time_part or dt.time())