Parses query string into sql sentences

@param string $sSQL query string (usually reqd from *.sql file)

@return array
338890
public function parseQuery($sSQL)
    {
        // parses query into single pieces
        $aRet = [];
        $blComment = false;
        $blQuote = false;
        $sThisSQL = "";

        $aLines = explode("\n", $sSQL);

        // parse it
        foreach ($aLines as $sLine) {
            $iLen = strlen($sLine);
            for ($i = 0; $i < $iLen; $i++) {
                if (!$blQuote && ($sLine[$i] == '#' || ($sLine[0] == '-' && $sLine[1] == '-'))) {
                    $blComment = true;
                }

                // add this char to current command
                if (!$blComment) {
                    $sThisSQL .= $sLine[$i];
                }

                // test if quote on
                if (($sLine[$i] == '\'' && $sLine[$i - 1] != '\\')) {
                    $blQuote = !$blQuote; // toggle
                }

                // now test if command end is reached
                if (!$blQuote && $sLine[$i] == ';') {
                    // add this
                    $sThisSQL = trim($sThisSQL);
                    if ($sThisSQL) {
                        $sThisSQL = str_replace("\r", "", $sThisSQL);
                        $aRet[] = $sThisSQL;
                    }
                    $sThisSQL = "";
                }
            }
            // comments and quotes can't run over newlines
            $blComment = false;
            $blQuote = false;
        }

        return $aRet;
    }
153835
public function parse($query=null, $isCheckSql=true)
    {
        if (! $query instanceof Query) $query = new Query($query);
        
        $this->query = $query;
        
        // guess query type
        $queryType = $this->query->type();
        
        // before parse
        $this->beforeParse();
        
        // preprocess: check and format basic options
        $preprocessMethod = 'preprocess' . ucfirst($queryType);
        $this->$preprocessMethod();
        
        // check sql
        if ($isCheckSql) {
        	$checkMethod = 'check' . ucfirst($queryType);
        	$this->$checkMethod();
        }
        
        /**
         * get query template, template is string placeholder by set key
         * example: %select% %from% %where%
         */
        $getTemplateMethod = 'get' . ucfirst($queryType) . 'Template';
        $sqlTemplateKeys = explode(' ', $this->$getTemplateMethod());
        $queryKeys = $this->query->keys();
        
        foreach ($sqlTemplateKeys as $k=>$v) {
            if (strpos($v, '%') !== false) {
                $vk = str_replace('%', '', $v);
                if (!in_array($vk, $queryKeys)) {
                    unset($sqlTemplateKeys[$k]);
                }
            }
        }
        
        $sql = implode(' ', $sqlTemplateKeys);
        
        /**
         * parse, replace template use set value, get sql
         */
        foreach ($sqlTemplateKeys as $key=>$val) {
            $valk = str_replace(['%', '$'], '', $val);
            $sql  = str_replace($val, $this->parseQueryItem($valk, $this->query[$valk]), $sql);
        }
        $sql = $this->parseBind($sql);
        
        $sql = trim(preg_replace('/\s+/', ' ', $sql), ' ');
        
        // clear 
        $this->query->clear();
        
        return $sql;
    }
1307572
protected function query($sql) {
        $vars = func_get_args();
		$cleaner = "/[\s,].+|[^a-zA-Z]/";
		$illegal = "/[\\\\'\"\%]/";
        try {
            $pdo = $this->dbConnect();
            $stmt = $pdo->prepare($sql);
            $binds = explode(':', $sql);
            foreach($binds as $n => $b) {
				if($n != 0 && substr($b,1)!=false) {
					$b = ':' . preg_replace($cleaner,'',$b);
					$vars[$n] = preg_replace($illegal,'',$vars[$n]);
					$stmt->bindParam($b,$vars[$n]);
				}
            }
            $stmt->execute();
            return (strpos($sql,'SELECT') !== FALSE) ? $stmt->fetchAll() : true;
        } catch(PDOException $e) {
            return array('query_error' => $e);
        }
    }
