Add user-relation policy condition to SQL query (select or where clause).
517690
private function queryAddUserRelationAccessPolicyCondition($policy_name, $policy, $query, $clause)
	{
		$policy_alias = $clause == 'select' ? ' AS '.$query->quoteIdent('_access_policy_'.$policy_name) : '';
		$user_id = $this->auth->getUserId();
		if ($this->auth->isAllMighty()) {
			$query->$clause('TRUE'.$policy_alias);
		} else if (isset($policy['required_value'])) {
			$query->$clause('('.$policy['sql_select'].') = ?'.$policy_alias, $user_id, $policy['required_value']);
		} else {
			$query->$clause('('.$policy['sql_select'].') IS NOT NULL'.$policy_alias, $user_id);
		}
	}
114108
protected void addAllowedOuCondition(
        CmsSelectQuery select,
        TableAlias users,
        List<CmsOrganizationalUnit> allowedOus) {

        if ((allowedOus != null) && !allowedOus.isEmpty()) {
            CmsCompositeQueryFragment ouCondition = new CmsCompositeQueryFragment();
            ouCondition.setPrefix("(");
            ouCondition.setSuffix(")");
            ouCondition.setSeparator(" OR ");
            for (CmsOrganizationalUnit ou : allowedOus) {
                String ouName = CmsStringUtil.joinPaths("/", ou.getName());
                ouCondition.add(new CmsSimpleQueryFragment(users.column(colOu()) + " = ? ", ouName));
            }
            select.addCondition(ouCondition);
        }
    }
1093066
protected function build_where($rules,$relation=false){
		$sql=array();
		for ($i=0; $i < sizeof($rules); $i++)
			if (is_string($rules[$i]))
				array_push($sql,"(".$rules[$i].")");
			else {
				$filtervalue = $rules[$i]["value"];
				$filteroperation = $rules[$i]["operation"];
				if ($filtervalue!=""){
					if (!$filteroperation)
						array_push($sql,$this->escape_name($rules[$i]["name"])." LIKE '%".$this->escape($filtervalue)."%'");
					else {
						if ($filteroperation != "IN") 
							$filtervalue = "'".$this->escape($filtervalue)."'";

						array_push($sql,$this->escape_name($rules[$i]["name"])." ".$filteroperation." ".$filtervalue);
					}
				}
			}

		if ($relation !== false && $relation !== ""){
			$relsql = $this->escape_name($this->config->relation_id["db_name"])." = '".$this->escape($relation)."'";
			if ($relation == "0")
				$relsql = "( ".$relsql." OR ".$this->escape_name($this->config->relation_id["db_name"])." IS NULL )";

			array_push($sql,$relsql);
		}
		return implode(" AND ",$sql);
	}
1164793
def or_where(self, key, operator, value):
        
        if len(self._queries) > 0:
            self._current_query_index += 1
        self.__store_query({"key": key, "operator": operator, "value": value})
        return self
984110
protected void addSearchFilterCondition(
        CmsSelectQuery select,
        TableAlias users,
        CmsUserSearchParameters searchParams) {

        String searchFilter = searchParams.getSearchFilter();
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(searchFilter)) {
            boolean caseInsensitive = !searchParams.isCaseSensitive();
            if (caseInsensitive) {
                searchFilter = searchFilter.toLowerCase();
            }
            CmsCompositeQueryFragment searchCondition = new CmsCompositeQueryFragment();
            searchCondition.setSeparator(" OR ");
            searchCondition.setPrefix("(");
            searchCondition.setSuffix(")");
            //use coalesce in case any of the name columns are null
            String patternExprTemplate = generateConcat(
                "COALESCE(%1$s, '')",
                "' '",
                "COALESCE(%2$s, '')",
                "' '",
                "COALESCE(%3$s, '')");
            patternExprTemplate = wrapLower(patternExprTemplate, caseInsensitive);

            String patternExpr = String.format(
                patternExprTemplate,
                users.column(colName()),
                users.column(colFirstName()),
                users.column(colLastName()));
            String like = " LIKE ? ESCAPE '!' ";
            String matchExpr = patternExpr + like;
            searchFilter = "%" + CmsEncoder.escapeSqlLikePattern(searchFilter, '!') + '%';
            searchCondition.add(new CmsSimpleQueryFragment(matchExpr, searchFilter));
            for (SearchKey key : searchParams.getSearchKeys()) {
                switch (key) {
                    case email:
                        searchCondition.add(
                            new CmsSimpleQueryFragment(
                                wrapLower(users.column(colEmail()), caseInsensitive) + like,
                                searchFilter));
                        break;
                    case orgUnit:
                        searchCondition.add(new CmsSimpleQueryFragment(
                            wrapLower(users.column(colOu()), caseInsensitive) + like,
                            searchFilter));
                        break;
                    default:
                        break;
                }
            }
            select.addCondition(searchCondition);
        }
    }
1180641
public function where(\Parable\ORM\Query\ConditionSet $set)
    {
        $this->where[] = $set;
        return $this;
    }
