Generate SQL string for JOINs

@param  string $fromAlias The alias of the table

@return string
978009
protected function prepareJoins($fromAlias): string
    {
        if (!isset($this->join[$fromAlias])) {
            return '';
        }

        $query = '';

        foreach ($this->join[$fromAlias] as $join) {
            $query .= ' ' . strtoupper($join['joinType'])
                . ' JOIN ' . Db::quoteIdentifier($join['joinTable']) . ' AS ' . Db::quoteIdentifier($join['joinAlias'])
                . ' ON ' . $join['joinCondition'];
            $query .= $this->prepareJoins($join['joinAlias']);
        }

        return $query;
    }
244137
public function alias($alias)
    {
        if (is_array($alias)) {
            foreach ($alias as $key => $val) {
                $this->options['alias'][$key] = $val;
            }
        } else {
            if (isset($this->options['table'])) {
                $table = is_array($this->options['table']) ? key($this->options['table']) : $this->options['table'];
                if (false !== strpos($table, '__')) {
                    $table = $this->parseSqlTable($table);
                }
            } else {
                $table = $this->getTable();
            }

            $this->options['alias'][$table] = $alias;
        }
        return $this;
    }
61964
private function getSQLIdentifier(SelectStatement $AST)
    {
        // Find out the SQL alias of the identifier column of the root entity.
        // It may be possible to make this work with multiple root entities but that
        // would probably require issuing multiple queries or doing a UNION SELECT.
        // So for now, it's not supported.

        // Get the root entity and alias from the AST fromClause.
        $from = $AST->fromClause->identificationVariableDeclarations;
        if (count($from) !== 1) {
            throw new \RuntimeException('Cannot count query which selects two FROM components, cannot make distinction');
        }

        $fromRoot       = reset($from);
        $rootAlias      = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable;
        $rootClass      = $this->queryComponents[$rootAlias]['metadata'];
        $rootIdentifier = $rootClass->identifier;

        // For every identifier, find out the SQL alias by combing through the ResultSetMapping
        $sqlIdentifier = [];
        foreach ($rootIdentifier as $property) {
            if (isset($rootClass->fieldMappings[$property])) {
                foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) {
                    if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) {
                        $sqlIdentifier[$property] = $alias;
                    }
                }
            }

            if (isset($rootClass->associationMappings[$property])) {
                $joinColumn = $rootClass->associationMappings[$property]['joinColumns'][0]['name'];

                foreach (array_keys($this->rsm->metaMappings, $joinColumn) as $alias) {
                    if ($this->rsm->columnOwnerMap[$alias] == $rootAlias) {
                        $sqlIdentifier[$property] = $alias;
                    }
                }
            }
        }

        if (count($sqlIdentifier) === 0) {
            throw new \RuntimeException('The Paginator does not support Queries which only yield ScalarResults.');
        }

        if (count($rootIdentifier) != count($sqlIdentifier)) {
            throw new \RuntimeException(sprintf(
                'Not all identifier properties can be found in the ResultSetMapping: %s',
                implode(', ', array_diff($rootIdentifier, array_keys($sqlIdentifier)))
            ));
        }

        return $sqlIdentifier;
    }
309780
final protected function getOrderBySQL(array $orderBy, $baseTableAlias)
    {
        if (! $orderBy) {
            return '';
        }

        $orderByList = [];

        foreach ($orderBy as $fieldName => $orientation) {
            $orientation = strtoupper(trim($orientation));

            if (! in_array($orientation, ['ASC', 'DESC'], true)) {
                throw InvalidOrientation::fromClassNameAndField($this->class->getClassName(), $fieldName);
            }

            $property = $this->class->getProperty($fieldName);

            if ($property instanceof FieldMetadata) {
                $tableAlias = $this->getSQLTableAlias($property->getTableName());
                $columnName = $this->platform->quoteIdentifier($property->getColumnName());

                $orderByList[] = $tableAlias . '.' . $columnName . ' ' . $orientation;

                continue;
            } elseif ($property instanceof AssociationMetadata) {
                if (! $property->isOwningSide()) {
                    throw InvalidFindByCall::fromInverseSideUsage(
                        $this->class->getClassName(),
                        $fieldName
                    );
                }

                $class      = $this->class->isInheritedProperty($fieldName)
                    ? $property->getDeclaringClass()
                    : $this->class;
                $tableAlias = $this->getSQLTableAlias($class->getTableName());

                foreach ($property->getJoinColumns() as $joinColumn) {
                    /** @var JoinColumnMetadata $joinColumn */
                    $quotedColumnName = $this->platform->quoteIdentifier($joinColumn->getColumnName());

                    $orderByList[] = $tableAlias . '.' . $quotedColumnName . ' ' . $orientation;
                }

                continue;
            }

            throw UnrecognizedField::byName($fieldName);
        }

        return ' ORDER BY ' . implode(', ', $orderByList);
    }
