/*
build select statement (fieldlist must be already single quote safe)
@param table, $iFldList, $where
@return string
962646
public static function qbSelect($tname, $options=array()) {

        if (empty($tname)) return;
        
        $one = self::getSUDIOptions("select", $tname, $options);        
        
        (!empty($one['where']))
            ? $where = " WHERE " . $one['where']
            : $where = "";
            
        (empty($one['fl'])) 
            ? $iFldList = "*"
            : $iFldList = $one['fl']
        ;
        
        return "SELECT " . $iFldList
            . " FROM ". $tname 
            . $where . ";"
        ;
    }
1253287
public function sqlStatement(DriverInterface $driver, bool $includeTable = true): string
    {
        $statement = [$this->type == self::UNIQUE ? 'UNIQUE INDEX' : 'INDEX'];

        $statement[] = $driver->identifier($this->name);

        if ($includeTable) {
            $statement[] = "ON {$driver->identifier($this->table)}";
        }

        //Wrapping column names
        $columns = implode(', ', array_map([$driver, 'identifier'], $this->columns));

        $statement[] = "({$columns})";

        return implode(' ', $statement);
    }
704974
private function addConditionsToSqlWhithWhereIn(): string
    {
        if (count($this->wheresIn) === 0) {
            throw new OrmException('Argument 2 passed to "whereIn()" can not be an empty array.');
        }
        
        $paramsWhereIn = " ( ";

        foreach ($this->wheresIn as $value) {                
            $paramsWhereIn .= " ?, ";

            $this->wheresBindValue[] = $value;
        }

        $this->wheresIn = [];

        return rtrim($paramsWhereIn, ', ')." ) ";
    }
685996
public function select(
        $table,
        $conditions = null,
        $fields = null,
        $order = null,
        $limit = null,
        $offset = null
    )
    {
        if (is_null($fields)) {
            $fields = "*";
        }

        $queryString = "SELECT {$fields} FROM {$table} ";

        if (!is_null($conditions)) {
            $queryString .= "WHERE {$conditions} ";
        }

        if (!is_null($order)) {
            $queryString .= "ORDER BY {$order} ";
        }

        if (!is_null($limit)) {
            $queryString .= "LIMIT {$limit} ";
        }

        if (!is_null($offset) && !is_null($limit)) {
            $queryString .= "OFFSET {$offset} ";
        }


        $queryString .= ";";

        $this->query($queryString);

        return $this->countRows();
    }
1159359
function equal($field, $_where)
    {
        if ($_where instanceof SelectDB)
        {
            $where = $field.'=('.$_where->getsql().')';
        }
        else
        {
            $where = "`$field`='$_where'";
        }
        $this->where($where);
    }
994496
private function buildSelectWhatPart(ISelectBuilder $query)
    {
        $columns = $query->getSelectColumns();
        if (!count($columns)) {
            return '*';
        }

        $result = [];
        foreach ($columns as $column) {
            if (is_array($column)) {
                list($name, $alias) = $column;
                $name = $this->protectExpressionValue($name);
                $result[] = $name . ($alias ? ' AS ' . $this->quoteIdentifier($alias) : '');
            }
        }

        return implode(", ", $result);
    }
244711
public static String buildSqlSELECT(String tableName, String[][] columns, String[] whereColumns,
            Object[] whereValues) {
        final String SQL_TEMPLATE_WHERE = "SELECT {1} FROM {0} WHERE {2}";
        final String SQL_TEMPLATE = "SELECT {1} FROM {0}";

        final List<String> WHERE_CLAUSE = new ArrayList<String>();
        if (whereColumns != null && whereValues != null) {
            if (whereColumns.length != whereValues.length) {
                throw new IllegalArgumentException(
                        "Number of whereColumns must be equal to number of whereValues.");
            }
            for (int i = 0; i < whereColumns.length; i++) {
                if (whereValues[i] instanceof ParamExpression) {
                    WHERE_CLAUSE.add("(" + whereColumns[i] + "="
                            + ((ParamExpression) whereValues[i]).getExpression() + ")");
                } else {
                    WHERE_CLAUSE.add("(" + whereColumns[i] + "=?)");
                }
            }
        }

        final List<String> SELECT_COLUMNS = new ArrayList<String>();
        for (String[] colDef : columns) {
            if (colDef.length > 1) {
                SELECT_COLUMNS.add(colDef[0] + " AS " + colDef[1]);
            } else {
                SELECT_COLUMNS.add(colDef[0]);
            }
        }

        String SQL;
        if (WHERE_CLAUSE.size() > 0) {
            SQL = MessageFormat.format(SQL_TEMPLATE_WHERE, tableName,
                    StringUtils.join(SELECT_COLUMNS, ", "),
                    StringUtils.join(WHERE_CLAUSE, " AND "));
        } else {
            SQL = MessageFormat.format(SQL_TEMPLATE, tableName,
                    StringUtils.join(SELECT_COLUMNS, ", "));
        }

        return SQL;
    }
113249
protected function where_clause_list($field, array $values) {
        if (empty($values)) {
            return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
        }

        // Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.

        $params = array();
        $select = "";
        $values = (array)$values;
        foreach ($values as $value) {
            if (is_bool($value)) {
                $value = (int)$value;
            }
            if (is_null($value)) {
                $select = "$field IS NULL";
            } else {
                $params[] = $value;
            }
        }
        if ($params) {
            if ($select !== "") {
                $select = "$select OR ";
            }
            $count = count($params);
            if ($count == 1) {
                $select = $select."$field = ?";
            } else {
                $qs = str_repeat(',?', $count);
                $qs = ltrim($qs, ',');
                $select = $select."$field IN ($qs)";
            }
        }
        return array($select, $params);
    }
408590
public function sql(string $fields = null, string $where = null, string $orderBy = null, string $limit = null): string
    {
        $this->statement->select($fields, $where, $orderBy, $limit);

        // 语句真正被创建
        $this->statement->create();

        // 返回相应的SQL语句
        return $this->statement->getSql();
    }
509309
function store($table, $where, $fields, $append=false)
	{
		if(!$append)
			$n = $this->get("SELECT COUNT(*) FROM `".addslashes($table)."` WHERE $where");

		if(!$append && $n>0)
			$res = $this->query("UPDATE `".addslashes($table)."` ".$this->make_string_set($fields)." WHERE $where");
		else
			$res = $this->query("REPLACE INTO `".addslashes($table)."` ".$this->make_string_values($fields));

		if($res === false)
			throw new Exception("Invalid query: " . mysql_error($this->dbh) ." ");
	}
428102
protected function buildWhere(): string
    {
        if ($this->query->getWhere() === null) {
            return '';
        }

        $where = $this->query->getWhere();
        if (count($where) !== 1) {
            throw new \UnexpectedValueException('Something went wrong: internal query property should always contain only one root element or bu null');
        }

        if (isset($where[LogicOp:: AND])) {
            $logicOp = LogicOp:: AND;
            $clauses = $where[LogicOp:: AND];
        } else {
            if (isset($where[LogicOp:: OR])) {
                $logicOp = LogicOp:: OR;
                $clauses = $where[LogicOp:: OR];
            } else {
                return false;
            }
        }

        return ' where ' . $this->buildClauses($logicOp, $clauses);
    }
241384
protected function _whereExpr($where)
    {
        if (empty($where)) {
            return $where;
        }
        if (!is_array($where)) {
            $where = array($where);
        }
        foreach ($where as $cond => &$term) {
            // is $cond an int? (i.e. Not a condition)
            if (is_int($cond)) {
                // $term is the full condition
                if ($term instanceof Zend_Db_Expr) {
                    $term = $term->__toString();
                }
            } else {
                // $cond is the condition with placeholder,
                // and $term is quoted into the condition
                $term = $this->quoteInto($cond, $term);
            }
            $term = '(' . $term . ')';
        }

        $where = implode(' AND ', $where);
        return $where;
    }
462309
public function getResult($wheres = [], $selectField = '*', $options = NULL)
    {
        try {
            if (is_array($wheres) && count($wheres) > 0) {
                foreach ($wheres as $field => $value) {
                    if (is_array($value)) {
                        $this->db->where($field, $value, self::OPERATOR_IS_IN);
                    } else {
                        $this->db->where($field, $value, self::OPERATOR_EQUAL_TO);
                    }
                }
            } else {
                $this->db->where($this->primaryKey, $wheres, self::OPERATOR_EQUAL_TO);
            }
            if (isset($options['orderBy']) && is_array($options['orderBy'])) {
                foreach ($options['orderBy'] as $column => $direction) {
                    $this->db->orderBy($column, $direction);
                }
            }
            $result = $this->db->get($this->table, NULL, $selectField);
            $this->debug->debug(__FUNCTION__, 'Format is get all Result => ' . json_encode($result));

            return $result;
        }
        catch (\Exception $e) {
            $this->debug->error(__FUNCTION__, $e->getFile() . ' - Line: ' . $e->getLine() . ' - Message: ' . $e->getMessage());

            return NULL;
        }
    }
328774
function selectByIdWhereSql () {
    // get id column
    var idColumn = this.model.columnName('id')
    // every where statement will begin with the alias and column name
    var columnSql = `${this.alias}.${this.quoteName(idColumn)}`
    // sql for where query
    var sql
    // if ids are array build in query
    if (Array.isArray(this.args.where.id)) {
        var i = 0
        // get placeholder for each in value
        var placeholders = _.map(this.args.where.id, id => {
            // get param name
            var paramName = `id${i}`
            // increment param counter
            i++
            // set value for param placeholder
            this.params[paramName] = id
            // create placeholder
            return this.unhexId(`:${paramName}`)
        })
        // return where sql
        sql = `WHERE ${columnSql} IN(${placeholders.join(', ')})`
    }
    // otherwise build equals query
    else {
        // set value for param placeholder
        this.params.id = this.args.where.id
        // get place holder
        var placeholder = this.unhexId(':id')
        // return where sql
        sql = `WHERE ${columnSql} = ${placeholder}`
    }
    // and deleted check if d column exists and set in args
    if (defined(this.model.columns.d) && typeof this.args.where.isDeleted === 'boolean') {
        sql += ` AND ${this.alias}.d = ${this.args.where.isDeleted ? 1 : 0}`
    }

    return sql
}
1015057
private static function smartUpdate($table, $fields, $where) {
        $table = self::sanitizeKey($table);
        $fieldsString = self::setFields($fields);
        $whereString = self::handleConditions($where);
        $sql = 'UPDATE ' . self::$_ops->addBackticks($table) . ' SET ' . $fieldsString . $whereString;

        return self::handleResults($sql);
    }
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);
    }
639522
public function get_or($fields)
    {
        $args = array();
        $fieldsValue = $fields;
        $fields = $this->getFields();
        $sql = '';
        foreach ($fields as $field) {
            if (isset($fieldsValue[$field])) {
                $value = $fieldsValue[$field];
                if (is_array($value)) {
                    foreach ($value as $subvalue) {
                        $sql .= '`' . $field . '` = ? OR ';
                        $args[] = $subvalue;
                    }
                } else {
                    $sql .= '`' . $field . '` = ? OR ';
                    $args[] = $value;
                }
            }
        }
        if (!empty($sql)) {
            $sql = substr($sql, 0, -4);
            return $this->build($this->db->select('SELECT * FROM `' . $this->table_name . '` WHERE ' . $sql, $args));
        }
        return $this->build(array());
    }