创建子查询SQL
@access public
@param bool $sub
@return string
@throws DbException
354236
public function buildSql($sub = true)
    {
        return $sub ? '( ' . $this->select(false) . ' )' : $this->select(false);
    }
1042447
public function select(SQLStatement $select): string
    {
        $limit = $select->getLimit();

        if ($limit <= 0) {
            return parent::select($select);
        }

        $sql = $select->getDistinct() ? 'SELECT DISTINCT ' : 'SELECT ';
        $sql .= $this->handleColumns($select->getColumns());
        $sql .= ' FROM ';
        $sql .= $this->handleTables($select->getTables());
        $sql .= $this->handleJoins($select->getJoins());
        $sql .= $this->handleWheres($select->getWheres());
        $sql .= $this->handleGroupings($select->getGroupBy());
        $sql .= $this->handleOrderings($select->getOrder());
        $sql .= $this->handleHavings($select->getHaving());

        $offset = $select->getOffset();

        if ($offset < 0) {
            return 'SELECT * FROM (' . $sql . ') M1 WHERE ROWNUM <= ' . $limit;
        }

        $limit += $offset;
        $offset++;

        return 'SELECT * FROM (SELECT M1.*, ROWNUM AS OPIS_ROWNUM FROM (' . $sql . ') M1 WHERE ROWNUM <= ' . $limit . ') WHERE OPIS_ROWNUM >= ' . $offset;
    }
502678
function DB()
	{
	global $_ADODB_ACTIVE_DBS;

		if ($this->_dbat < 0) {
			$false = false;
			$this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
			return $false;
		}
		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
		$db = $activedb->db;
		return $db;
	}
827270
public function sql(): string
    {
        if (empty($this->parts)) {
            return '1';
        }
        return (string) \array_reduce(
            $this->parts,
            function (string $sql, array $part): string {
                /** @var string|self $condition */
                $condition = $part['condition'];

                if ($this->isGroup($condition)) {
                    // (...)
                    if (\is_string($condition)) {
                        $statement = '(' . $condition . ')';
                    } else {
                        $statement = '(' . $condition->sql() . ')';
                    }
                } else {
                    // foo = ?
                    $statement = $condition;
                }
                /** @var string $statement */
                $statement = (string) $statement;
                $part['type'] = (string) $part['type'];

                if ($sql) {
                    switch ($part['type']) {
                        case 'AND':
                        case 'OR':
                            $statement = $part['type'] . ' ' . $statement;
                            break;
                        default:
                            throw new RuntimeException(
                                \sprintf('Invalid joiner %s', $part['type'])
                            );
                    }
                }

                return \trim($sql . ' ' . $statement);
            },
            ''
        );
    }
503458
public static function _getValues ($params = array (), &$db = FALSE)
	{
		
		// Set select

		if (!isset ($params['select']))
		{
			$params['select']	= '*';
		}
		
		// Set from

		if (!isset ($params['from']))
		{
			$params['from']		= '`' . static::$dbTable . '`';
		}
		
		// Get database slave for read

		if ($db === FALSE)
		{
			$db	=& self::_getDbSlave ();
		}
		
		// Return value

		return $db->getValues ($params);

	}
1084953
public function load($overwrite = false)
	{
		$lang = array();

		foreach ($this->languages as $language)
		{
			// try to retrieve the config from the database
			try
			{
				$result = \DB::select('lang')->from($this->table)->where('identifier', '=', $this->identifier)->where('language', '=', $language)->execute();
			}
			catch (Database_Exception $e)
			{
				// strip the actual query from the message
				$msg = $e->getMessage();
				$msg = substr($msg, 0, strlen($msg)  - strlen(strrchr($msg, ':')));

				// and rethrow it
				throw new \Database_Exception($msg);
			}

			// did we succeed?
			if ($result->count())
			{
				if ( ! empty($result[0]['lang']))
				{
					$lang = $overwrite ?
						array_merge($lang, unserialize($this->parse_vars($result[0]['lang']))) :
						\Arr::merge($lang, unserialize($this->parse_vars($result[0]['lang'])));
				}
			}
		}


		return $lang;
	}
1079233
public function sql(&$parameters = array())
    {
        // Build each component as needed
        $sql = DB::build_sql($this, $parameters);

        if (empty($sql)) {
            return null;
        }

        if ($this->replacementsOld) {
            $sql = str_replace($this->replacementsOld, $this->replacementsNew, $sql);
        }

        return $sql;
    }
219840
public function query($sql, $execute = FALSE)
    {

        $query = (empty($sql)) ? $this->query : $sql;
        $this->transactions[] = $this->replacePrefix($query); //just for reference

        //@TODO;
        if ($execute) {
            $this->exec($query);
        }

        return true;
    }