103153
private function buildSelectJoinPart(ISelectBuilder $query)
    {
        $joins = $query->getJoins();
        if (!count($joins)) {
            return '';
        }

        $result = '';

        foreach ($joins as $join) {
            list($name, $alias) = $join->getTable();
            $result .= "\n\t" . $join->getType() . ' JOIN ';
            $result .= $this->quoteIdentifier($name) . ($alias ? ' AS ' . $this->quoteIdentifier($alias) : '');
            $joinConditions = [];
            foreach ($join->getConditions() as $condition) {
                list($leftColumn, $operator, $rightColumn) = $condition;
                $joinConditions[] = $this->quoteIdentifier($leftColumn)
                    . ' ' . $operator . ' ' . $this->quoteIdentifier($rightColumn);
            }

            if (count($joinConditions) === 1) {
                $result .= ' ON ' . $joinConditions[0];
            } elseif (count($joinConditions) > 1) {
                $result .= ' ON (' . implode(' AND ', $joinConditions) . ')';
            }
        }

        return $result;
    }
1211064
public function get_join(array $cfg): string
  {
    $res = '';
    if ( !empty($cfg['join']) ){
      foreach ( $cfg['join'] as $join ){
        if ( isset($join['table'], $join['on']) && ($cond = $this->db->get_conditions($join['on'], $cfg)) ){
          $res .=
            (isset($join['type']) && ($join['type'] === 'left') ? 'LEFT ' : '').
            'JOIN '.$this->table_full_name($join['table'],true).
            (!empty($join['alias']) ? ' AS '.$this->escape($join['alias']) : '').PHP_EOL.'ON '.$cond;
        }
      }
    }
    return $res;
  }
1098740
final function Table($alias = '', array $fieldAliases = array())
    {
        $sql = $this->SqlBuilder();
        return $sql->Table($this->TableName(), $this->FieldNames($fieldAliases), $alias);
    }
573295
protected function sortedQueryPrefix(array $aliases) {

        $sortFields = [];

        $result = $this->getDriverEscaper()->dbCommand('SELECT') . ' ' .
                $this->getDriverEscaper()->reserved('subject') . ' ' .
                $this->getDriverEscaper()->dbCommand('FROM') .
                $this->operationSeparator . '(' .
                $this->getDriverEscaper()->dbCommand('SELECT') . ' ' .
                $this->getDriverEscaper()->reserved('mainq') . '.' .
                $this->getDriverEscaper()->reserved('subject') .
                $this->getDriverEscaper()->getFieldsSeparator();

        foreach ($aliases as $alias) {
            $sortFields[] = $this->getDriverEscaper()->reserved($alias['name']) . '.' .
                    $this->getDriverEscaper()->reserved('object') . ' ' .
                    $this->getDriverEscaper()->dbCommand('AS') . ' ' . $alias['name'];
        }

        $result .= implode($this->getDriverEscaper()->getFieldsSeparator(), $sortFields)
                . ' ' .
                $this->getDriverEscaper()->dbCommand('FROM') . ' ' .
                ' ( ' . $this->query . ' ) AS mainq ' .
                $this->operationSeparator;

        return $result;
    }
