Returns raw SQL or a paramter placeholder.

@param  mixed  $param   Parameter
@param  bool   $enclose Should subqueries be enclosed in parentheses?
@return string
436620
protected function param($param, bool $enclose = true): string
	{
		if($param instanceof Raw)
		{
			return $this->raw($param);
		}
		elseif($param instanceof Subquery)
		{
			return $this->subquery($param, $enclose);
		}
		elseif($param instanceof DateTimeInterface)
		{
			$this->params[] = $param->format(static::$dateFormat);

			return '?';
		}

		$this->params[] = $param;

		return '?';
	}
47690
public function toSQL(Parameters $params, bool $inner_clause)
    {
        $drv = $params->getDriver();
        // First get the source tables: FROM and JOIN clauses
        $source = array();

        if ($table = $this->getTable())
            $source[] = "FROM " . $drv->toSQL($params, $table);

        foreach ($this->getJoins() as $join)
            $source[] = $drv->toSQL($params, $join);

        // Now build the start of the query, all tables should be known
        $parts = array();

        $parts[] = "SELECT";
        $fields = $this->getFields();
        if (!empty($fields))
        {
            $field_parts = array();
            foreach ($fields as $field)
                $field_parts[] = $drv->toSQL($params, $field);
            $parts[] = implode(", ", $field_parts);
        }
        else
            $parts[] = "*";

        // Add the source tables and joins to the query
        foreach ($source as $part)
            $parts[] = $part;

        if ($where = $this->getWhere())
            $parts[] = $drv->toSQL($params, $where);

        if ($union = $this->getUnion())
            $parts[] = $drv->toSQL($params, $union);
        
        if ($order = $this->getOrder())
            $parts[] = $drv->toSQL($params, $order);

        if ($limit = $this->getLimit())
            $parts[] = $drv->toSQL($params, $limit);
        
        if ($offset = $this->getOffset())
            $parts[] = $drv->toSQL($params, $offset);
        
        return implode(" ", $parts);
    }
706934
public function toSQL(Parameters $params, bool $inner_clause)
    {
        return "LIMIT " . $params->getDriver()->toSQL($params, $this->getLimit());
    }
217035
protected static function generateRow(array $row, $delimiter, $enclose)
    {
        array_walk($row, function (&$item) use ($enclose) {
            if (is_bool($item)) {
                $item = (int) $item;
            } elseif (is_null($item)) {
                $item = '';
            } elseif (!is_scalar($item)) {
                $item = "[array]";
            }
            $item = $enclose.Html::encode($item).$enclose;
        });

        return implode($delimiter, $row) . PHP_EOL;
    }
1361983
public function getSqlWithParams($quotationChar = '<>')
    {
        if (($l = strlen($quotationChar)) > 1) {
            $quoteLeft = substr($quotationChar, 0, $l / 2);
            $quoteRight = substr($quotationChar, $l / 2);
        } else {
            $quoteLeft = $quoteRight = $quotationChar;
        }

        $sql = $this->sql;

        $cleanBackRefCharMap = ['%' => '%%', '$' => '$%', '\\' => '\\%'];

        foreach ($this->parameters as $k => $v) {

            $backRefSafeV = strtr($v, $cleanBackRefCharMap);

            $v = "$quoteLeft$backRefSafeV$quoteRight";

            if (is_numeric($k)) {
                $marker = "\?";
            } else {
                $marker = (preg_match("/^:/", $k)) ? $k : ":" . $k;
            }

            $matchRule = "/({$marker}(?!\w))(?=(?:[^$quotationChar]|[$quotationChar][^$quotationChar]*[$quotationChar])*$)/";
            for ($i = 0; $i <= mb_substr_count($sql, $k); $i++) {
                $sql = preg_replace($matchRule, $v, $sql, 1);
            }
        }

        $sql = strtr($sql, array_flip($cleanBackRefCharMap));

        return $sql;
    }
830040
public function toSQL(Parameters $params, bool $inner_clause)
    {
        $q = $this->getQuery();
        $t = $this->getType();
        
        $scope = $params->getSubScope($this->sub_scope_number);
        $this->sub_scope_number = $scope->getScopeID();
        return 'UNION ' . $t . ' (' . $params->getDriver()->toSQL($scope, $q) . ')';
    }
1193735
protected function prepareQueryAndParams(string $query, array $params): array
	{
		// Replace IN clause placeholder with escaped values

		replace:

		if(strpos($query, '([?])') !== false)
		{
			foreach($params as $key => $value)
			{
				if(is_array($value))
				{
					array_splice($params, $key, 1, $value);

					$query = preg_replace('/\(\[\?\]\)/', '(' . trim(str_repeat('?, ', count($value)), ', ') . ')', $query, 1);

					goto replace;
				}
			}
		}

		// Return query and parameters

		return [$query, $params];
	}
1275882
public function getParam($param = null)
    {
        if (null === $param) {
            return $this->params;
        }

        return isset($this->params[$param]) ? $this->params[$param] : null;
    }
884663
public static function get($param)
    {
        if (isset(self::$db_params[$param])) {
            return self::$db_params[$param];
        }
        return false;
    }
1011238
public function get_sql_filter($extra='', array $params=null) {
        global $SESSION;

        $sqls = array();
        if ($extra != '') {
            $sqls[] = $extra;
        }
        $params = (array)$params;

        if (!empty($SESSION->user_filtering)) {
            foreach ($SESSION->user_filtering as $fname => $datas) {
                if (!array_key_exists($fname, $this->_fields)) {
                    continue; // Filter not used.
                }
                $field = $this->_fields[$fname];
                foreach ($datas as $i => $data) {
                    list($s, $p) = $field->get_sql_filter($data);
                    $sqls[] = $s;
                    $params = $params + $p;
                }
            }
        }

        if (empty($sqls)) {
            return array('', array());
        } else {
            $sqls = implode(' AND ', $sqls);
            return array($sqls, $params);
        }
    }
