Generate WHERE clause from user-supplied string or array

@param  string|array $where  OPTIONAL An SQL WHERE clause.
@return Kwf_Db_Table_Select
338856
protected function _where(Kwf_Db_Table_Select $select, $where)
    {
        $where = (array) $where;

        foreach ($where as $key => $val) {
            // is $key an int?
            if (is_int($key)) {
                // $val is the full condition
                $select->where($val);
            } else {
                // $key is the condition with placeholder,
                // and $val is quoted into the condition
                $select->where($key, $val);
            }
        }

        return $select;
    }
692643
protected function parseWhere($where)
    {
        $result = [];
        foreach($where as $item)
        {
            $result[] = $item->getLogicalOperator();
            $result[] = $item->toStringWithoutLogic();
            $this->params = array_merge($this->params, $item->getBinds());
        }
        array_shift($result);
        $result = implode(' ', $result);
        if('' !== $result)
        {
            $result = ' where ' . $result;
        }
        return $result;
    }
816555
public function buildQuery(string $table, array $where): SqlParams
    {
        $whereClause = $this->buildWhereClause($where);
        $sql = "DELETE FROM {$table}" . $whereClause->getSql();
        return new SqlParams($sql, $whereClause->getParams());
    }
1016789
public function buildSelectString($whereCondition = null)
    {
        $database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        $get = $this->getSelectFields();
        $query = "select $get from " . $this->getViewName() . ' where 1 ';

        if ($whereCondition) {
            reset($whereCondition);
            foreach ($whereCondition as $name => $value) {
                $query .= ' and ' . $name . ' = ' . $database->quote($value);
            }
        }

        return $query;
    }
80577
protected function getTableFieldInformationWhere(Where $where)
    {
        $sql = <<<SQL
select
    att.attname      as "name",
    case
        when name.nspname = 'pg_catalog' then typ.typname
        else format('%s.%s', name.nspname, typ.typname)
    end as "type",
    def.adsrc        as "default",
    att.attnotnull   as "is_notnull",
    dsc.description  as "comment",
    att.attnum       as "position",
    att.attnum = any(ind.indkey) as "is_primary"
from
  pg_catalog.pg_attribute att
    join pg_catalog.pg_type  typ  on att.atttypid = typ.oid
    join pg_catalog.pg_class cla  on att.attrelid = cla.oid
    join pg_catalog.pg_namespace clns on cla.relnamespace = clns.oid
    left join pg_catalog.pg_description dsc on cla.oid = dsc.objoid and att.attnum = dsc.objsubid
    left join pg_catalog.pg_attrdef def     on att.attrelid = def.adrelid and att.attnum = def.adnum
    left join pg_catalog.pg_index ind       on cla.oid = ind.indrelid and ind.indisprimary
    left join pg_catalog.pg_namespace name  on typ.typnamespace = name.oid
where
{condition}
order by
    att.attnum
SQL;

        $where = $where
            ->andWhere('att.attnum > 0')
            ->andWhere('not att.attisdropped')
            ;

        return $this->executeSql($sql, $where);
    }
29326
public function fetchPaginator($where = null)
    {
        if ($where instanceof DbSelect) {
            $adapter = $where;
        } else {
            $select = $this->sql->select();

            if ($where instanceof \Closure) {
                $where($select);
            } elseif ($where !== null) {
                $select->where($where);
            }

            if (count($select->getRawState(Select::GROUP))) {
                $adapter = new DbSelect($select, $this->getAdapter(), $this->getResultSetPrototype());
            } else {
                $count   = null;
                $adapter = new Callback(
                    function ($offset, $itemCountPerPage) use ($select) {
                        $select->offset($offset);
                        $select->limit($itemCountPerPage);

                        $statement = $this->sql->prepareStatementForSqlObject($select);
                        $result    = $statement->execute();

                        $resultSet = $this->getResultSetPrototype() ? clone $this->getResultSetPrototype() : new ResultSet();
                        $resultSet->initialize($result);
                        return $resultSet;
                    }, function () use ($select, &$count) {
                        if ($count === null) {
                            $select = clone $select;
                            $select->columns(array('Gzfextra_Db_Count' => new Expression('count(1)')));
                            $result = $this->sql->prepareStatementForSqlObject($select)->execute()->current();
                            $count  = $result['Gzfextra_Db_Count'];
                        }
                        return $count;
                    }
                );
            }
        }

        return new Paginator($adapter);
    }