799918
protected function getAliasSql(string $sql): string
    {
        if (!isset($this->alias)) {
            return $sql;
        }

        return sprintf('(%s) AS %s', $sql, $this->quoter->quoteName($this->alias));
    }
934467
private function getDeleteQuery()
    {
        $fromClause = null;

        if (isset($this->parts['from'][0]['alias'])) {
            $fromClause = $this->parts['from'][0]['alias'].' ';
        }

        $fromClause .= 'FROM '.$this->getFromClause();

        return 'DELETE '.$fromClause.
               (($this->parts['where'] !== null) ? ' WHERE '.$this->parts['where'] : null);
    }
245032
public function innerJoinTwoSequentialTables(
        string $fromAlias,
        string $fromColumn,
        string $intTable,
        string $intToFromColumn,
        string $intToTargetColumn,
        string $targetTable,
        string $targetColumn
    ): string {
        $intAlias    = $this->innerJoinOneTable($fromAlias, $fromColumn, $intTable, $intToFromColumn);
        $targetAlias = $this->innerJoinOneTable($intAlias, $intToTargetColumn, $targetTable, $targetColumn);

        return $targetAlias;
    }
260952
public static function render(SQL\Aliased $aliased)
    {
        $content = $aliased->getContent();

        if ($content instanceof Query\Select) {
            $content = "(".Select::render($content).")";
        } else {
            $content = Compiler::name($content);
        }

        return Compiler::expression(array(
            $content,
            Compiler::word('AS', Compiler::name($aliased->getAlias()))
        ));
    }
956110
public function formatFieldsWithFieldAlias($table_alias = null)
    {
        $fields = $this->getFieldsWithTableAlias($table_alias);

        return join(
            ', ',
            array_map(
                function ($field_alias, $field_definition) {
                    return sprintf(
                        '%s as "%s"',
                        $field_definition,
                        addcslashes($field_alias, '"\\')
                    );
                },
                array_keys($fields),
                $fields
            )
        );
    }
154619
protected function compileOneJoin(Join $join, array &$bindings): string
    {
        $sql = $join->type.' JOIN '.$this->compileIdentifierWithAlias($join->table, $join->tableAlias, $bindings);

        if ($join->criteria) {
            $sql .= ' ON '.$this->compileCriteria($join->criteria, $bindings);
        }

        return $sql;
    }
500752
protected function _quoteJoins($joins)
    {
        $result = [];
        foreach ($joins as $value) {
            $alias = null;
            if (!empty($value['alias'])) {
                $alias = $this->_driver->quoteIdentifier($value['alias']);
                $value['alias'] = $alias;
            }

            if (is_string($value['table'])) {
                $value['table'] = $this->_driver->quoteIdentifier($value['table']);
            }

            $result[$alias] = $value;
        }

        return $result;
    }