898507
public function getEmulatedSQL($preservedStrLength = -1)
    {
        $context = $this->_context;

        if (!$context->bind) {
            return (string)$context->sql;
        }

        $bind = $context->bind;
        if (isset($bind[0])) {
            return (string)$context->sql;
        } else {
            $replaces = [];
            foreach ($bind as $key => $value) {
                $replaces[':' . $key] = $this->_parseBindValue($value, $preservedStrLength);
            }

            return strtr($context->sql, $replaces);
        }
    }
430667
protected function getQueryParam(string $param) : ?string
    {
        if ($this->queryParams === null) {
            $this->parseQueryParams();
        }
        return $this->queryParams[$param] ?? null;
    }
1122767
public function toSQL(Parameters $params, bool $inner_clause)
    {
        $field = $this->getField();
        $table = $this->getTable();
        if (empty($table))
            $table = $params->getDefaultTable();

        $drv = $params->getDriver();
        if (!empty($table))
        {
            list($table, $alias) = $params->resolveTable($table->getPrefix());
            if ($alias)
                $table_ref = $drv->identQuote($alias);
            else
                $table_ref = $drv->getName($table);

            return $table_ref . '.' . $drv->identQuote($field);
        }

        return $drv->identQuote($field);
    }
1189720
public function query($query=null, $params = [])
    {
        $result = false;
        $result_key = [];
        
        if ($query && static::isSql($query)) {
            $sql = $query;
        } else {
            $result_key = $this->getQuery()->set($query)->get('result_key');
            
            $queryType = $this->getQuery()->type();
            
            // limit select count
            if ((!$queryType || $queryType === 'select') 
                && !isset($this->getQuery()['count']) 
                && !isset($this->getQuery()['limit'])
                && !isset($this->getQuery()['pagesize'])) 
            {
                $this->getQuery()->set('limit', 1000);
            }
            
            // update must set where
            if (($queryType === 'update' || $queryType === 'delete') && !$this->getQuery()->get('where')) {
                Ioc::logger('db')->error('query no set where: ' . json_encode($this->getQuery()->all()));
                return false;
            }
            
            $sql = $this->parse();
        }
        
        if ($params) {
            $this->bindParams($params);
        }
        
        $this->lastSql = $this->formatSql($sql);
        
        // sql log
        Ioc::logger('db')->debug($sql);
        
        try {
            $this->getAdapter()->prepare($sql);
            if (!empty($this->binds)) {
                $this->getAdapter()->bindParams($this->binds);
            }
            $bool = $this->getAdapter()->execute();
            
            if (!$bool) {
                throw new Exception($this->getAdapter()->getErrorMessage());
            }
        } catch (Exception $e) {
            
            $this->getAdapter()->rollback();
            throw new Exception('Excute sql error: ' . $e->getMessage() . ', sql:' . $sql);
        }
        
        $rawStatement = explode(" ", $sql);
        $statement = strtolower(trim($rawStatement[0]));
        
        if ($statement === 'show') {
            $result = $this->getAdapter()->fetchAll($fetchmode);
        } elseif ($statement === 'select') {
            $rkeys = $result_key ? StringHelper::toArray($result_key, ',\s') : null;
            
            while($rs = $this->getAdapter()->fetch()) {
                // 如果指定返回结果集的key，则按key重组数据
                if ($rkeys) {
                    if (count($rkeys) == 1) {
                        $rk1 = trim($rkeys[0]);
                        if (isset($rs[$rk1])) {
                            $result[$rs[$rk1]] = $rs;
                        } else {
                            $result[] = $rs;
                        }
                    } elseif (count($rkeys) == 2) {
                        $rk1 = trim($rkeys[0]);
                        $rk2 = trim($rkeys[1]);
                        if (!empty($rk2)) {
                            $result[$rs[$rk1]][$rs[$rk2]] = $rs;
                        } else {
                            $result[$rs[$rk1]][] = $rs;
                        }
                    }
                } else {
                    $result[] = $rs;
                }
            }
        } elseif ($statement === 'update' || $statement === 'delete') {
            $result = $this->getAdapter()->numberOfRows();
        } elseif ($statement === 'insert') {
            $result = $this->getAdapter()->lastId();
        } else {
            return null;
        }
        
        return $result;
    }
537515
function execQueryString($sql, $params = null)
    {
        if (!is_array($params) && !is_null($params)) {
            $params = array($params);
        }

        $stmt = $this->prepare($sql);
        $stmt->execute($params);
        return $stmt;
    }
1104051
public function getQuery(): string
    {
        $sql = $this->getSql();

        $sql = str_replace(['%', '?'], ['%%', '"%s"'], $sql);

        // replace mask by data
        return vsprintf($sql, $this->getParams());
    }
343621
public static function getSqlWithParams(string $sql, array $params = []): string
    {
        if (! empty($params)) {
            $indexed = ($params === array_values($params));
            foreach ($params as $k => $v) {
                if (is_string($v)) {
                    $v = "'${v}'";
                }
                if (is_array($v)) {
                    $v = "'" . implode("','", $v) . "'";
                }
                if ($indexed) {
                    $sql = preg_replace('/\?/', $v, $sql, 1);
                } else {
                    $sql = str_replace(":${k}", $v, $sql);
                }
            }
        }

        return str_replace(PHP_EOL, '', $sql);
    }