function _parseSqlAll_fixAliasesInNode(&$sqlTree, $fromList, &$selectTreeNode = FALSE) { foreach ($sqlTree as &$node) { if (isSubquery($node)) { _parseSqlAll_fixAliases($node['sub_tree']); } //only process colrefs if (!isColref($node) && !isExpression($node)) { continue; } $table = extractTableName($node); $column = extractColumnName($node); //we only need to change this column if it was retrieved from a subquery if ($table !== false && array_key_exists($table, $fromList) && isSubquery($fromList[$table]) && $fromList[$table]['sub_tree'] != NULL) { //look this column up in the sub select foreach ($fromList[$table]['sub_tree']['SELECT'] as $selNode) { if (hasAlias($selNode) && strpos($selNode['alias']['name'], $column)) { $node['base_expr'] = "`" . $table . "`.`" . trim($selNode['alias']['name'], "`") . "`"; $node['no_quotes'] = array("delim" => ".", "parts" => array($table, trim($selNode['alias']['name'], "`"))); } } } else { if ($selectTreeNode !== FALSE) { //go through the list of columns in the select tree part, and find the corresponding alias //we are doing this the cheep way: //take the column name in where/order/group and get rid of all ` and replace . with __ //this way we should end up with a name that should be contained in the SELECT column list $currAlias = str_replace(".", "__", str_replace("`", "", $node['base_expr'])); $strLenCurrAlias = strlen($currAlias); foreach ($selectTreeNode as $selNode) { $nodeAlias = trim($selNode['alias']['name'], "`"); $aliasStrPos = strpos($nodeAlias, $currAlias); if ($aliasStrPos !== FALSE && strlen($nodeAlias) == $aliasStrPos + $strLenCurrAlias) { $node['base_expr'] = $selNode['alias']['name']; $node['no_quotes'] = array("delim" => ".", "parts" => array($selNode['alias']['name'])); } } } } } }
function extractColumnAlias($node) { //is this a table type or colref/alias? if ((isColref($node) || isFunction($node) || isExpression($node)) && isset($node['alias']['as'])) { $partCounts = count($node['alias']['no_quotes']['parts']); return $node['alias']['no_quotes']['parts'][$partCounts - 1]; } else { //don't know what to do return false; } }
/** * @param mixed $variable * * @return bool */ function isString($variable) { return is_string($variable) and !isExpression($variable); }