911423
public function tokenizeSqlStatement($statementString)
    {

#		$statementString = preg_replace("/\s+/is", " ", $statementString);
        $statementString = str_replace("\t", "  ", $statementString);

        $reflectionTokenEnum = new \ReflectionClass("\Addiks\PHPSQL\Value\Enum\Sql\SqlToken");

        $tokenNames = array_map(function ($tokenName) {
            return substr($tokenName, 2);
        }, array_keys($reflectionTokenEnum->getConstants()));

        $tokenNamePattern = "^(".implode("|", $tokenNames).")([^A-Z0-9_]|\$)";

        $userSpaceKeyWordPattern = "^([a-zA-Z0-9_-]+)([^A-Z_]|\$)";

        $stringQuotePattern  = "^\'[^\']*\'";
        $stringDQuotePattern = "^\"[^\"]*\"";
        $stringWordPattern   = "^\`[^\`]*\`";

        $operatorPattern = "^(".implode("|", ['<=>', '!=', '<>', '<=', '>=']).")([^A-Z_]|\$)";
        $otherCharactersPattern = "^[\\".implode("\\", str_split("+-*/,.()-=<>|&;!?", 1))."]";
        $commentPattern = "^\-\-[^\n]*\n";
        $multiLineComment = "^\/\*.*?\*\/";

        $numberPattern     = "^((0|\-?[1-9]([0-9]+)?)(\.[0-9]+)?)([^A-Z_]|\$)";
        $whiteSpacePattern = "^\s+";

        $variablePattern = "^(\:[a-zA-Z0-9_-]+|\?)([^A-Z_]|\$)";

        $position = 0;
        $statementStringLeft = substr($statementString, $position);

        $tokenArray = array();
        $line = 1;

        while (strlen($statementStringLeft)>0) {
            switch(true){

                case preg_match("/{$whiteSpacePattern}/", $statementStringLeft, $matches):
                    $position += strlen($matches[0]);
                    $tokenArray[] = [T_WHITESPACE, $matches[0], $line];
                    $line += substr_count($matches[0], "\n");
                    break;

            #	case $statementStringLeft[0]===' ':
            #		$position++;
            #		break;

                case preg_match("/{$numberPattern}/", $statementStringLeft, $matches):
                    $position += strlen($matches[1]);
                    $tokenArray[] = [T_NUM_STRING, $matches[1], $line];
                    break;

                case preg_match("/{$stringQuotePattern}/", $statementStringLeft, $matches):
                case preg_match("/{$stringDQuotePattern}/", $statementStringLeft, $matches):
                    $position += strlen($matches[0]);
                    $tokenArray[] = [T_CONSTANT_ENCAPSED_STRING, $matches[0], $line];
                    $line += substr_count($matches[0], "\n");
                    break;

                case preg_match("/{$commentPattern}/is", $statementStringLeft, $matches):
                    $position += strlen($matches[0]);
                    $tokenArray[] = [T_COMMENT, $matches[0], $line];
                    $line += substr_count($matches[0], "\n");
                    break;

                case preg_match("/{$multiLineComment}/is", $statementStringLeft, $matches):
                    $position += strlen($matches[0]);
                    $tokenArray[] = [T_COMMENT, $matches[0], $line];
                    $line += substr_count($matches[0], "\n");
                    break;


                case preg_match("/{$tokenNamePattern}/is", $statementStringLeft, $matches):
                    $tokenName = strtoupper("T_{$matches[1]}");
                    $position += strlen($matches[1]);
                    $tokenValue = call_user_func("\Addiks\PHPSQL\Value\Enum\Sql\SqlToken::{$tokenName}");
                    $tokenArray[] = [$tokenValue, $matches[1], $line];
                    break;

                case preg_match("/{$variablePattern}/si", $statementStringLeft, $matches):
                    $position += strlen($matches[1]);
                    $tokenArray[] = [T_VARIABLE, $matches[1], $line];
                    break;

                case preg_match("/{$operatorPattern}/is", $statementStringLeft, $matches):
                    $position += strlen($matches[1]);
                    $tokenArray[] = [$matches[1], $matches[1], $line];
                    break;

                case preg_match("/{$otherCharactersPattern}/is", $statementStringLeft, $matches):
                    $position += strlen($matches[0]);
                    $tokenArray[] = [$matches[0], $matches[0], $line];
                    break;

                case preg_match("/{$stringWordPattern}/", $statementStringLeft, $matches):
                    $word = substr($matches[0], 1, strlen($matches[0])-2);
                    $position += strlen($matches[0]);
                    $tokenArray[] = [T_STRING, $word, $line];
                    $line += substr_count($matches[0], "\n");
                    break;

                case preg_match("/{$userSpaceKeyWordPattern}/si", $statementStringLeft, $matches):
                    $position += strlen($matches[1]);
                    $tokenArray[] = [T_STRING, $matches[1], $line];
                    break;

                default:
                    $malformedSQLPart = substr($statementString, $position, 100);
                    throw new ErrorException("Malformed SQL: '{$malformedSQLPart}'!");
            }
            $statementStringLeft = substr($statementString, $position);
        }

        return $tokenArray;
    }
1191656
public function aliasNamespace($from, $to)
	{
		$from = trim($from, '\\');
		$to = trim($to, '\\');

		$this->namespaces[] = [$from, $to];
	}