656168
function parseQueryParams()
    {
        $request = $this->getMessageObject();

        $data = array();
        $url  = $request->getTarget();
        if ($p = parse_url($url, PHP_URL_QUERY))
            parse_str($p, $data);

        return $data;
    }
1161232
private function parseQueryError(string $query): array
    {
        $return = ['sql_state' => null, 'code' => null, 'message' => 'Unknown error.'];
        $resource = $this->resource->getObject();

        if (isset($resource->error_list[0])) {
            [$errno, $sqlstate, $error] = array_values($resource->error_list[0]);
        } else {
            [$errno, $sqlstate, $error] = [$resource->errno, $resource->sqlstate, $resource->error];
        }

        if ($errno) {
            $return['sql_state'] = $sqlstate;
            $return['code'] = $errno;
            // dump useless verbose message
            if ($errno == 1064) {
                preg_match('~syntax to use near (?<query>.+) at line (?<line>\d+)~sm', $error, $match);
                if (isset($match['query'], $match['line'])) {
                    $return['message'] = sprintf('Syntax error at or near "%s", line %d. Query: "%s".',
                        trim(substr($match['query'], 1, (int) ceil(strlen($match['query']) / 2))), $match['line'], $query);
                } else {
                    $return['message'] = $error;
                }
            } else {
                $return['message'] = $error;
            }
        }

        return $return;
    }
459124
protected function parse_query($sql) {
        $stmt = oci_parse($this->oci, $sql);
        if ($stmt == false) {
            throw new dml_connection_exception('Can not parse sql query'); //TODO: maybe add better info
        }
        return $stmt;
    }
1159848
protected function parseData(Query $query, $data)
    {
        if (empty($data)) {
            return [];
        }

        $result = [];

        foreach ($data as $key => $val) {
            $item = $this->parseKey($key);

            if (is_object($val)) {
                $result[$item] = $val;
            } elseif (isset($val[0]) && 'exp' === $val[0]) {
                $result[$item] = $val[1];
            } elseif (is_null($val)) {
                $result[$item] = 'NULL';
            } else {
                $result[$item] = $this->parseValue($query, $val, $key);
            }
        }

        return $result;
    }
845759
protected function getColumnsSql(array $sql): array
    {
        if (empty($this->columns)) {
            $sql[] = '*';

            return $sql;
        }
        $columns = [];
        foreach ($this->columns as $key => $column) {
            if ($column instanceof Closure) {
                // Sub Select
                $query = new SelectQuery($this->db);
                $column($query);
                $column = new RawExp($query->build(false));
            }
            $columns[] = $column;
        }
        $sql[] = implode(',', $this->quoter->quoteNames($columns));

        return $sql;
    }
568515
public function parseJoin(string $sql): array
	{
		// Get sql clause components
		preg_match_all('`'.$this->matchPatterns['function'].'`', $sql, $this->matches['functions'], PREG_SET_ORDER);
		preg_match_all('`'.$this->matchPatterns['identifier'].'`', $sql, $this->matches['identifiers'], PREG_SET_ORDER);
		preg_match_all('`'.$this->matchPatterns['operator'].'`', $sql, $this->matches['operators'], PREG_SET_ORDER);

		// Get everything at once for ordering
		$fullPattern = '`'.$this->matchPatterns['function'].'+|'.$this->matchPatterns['identifier'].'|('.$this->matchPatterns['operator'].')+`i';
		preg_match_all($fullPattern, $sql, $this->matches['combined'], PREG_SET_ORDER);

		// Go through the matches, and get the most relevant matches
		$this->matches = array_map([$this, 'filterArray'], $this->matches);

		return $this->matches;
	}
