Return SELECT statement that will be used as a filter.

    :param filter_definition: definition of a filter that should be used for SELECT construction
    :return:
192239
def _construct_select_query(**filter_definition):
    
    table_name = filter_definition.pop('table')
    distinct = filter_definition.pop('distinct', False)
    select_count = filter_definition.pop('count', False)

    if distinct and select_count:
        raise UnsupportedDefinitionError('SELECT (DISTINCT ...) is not supported')

    if select_count and 'select' in filter_definition:
        raise UnsupportedDefinitionError('SELECT COUNT(columns) is not supported')

    if 'joins' in filter_definition:
        join_definitions = filter_definition.pop('joins')

        if not isinstance(join_definitions, (tuple, list)):
            join_definitions = (join_definitions,)

        filter_definition['joins'] = []
        for join_def in join_definitions:
            filter_definition['joins'].append(_expand_join(join_def))

    if 'where' in filter_definition:
        for key, value in filter_definition['where'].items():
            if is_filter_query(value):
                # We can do it recursively here
                sub_query = value.pop(DEFAULT_FILTER_KEY)
                if value:
                    raise ParsingInputError("Unknown keys for sub-query provided: %s" % value)
                filter_definition['where'][key] = mosql_raw('( {} )'.format(_construct_select_query(**sub_query)))
            elif isinstance(value, str) and value.startswith('$') and QUERY_REFERENCE.fullmatch(value[1:]):
                # Make sure we construct correct query with escaped table name and escaped column for sub-queries
                filter_definition['where'][key] = mosql_raw('"{}"'.format('"."'.join(value[1:].split('.'))))

    raw_select = select(table_name, **filter_definition)

    if distinct:
        # Note that we want to limit replace to the current SELECT, not affect nested ones
        raw_select = raw_select.replace('SELECT', 'SELECT DISTINCT', 1)
    if select_count:
        # Note that we want to limit replace to the current SELECT, not affect nested ones
        raw_select = raw_select.replace('SELECT *', 'SELECT COUNT(*)', 1)

    return raw_select
535320
def __filter_query(self) -> str:
        
        filter_query = 'WHERE %s'
        bind_values = {}
        if not self.__filters:
            return None
        for filter in self.__filters:
            bind = {
                'name': Security.random_string(5),
                'value': filter['value']}
            filter_str = '%s %s :%s' % \
                (filter['column'], filter['operator'], bind['name'])
            bind_values[bind['name']] = bind['value']
            filter_query = filter_query % (filter_str + ' AND %s')
        return {
            'query': filter_query.replace(' AND %s', ''),
            'binds': bind_values}
1294969
def filter(self, criteria: Q, offset: int = 0, limit: int = 10,
               order_by: list = ()) -> ResultSet:
        
1082123
def get_filters(cls, raw_filters, num_cols, columns_dict):  # noqa
        """"""
        filters = None
        for flt in raw_filters:
            col = flt.get('col')
            op = flt.get('op')
            eq = flt.get('val')
            if (
                    not col or
                    not op or
                    (eq is None and op not in ('IS NULL', 'IS NOT NULL'))):
                continue

            # Check if this dimension uses an extraction function
            # If so, create the appropriate pydruid extraction object
            column_def = columns_dict.get(col)
            dim_spec = column_def.dimension_spec if column_def else None
            extraction_fn = None
            if dim_spec and 'extractionFn' in dim_spec:
                (col, extraction_fn) = DruidDatasource._create_extraction_fn(dim_spec)

            cond = None
            is_numeric_col = col in num_cols
            is_list_target = op in ('in', 'not in')
            eq = cls.filter_values_handler(
                eq, is_list_target=is_list_target,
                target_column_is_numeric=is_numeric_col)

            # For these two ops, could have used Dimension,
            # but it doesn't support extraction functions
            if op == '==':
                cond = Filter(dimension=col, value=eq, extraction_function=extraction_fn)
            elif op == '!=':
                cond = ~Filter(dimension=col, value=eq, extraction_function=extraction_fn)
            elif op in ('in', 'not in'):
                fields = []
                # ignore the filter if it has no value
                if not len(eq):
                    continue
                # if it uses an extraction fn, use the "in" operator
                # as Dimension isn't supported
                elif extraction_fn is not None:
                    cond = Filter(
                        dimension=col,
                        values=eq,
                        type='in',
                        extraction_function=extraction_fn,
                    )
                elif len(eq) == 1:
                    cond = Dimension(col) == eq[0]
                else:
                    for s in eq:
                        fields.append(Dimension(col) == s)
                    cond = Filter(type='or', fields=fields)
                if op == 'not in':
                    cond = ~cond
            elif op == 'regex':
                cond = Filter(
                    extraction_function=extraction_fn,
                    type='regex',
                    pattern=eq,
                    dimension=col,
                )

            # For the ops below, could have used pydruid's Bound,
            # but it doesn't support extraction functions
            elif op == '>=':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    dimension=col,
                    lowerStrict=False,
                    upperStrict=False,
                    lower=eq,
                    upper=None,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '<=':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    dimension=col,
                    lowerStrict=False,
                    upperStrict=False,
                    lower=None,
                    upper=eq,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '>':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    lowerStrict=True,
                    upperStrict=False,
                    dimension=col,
                    lower=eq,
                    upper=None,
                    alphaNumeric=is_numeric_col,
                )
            elif op == '<':
                cond = Filter(
                    type='bound',
                    extraction_function=extraction_fn,
                    upperStrict=True,
                    lowerStrict=False,
                    dimension=col,
                    lower=None,
                    upper=eq,
                    alphaNumeric=is_numeric_col,
                )
            elif op == 'IS NULL':
                cond = Dimension(col) == None  # NOQA
            elif op == 'IS NOT NULL':
                cond = Dimension(col) != None  # NOQA

            if filters:
                filters = Filter(type='and', fields=[
                    cond,
                    filters,
                ])
            else:
                filters = cond

        return filters