1233040
protected function build_query($count = false) {
        $sql = 'SELECT ';

        if ($count) {
            $sql .= 'COUNT(\'x\') ';
        } else {
            $sql .= implode(', ', $this->fields) . ' ';
        }

        $sql .= $this->from . ' ';
        $sql .= implode(' ', $this->joins) . ' ';

        if (!empty($this->where)) {
            $sql .= 'WHERE (' . implode(') AND (', $this->where) . ') ';
        }

        if (!$count && !empty($this->order)) {
            $sql .= 'ORDER BY ' . implode(', ', $this->order);
        }

        return $sql;
    }
929963
public function buildQuery($query = null)
    {
        if (null === $query) {
            $query = $this->query;
        }

        $sql = "SELECT ";
        if (isset($query['distinct']) && $query['distinct']) {
            $sql .= 'DISTINCT ';
        }
        $sql .= isset($query['select']) ? $query['select'] : '*';

        if (!isset($query['from'])) {
            return false;
        }

        $sql .= "\nFROM " . $query['from'];
        if (isset($query['join'])) {
            $sql .= "\n" . (is_array($query['join']) ? implode("\n", $query['join']) : $query['join']);
        }
        if (isset($query['where']) && $query['where'] !== '') {
            $sql .= "\nWHERE " . $query['where'];
        }
        if (isset($query['group'])) {
            $sql .= "\nGROUP BY " . $query['group'];
            if (isset($query['having'])) {
                $sql .= "\nHAVING " . $query['having'];
            }
        }
        if (isset($query['order'])) {
            $sql .= "\n ORDER BY " . $query['order'];
        }
        $limit = isset($query['limit']) ? $query['limit'] : 0;
        $offset = isset($query['offset']) ? $query['offset'] : 0;
        $sql = $this->db->buildLimitOffset($sql, $limit, $offset);

        if (isset($query['union'])) {
            $sql .= "\n" . (is_array($query['union']) ? implode("\n", $query['union']) : $query['union']);
        }

        return $sql;
    }
584166
public function getSelectSql($for_max_object_count = false): string
    {
        // Select
        if ($this->getSelectFields()) {
            $select_sql = [];
            foreach ($this->getSelectFields() as $field_data) {
                // Simple select
                if ($field_data['type'] === 'simple') {
                    $select_sql[] = '`' . $field_data['table'] . '`.`' . $field_data['field'] . '`' . ($field_data['as'] ? ' AS `' . $field_data['as'] . '`' : '');
                } elseif ($field_data['type'] === 'string') {
                    $select_sql[] = $field_data['field'];
                } elseif ($field_data['type'] === TableStructure::FIELD_TYPE_TRANSLATION) {
                    $select_sql[] = '`' . $field_data['table'] . '`.`' . $field_data['field'] . '` AS `' . $field_data['as'] . '`';
                }
            }
            $select_sql = implode(', ', $select_sql);
        } else {
            $select_sql = '`' . $this->getDbTableName() . '`.*';
        }

        // Where
        $where_sql = $this->getWhereSql();
        $where_sql = $where_sql ? 'WHERE ' . $where_sql : '';

        // Having
        $having_sql = $this->getHavingSql();
        $having_sql = $having_sql ? 'HAVING ' . $having_sql : '';

        // Order by
        $order_by_sql = $this->getOrderBySQL();

        // Limit
        $limit_sql = $this->sql_limit ? 'LIMIT ' . $this->sql_offset . ', ' . $this->sql_limit : '';

        // Group by
        $group_sql = $this->getGroupBySql();

        // Joins
        $join_sql = $this->getJoinTablesSql();

        // Counting total
        if ($for_max_object_count) {
            $select_sql = 'COUNT(*)';
            $where_sql = '';
            $having_sql = '';
            $order_by_sql = '';
            $limit_sql = '';
        }

        $sql_calc_found_rows = $this->require_to_count_total_rows ? ' SQL_CALC_FOUND_ROWS ' : '';

        $sql = '
SELECT ' . $sql_calc_found_rows . $select_sql . '
FROM `' . $this->getDbTableName() . '`
' . $join_sql . '
' . $where_sql . '
' . $group_sql . '
' . $having_sql . '
' . $order_by_sql . '
' . $limit_sql . '
    ';

        return $sql;
    }
107533
public function nextQuery()
    {
        $sql = null;

        while (($line = $this->sqlReader->readLine()) !== null) {
            $delimiter = $this->parent->getDelimiter();
            $project = $this->parent->getOwningTarget()->getProject();
            $line = $project->replaceProperties(trim($line));

            if (($line != $delimiter) && (StringHelper::startsWith("//", $line)
                    || StringHelper::startsWith("--", $line)
                    || StringHelper::startsWith("#", $line))
            ) {
                continue;
            }

            $sql .= " " . $line . "\n";

            /**
             * fix issue with PDO and wrong formated multistatements
             *
             * @issue 1108
             */
            if (StringHelper::endsWith($delimiter, $line)) {
                break;
            }
        }

        return $sql;
    }