1348842
protected function extractPaginationInfo(& $cql)
    {
        $words = explode(' ', $cql);
        $limit = 0;
        $offset = 0;
        $limitKey = null;
        foreach ($words as $key => $word) {
            if ('limit' === strtolower($word) && is_numeric($words[$key + 1])) {
                $limit = (int)$words[$key + 1];
                $limitKey = $key + 1;
            }
            if ('offset' === strtolower($word) && is_numeric($words[$key + 1])) {
                $offset = (int)$words[$key + 1];
                //Take out offset from CQL. It is not supported.
                unset($words[$key], $words[$key + 1]);
            }
        }

        //Offset is not supported by CQL. Therefore need to modify limit based on offset.
        //Adding offset to limit in order to fetch all available records.
        $limit += $offset;
        if ($limitKey !== null) {
            $words[$limitKey] = $limit;
        }
        $cql = implode(' ', $words);

        return ['limit' => $limit, 'offset' => $offset];
    }
1224124
static function parse_str($query)
    {
        if ($query === null) {
            return null;
        }

        $parts = explode('&', $query);

        $new_parts = array();
        for ($i = 0; $i < count($parts); $i++) {
            $pair = explode('=', $parts[$i]);

            if (count($pair) != 2) {
                continue;
            }

            list($key, $value) = $pair;
            $new_parts[urldecode($key)] = urldecode($value);
        }

        return $new_parts;
    }
1029871
private function _parseSql($sql)
    {
        return array_values(array_filter(array_map(function ($value) { return trim(rtrim($value, $this->separator)); },
            preg_split(sprintf("/%s[\s]*\n/", preg_quote($this->separator)), rtrim(trim($sql), $this->separator)))));
    }
1252017
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;
        foreach ($this->parameters as $k => $v) {
            $v = "$quoteLeft$v$quoteRight";
            if (!is_numeric($k)) {
                $sql = str_replace($k, $v, $sql);
            } else {
                $p   = strpos($sql, '?');
                $sql = substr($sql, 0, $p) . $v . substr($sql, $p + 1);
            }
        }
        return $sql;
    }
1263100
public function _getSql()
    {
        $sql = '';
        $params = [];
        try {
            list($sql, $params) = $this->getSqlCompiler(BaseOrm::getDbConnection())->asSql();
        } catch (OrmException $e) {
        }

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

        return vsprintf($sql, $params);
    }
665165
private function tokenizeSQL($sql): array
    {
        $token = '\\(|\\)|\[|\]|[\']|"|\140|<>|<=|>=|:=|[*\/<>,+=-]';
        $terminal = $token.'|;| |\\n';
        $result = [];
        $string = $sql;
        $string = ltrim($string);
        $string = rtrim($string, ';').';'; // always ends with a terminal
        $string = preg_replace("/[\n\r]/s", ' ', $string);
        while (
            preg_match("/^($token)($terminal)/s", $string, $matches) ||
            preg_match("/^({$token})./s", $string, $matches) ||
            preg_match("/^(@?[a-zA-Z0-9_.]+?)($terminal)/s", $string, $matches)
        ) {
            $t = $matches[1];
            if ($t == '\'') {
                // it's a string
                $t = $this->tokSingleQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == "\140") {
                // it's a backtick string (a name)
                $t = $this->tokBackQuoteString($string);
                array_push($result, $t);
            }
            elseif ($t == '"') {
                // it's a double quoted string (a name in normal sql)
                $t = $this->tokDoubleQuoteString($string);
                array_push($result, $t);
            }
            else {
                array_push($result, $t);
            }
            $string = substr($string, strlen($t));
            $string = ltrim($string);
        }
        return $result;
    }
799173
public static function parse(string $yasql, string $name = null)
    {
        $parser = new Parser($yasql, $name);
        return $parser->getData();
    }
705591
protected function getFromSql(array $sql): array
    {
        if (!empty($this->from)) {
            $sql[] = 'FROM ' . $this->quoter->quoteName($this->from);
        }

        return $sql;
    }