389927
private static function parseSql($table,$where,$option=[])
    {
        $field='';
        if(isset($option['field']) && is_array($option['field'])){
            $ends=count($option['field'])-1;
            foreach ($field as $key => $value) {
                $field.='`'.$value.'`';
                if($key!=$ends){
                    $field.=',';
                }
            }
        }else{
            $field='*';
        }
        $limit='';
        if(isset($option['limit']) && is_array($option['limit'])){
            $limit=' LIMIT '.$option['limit'][0].','.$option['limit'][1];
        }
        $order='';
        if(isset($option['order']) && is_array($option['order'])){
            $c=count($option['order'])-1;
            $i=0;
            $order='ORDER BY ';
            foreach ($option['order'] as $key=>$value) {
                $i++;
                $order.="`{$key}` {$value}";
                if($c==$i){
                    $order.=',';
                }
            }

        }
        $bind=[];
        if(empty($where)){
            $where='';
        }else{
            $w=new Where($where);
            $where=' WHERE '.$w->parseWhere();
            $bind=array_merge($bind,$w->parseBind());
        }

        $sql=sprintf('SELECT '.$field.' FROM `:%s` %s %s %s',$table,$where,$limit,$order);
        return self::query($sql,$bind);
    }
1161776
public function find(array $where = [], array $field = [])
    {
        return $this
            ->createQuery(
                $this->getQueryBuilder()
                    ->select(array() === $field ? $this->getAlias() : $field)
                    ->from($this->getTable())
                    ->where($where)
            )
            ->execute()
            ->getOne()
            ;
    }
9029
public function setWhere(array $where)
    {
        // When the statement is empty set the
        // where property to null to prevent
        // empty statement errors.
        if (empty($where)) {
            // delete the current where statement
            $this->where = null;

            // Skip further execution
            return $this;
        }

        // Ensure the base $or clause
        if (! isset($where['$or'])) {
            // wrap the statement in an $or clause
            $where = ['$or' => [$where]];
        }

        // Fetch the last clause in the $or array
        // to allow further chaining it's required
        // to be wrapped in an @and statement.
        $lastClause = array_pop($where['$or']);

        if (! isset($lastClause['$and'])) {
            // Wrap in an @and statement
            $lastClause = ['$and' => [$lastClause]];
        }

        // Re-append the $and clause
        $where['$or'][] = $lastClause;

        // Replace the base where statement
        $this->where = $where;

        return $this;
    }
394090
public static function where($where=null) {

        if ( !$where || empty($where) ) return array();

        /**
         * 基于 key => value 数组语法的查询条件解析,这里借鉴的是mongodb的查询语法，以便兼容mongodb
         * array('name' => 'zhangsan', '|age' => '>12')
         * 转换后：array('name' => 'zhangsan', '$or' => array('age' => array('$lt' => 24, '$gt' => 30)))
         */
        $condi = array();
        foreach ( $where as $key => $value ) {

            if ( $key == '$or' ) { //组合or查询
                $condi['$or'] = array($value);
                continue;
            }
            if ( $key == '$and' ) {
                $condi['$and'] = array($value);
                continue;
            }
            //这里判断是AND,OR
            if ( $key[0] == '|' ) {
                $key = substr($key, 1);
                $condi['$or'][] = array($key => $value);
            } else {
                $condi[$key] = self::getFormatValue($value);
            }

            if ( is_array($value) ) {

                foreach ( $value as $key1 => $value1 ) {
                    /**
                     * 3. IN 查询,支持2种形式
                     * array('id' => array('$in' => array(1,2,3)))
                     * array('id' => array('$in' => '1,2,3'))
                     */
                    if ( $key1 == '$in' || $key1 == '$nin' ) {
                        if ( is_string($value1) ) {
                            $value[$key1] = explode(',', $value1);
                        }
                        $condi[$key] = $value;
                        continue;
                    }

                    //4. like查询 array('title' => array('$like' => 'xabc'))
                    if ( $key1 == '$like' ) {
                        $condi[$key] = array('$regex' => $value[$key1]);
                        continue;
                    }

                } //end foreach

            } //end fi
        } //end foreach

        self::replaceConditionOperation($condi, $arr);

        return $arr;
    }