902017
def _validate_select_where(self):
        
        #check that there's either a = or IN relationship with a primary key or indexed field
        equal_ops = [self.model._columns.get(w.field) for w in self._where if isinstance(w.operator, EqualsOperator)]
        token_comparison = any([w for w in self._where if isinstance(w.value, Token)])
        if not any([w.primary_key or w.index for w in equal_ops]) and not token_comparison and not self._allow_filtering:
            raise QueryException('Where clauses require either a "=" or "IN" comparison with either a primary key or indexed field')

        if not self._allow_filtering:
            #if the query is not on an indexed field
            if not any([w.index for w in equal_ops]):
                if not any([w.partition_key for w in equal_ops]) and not token_comparison:
                    raise QueryException('Filtering on a clustering key without a partition key is not allowed unless allow_filtering() is called on the querset')
671793
protected function get_filter_sql() {
        global $DB;

        // Search condition.
        $extrafields = get_extra_user_fields($this->get_context());
        list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);

        // Role condition.
        if ($this->rolefilter) {
            // Get context SQL.
            $contextids = $this->context->get_parent_context_ids();
            $contextids[] = $this->context->id;
            list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
            $params += $contextparams;

            // Role check condition.
            $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
                    "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
            $params['roleid'] = $this->rolefilter;
        }

        // Group condition.
        if ($this->groupfilter) {
            if ($this->groupfilter < 0) {
                // Show users who are not in any group.
                $sql .= " AND gm.groupid IS NULL";
            } else {
                $sql .= " AND gm.groupid = :groupid";
                $params['groupid'] = $this->groupfilter;
            }
        }

        // Status condition.
        if ($this->statusfilter === ENROL_USER_ACTIVE) {
            $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
                    AND (ue.timeend = 0 OR ue.timeend > :now2)";
            $now = round(time(), -2); // rounding helps caching in DB
            $params += array('enabled' => ENROL_INSTANCE_ENABLED,
                             'active' => ENROL_USER_ACTIVE,
                             'now1' => $now,
                             'now2' => $now);
        } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
            $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
                    OR (ue.timeend <> 0 AND ue.timeend < :now2))";
            $now = round(time(), -2); // rounding helps caching in DB
            $params += array('disabled' => ENROL_INSTANCE_DISABLED,
                             'inactive' => ENROL_USER_SUSPENDED,
                             'now1' => $now,
                             'now2' => $now);
        }

        return array($sql, $params);
    }
496461
protected static function addRoleInheritCondition(Builder $query, Model $authority, $roles)
    {
        $query->orWhere('level', '<', function ($query) use ($authority, $roles) {
            $query->selectRaw('max(level)')
                  ->from($roles)
                  ->whereExists(static::getAuthorityRoleConstraint($authority));

            Models::scope()->applyToModelQuery($query, $roles);
        });
    }
228482
def allow_user(user):
    """"""
    def processor(action, argument):
        db.session.add(
            ActionUsers.allow(action, argument=argument, user_id=user.id)
        )
    return processor
1280301
@Override
	public SqlBatch by(final BiPredicate<SqlContext, Map<String, Object>> condition) {
		this.condition = condition;
		return this;
	}
369167
public NrqlAlertConditionCache nrqlAlertConditions(long policyId)
    {
        NrqlAlertConditionCache cache = nrqlConditions.get(policyId);
        if(cache == null)
            nrqlConditions.put(policyId, cache = new NrqlAlertConditionCache(policyId));
        return cache;
    }
353579
private void setWhere(Where where) throws SqlParseException {
		if (where != null) {
			BoolQueryBuilder boolQuery = QueryMaker.explan(where,this.select.isQuery);
			request.setQuery(boolQuery);
		}
	}
95746
def create_condition(self, 
		service_id, 
		version_number,
		name,
		_type,
		statement,
		priority="10", 
		comment=None):
		""""""
		body = self._formdata({
			"name": name,
			"type": _type,
			"statement": statement,
			"priority": priority,
			"comment": comment,
		}, FastlyCondition.FIELDS)
		content = self._fetch("/service/%s/version/%d/condition" % (service_id, version_number), method="POST", body=body)
		return FastlyCondition(self, content)
154108
protected function addConditions($query, $conditions)
    {
        foreach ($conditions as $key => $value) {
            $this->addWhere($query, $key, $value);
        }

        return $query;
    }
1132735
def filter(self, table, users, filter_string):
        """"""
        q = filter_string.lower()
        return [user for user in users
                if (q in user.name.lower() or
                    q in (getattr(user, 'email', None) or '').lower())]
713441
def query_as_ldap(query, compiler, connection):
    """"""
    if query.is_empty():
        return

    if query.model._meta.model_name == 'migration' and not hasattr(query.model, 'object_classes'):
        # FIXME(rbarrois): Support migrations
        return

    # FIXME(rbarrois): this could be an extra Where clause
    filterstr = ''.join(['(objectClass=%s)' % cls for cls in
                         query.model.object_classes])

    # FIXME(rbarrois): Remove this code as part of #101
    if (len(query.where.children) == 1
            and not isinstance(query.where.children[0], WhereNode)
            and query.where.children[0].lhs.target.column == 'dn'):

        lookup = query.where.children[0]
        if lookup.lookup_name != 'exact':
            raise LdapDBError("Unsupported dn lookup: %s" % lookup.lookup_name)

        return LdapLookup(
            base=lookup.rhs,
            scope=ldap.SCOPE_BASE,
            filterstr='(&%s)' % filterstr,
        )

    sql, params = compiler.compile(query.where)
    if sql:
        filterstr += '(%s)' % (sql % tuple(escape_ldap_filter(param) for param in params))
    return LdapLookup(
        base=query.model.base_dn,
        scope=query.model.search_scope,
        filterstr='(&%s)' % filterstr,
    )