1202407
def filter(table, predicates):
    
    resolved_predicates = _resolve_predicates(table, predicates)
    return _L.apply_filter(table, resolved_predicates)
244025
def filter(self, field_name, field_value):
        
        self.filters.append((field_name, field_value))
        return self
586998
def get_value_filter(self, filter_value):
        '''
        
        '''
        self.validate_parameter(filter_value)
        f, t = self._ranges[filter_value]
        limits = {}
        # lt and gte to ensure non-overlapping ranges
        if f is not None:
            limits['gte'] = f
        if t is not None:
            limits['lt'] = t

        return Q('range', **{
            self._params['field']: limits
        })
1000532
def dfilter(fn, record):
    
    return dict([(k, v) for k, v in record.items() if fn(v)])
546428
def _select_query(self):
        
        if self._where:
            self._validate_select_where()
        return SelectStatement(
            self.column_family_name,
            fields=self._select_fields(),
            where=self._where,
            order_by=self._order,
            limit=self._limit,
            allow_filtering=self._allow_filtering
        )
124430
def _apply_filter(self, filters, candidates):
        
        if filters:
            filter_input = candidates
            for fetch_vector_filter in filters:
                filter_input = fetch_vector_filter.filter_vectors(filter_input)

            return filter_input
        else:
            return candidates
1162384
def filter(self, value, table=None):
        '''
        
        '''
        if table is not None:
            filterable = self.filterable_func(value, table)
        else:
            filterable = self.filterable_func(value)
        return filterable
666841
def filter_module(module, filter_type):
        
        filter_type = ModuleUtils.is_function if filter_type == "function" else ModuleUtils.is_variable
        module_functions_dict = dict(filter(filter_type, vars(module).items()))
        return module_functions_dict
35415
def build_filter(self, filter):
        
        try:
            self.filter = Filter.from_string(filter, self.limit)
        except ValueError:
            raise

        return self
1369392
def _get_filter(self, features):
        

        # This chops the features up into smaller lists so the api can handle them
        for ip_batch in (features['ips'][pos:pos + self.ip_query_batch_size]
                         for pos in six.moves.range(0, len(features['ips']), self.ip_query_batch_size)):
            # Query for each chunk and add it to the filter list
            query = {'ips': ip_batch, 'ports': features['ports']}
            self.filter['ips'] += self._send_features(query)['ips']
274716
def where(self, relation, filter_fn):
        '''  '''
        assert type(relation).__name__ in {'str','unicode'}, 'where needs the first arg to be a string'
        assert callable(filter_fn), 'filter_fn needs to be callable'
        return VList(i for i in self if relation in i._relations() and any(filter_fn(_()) for _ in i[relation]))
608441
def get_joined_filters(self, filters):
        
        retfilters = Filters(self.filter_converter, self.datamodel)
        retfilters.filters = self.filters + filters.filters
        retfilters.values = self.values + filters.values
        return retfilters
1249031
def _build_filters(_filters):
    
    root = utils.NestedDict({})
    for _filter in _filters:
        operation = None
        for operation, token in SPLIT_TOKENS:
            # split "some.key=value" into ["some.key", "value"]
            top_parts = _filter.split(token, 1)
            if len(top_parts) == 2:
                break
        else:
            raise exceptions.CLIAbort('Failed to find valid operation for: %s'
                                      % _filter)

        key, value = top_parts
        current = root
        # split "some.key" into ["some", "key"]
        parts = [part.strip() for part in key.split('.')]

        # Actually drill down and add the filter
        for part in parts[:-1]:
            current = current[part]

        if operation == 'eq':
            current[parts[-1]] = utils.query_filter(value.strip())
        elif operation == 'in':
            current[parts[-1]] = {
                'operation': 'in',
                'options': [{
                    'name': 'data',
                    'value': [p.strip() for p in value.split(',')],
                }],
            }

    return root.to_dict()