339932
public function where($where,$parse=null){
        if(!is_null($parse) && is_string($where)) {
            if(!is_array($parse)) {
                $parse = func_get_args();
                array_shift($parse);
            }
            $parse = array_map(array($this->db,'escapeString'),$parse);
            $where =   vsprintf($where,$parse);
        }elseif(is_object($where)){
            $where  =   get_object_vars($where);
        }
        if(is_string($where) && '' != $where){
            $map    =   array();
            $map['_string']   =   $where;
            $where  =   $map;
        }        
        if(isset($this->options['where'])){
            $this->options['where'] =   array_merge($this->options['where'],$where);
        }else{
            $this->options['where'] =   $where;
        }
        
        return $this;
    }
27695
public static function select($where = null)
    {
        $query = static::parseWhere(static::query(), $where);

        // 查询前
        Event::trigger(static::__getRealClassName() . ':' . ModelEvents::BEFORE_SELECT, [
            'query' => $query,
        ], null, \Imi\Model\Event\Param\BeforeSelectEventParam::class);

        $result = $query->select()->getArray();

        // 查询后
        Event::trigger(static::__getRealClassName() . ':' . ModelEvents::AFTER_SELECT, [
            'result' => &$result,
        ], null, \Imi\Model\Event\Param\AfterSelectEventParam::class);

        return $result;
    }
151385
private static function smartSelect($table, $fields = null, $where = null) {
        $additional = '';
        if(is_array($table)) {
            $additional = DbCallFunctions::calls($table);
            $table = $table['from'];
        }
        $table = self::sanitizeKey($table);
        $fieldsString = self::handleSelectandi($fields);
        $whereString = !empty($where) ? self::handleConditions($where) : '';
        $whereString .= $additional;
        $sql = 'SELECT ' . $fieldsString . ' FROM ' . self::$_ops->addBackticks($table) . ' ' . $whereString;
        return self::handleResults($sql);
    }
357566
public function select(string $columns, array $where = [], int $fetch_mode = PDO::FETCH_ASSOC) : self {
    $this->query_builder->resetProperties();
    $this->query_builder->setMode('select');
    $this->query_builder->setColumns($columns);

    if (!empty($where)) {
      $this->query_builder->setWhere($where);
      $where = $this->formatWhereData($where);
    }

    try {
      $stmt = parent::prepare($this->query_builder->getQuery());
      $stmt->execute($where);
      $this->results = $stmt->fetchAll($fetch_mode);
    } catch (PDOException $e) {
      $this->pdo_exception = $e;
      $this->query_failed = true;
    }

    return $this;
  }
292258
private function createWhereExpression(array $where = [])
    {
        $criteria = [];
        foreach ($where as $index => $value) {
            if (is_int($index)) {
                $criteria[] = $value;
            } else {
                $criteria[] = $this->quote()->into($index, $value);
            }
        }
        return implode(' AND ', $criteria);
    }
701789
public function GetWhereCache($Where) {
      $Result = array();
      
      foreach (self::Categories() as $Index => $Row) {
         $Match = true;
         foreach ($Where as $Column => $Value) {
            $RowValue = GetValue($Column, $Row, NULL);
            
            if ($RowValue != $Value && !(is_array($Value) && in_array($RowValue, $Value))) {
               $Match = false;
               break;
            }
         }
         if ($Match)
            $Result[$Index] = $Row;
      }
      
      return $Result;
   }
497362
protected function buildColRelVal( $where )
    {
        $rel = $where[ 'rel' ];
        $col = $where[ 'col' ];
        $val = $where[ 'val' ];
        if ( $rel == 'EQ' ) {
            // EQ: equal to another column (i.e. val is an identifier.)
            $val = $this->quote( $val );
            $rel = '=';
        } else {
            $val = $this->formWhereVal( $val );
        }
        // normal case. compose where like col = val
        $col = $this->formWhereCol( $col );

        $where = trim( "{$col} {$rel} {$val}" ) . ' ';
        return $where;
    }