1362555
public function getNextStatement()
    {
        $isAfterBackslash = false;
        $isInString = false;
        $stringQuotes = '';
        $parsedString = '';
        $lowercaseString = ''; // helper variable for performance sake
        while ($this->pos <= $this->len) {
            $char = isset($this->sql[$this->pos]) ? $this->sql[$this->pos] : '';
            // check flags for strings or escaper
            switch ($char) {
                case "\\":
                    $isAfterBackslash = true;
                    break;
                case "'":
                case "\"":
                    if ($isInString && $stringQuotes == $char) {
                        if (!$isAfterBackslash) {
                            $isInString = false;
                        }
                    } elseif (!$isInString) {
                        $stringQuotes = $char;
                        $isInString = true;
                    }
                    break;
            }
            $this->pos++;
            if ($char !== "\\") {
                $isAfterBackslash = false;
            }
            if (!$isInString) {
                if (false !== strpos($lowercaseString, 'delimiter ')) {
                    // remove DELIMITER from string because it's a command-line keyword only
                    $parsedString = trim(str_ireplace('delimiter ', '', $parsedString));
                    // set new delimiter
                    $this->delimiter = $char;
                    // append other delimiter characters if any
                    while (isset($this->sql[$this->pos]) && $this->sql[$this->pos] != "\n") {
                        $this->delimiter .= $this->sql[$this->pos++]; // increase position
                    }
                    $this->delimiter = trim($this->delimiter);
                    // store delimiter length for better performance
                    $this->delimiterLength = strlen($this->delimiter);
                    // delimiter has changed so return current sql if any
                    if ($parsedString) {
                        return $parsedString;
                    } else {
                        // reset helper variable
                        $lowercaseString = '';
                        continue;
                    }
                }
                // get next characters if we have multiple characters in delimiter
                $nextChars = '';
                for ($i = 0; $i < $this->delimiterLength - 1; $i++) {
                    if (!isset($this->sql[$this->pos + $i])) break;
                    $nextChars .= $this->sql[$this->pos + $i];
                }
                // check for end of statement
                if ($char.$nextChars == $this->delimiter) {
                    $this->pos += $i; // increase position
                    return trim($parsedString);
                }
                // avoid using strtolower on the whole parsed string every time new character is added
                // there is also no point in adding characters which are in the string
                $lowercaseString .= strtolower($char);
            }
            $parsedString .= $char;
        }
        return trim($parsedString);
    }
397484
public function getSQL($strip_table_name = false)
        {
            $sql_parts = [];
            foreach ($this->parts as $part) {
                if ($part instanceof Criterion) {
                    $part->setCriteria($this);
                } elseif ($part instanceof Criteria) {
                    $part->setQuery($this->query);
                }

                $sql_parts[] = $part->getSql($strip_table_name);
            }

            if (count($sql_parts) > 1) {
                return '(' . join(" {$this->getMode()} ", $sql_parts) . ')';
            } else {
                return $sql_parts[0];
            }
        }
105653
function MetaTables($ttype=false,$showSchema=false,$mask=false)
	{
		$false = false;
		if ($this->metaTablesSQL) {
			// complicated state saving by the need for backward compat

			if ($ttype == 'VIEWS'){
						$sql = str_replace('U', 'V', $this->metaTablesSQL);
			}elseif (false === $ttype){
						$sql = str_replace('U',"U' OR type='V", $this->metaTablesSQL);
			}else{ // TABLES OR ANY OTHER
						$sql = $this->metaTablesSQL;
			}
			$rs = $this->Execute($sql);

			if ($rs === false || !method_exists($rs, 'GetArray')){
					return $false;
			}
			$arr = $rs->GetArray();

			$arr2 = array();
			foreach($arr as $key=>$value){
					$arr2[] = trim($value['name']);
			}
			return $arr2;
		}
		return $false;
	}
844785
public function sql($sql, $val = false) {
        #$val为true时，返回执行结果
        $result = preg_split('/;(\r|\n)/is', $sql);
        if ($val) {
            foreach ((array) $result as $r) {
                if ($row = $this->connection->query($r)) {
                    return $row;
                } else {
                    return false;
                }
            }
        }
        foreach ((array) $result as $r) {
            if (!$this->connection->execute($r)) {
                return false;
            }
        }
        return true;
    }
761052
public function query($sql, $binders = array(), $suggestedClass = null, $debug = false)
    {
        //By keeping track of the last binding location, we can skip
        //binders that are within bound data
        $minBinderLocation = 0;

        if (!is_array($binders)) $binders = array($binders);

        if (!empty($binders)) {
            foreach ($binders as &$bound) {
                $bound = $this->provider->escapeItem($bound);

                $bindingLocation = strpos($sql, static::DATABASE_BINDING_TOKEN, $minBinderLocation);

                if ($bindingLocation !== false) {
                    $sql = substr_replace($sql, $bound, $bindingLocation, 1);

                    $minBinderLocation = $bindingLocation + mb_strlen($bound) + 1;
                }
            }
        }

        $data = $this->provider->query($sql, $suggestedClass);

        if (!empty($debug)) {
            $output = new \stdClass();
            $output->sql = $sql;
            $output->response = $data;
            $output->inputs = $binders;

            if (!empty($this->log))
            {
                $this->log->notice('Debug Output', [$output]);
            }
        }

        return $data;
    }