Builds the SQL statement from all attributes previously set.

@throws \Bloatless\Endocore\Components\Database\Exception\DatabaseException
@return string
199372
protected function buildStatement(): string
    {
        $this->statementBuilder->addFlags($this->flags);
        $this->statementBuilder->addInto($this->into);
        $this->statementBuilder->addRows($this->rows);
        return $this->statementBuilder->getStatement();
    }
1182066
public function toString()
    {
        if (!$this->_parts['into']) {
            throw new SqlException("Invalid `INSERT` statement, missing `INTO` clause.");
        }

        $fields = count($this->_parts['values']) ? array_keys($this->_parts['values'][0]) : [];

        return 'INSERT' .
            $this->_buildFlags($this->_parts['flags']) .
            $this->_buildClause('INTO', $this->dialect()->name($this->_parts['into'], true)) .
            $this->_buildChunk('(' . $this->dialect()->names($fields, true) . ')', false) .
            $this->_buildValues() .
            $this->_buildClause('RETURNING', $this->dialect()->names($this->_parts['returning'], false, ''));
    }
711172
protected function buildStatement(): string
    {
        $this->statementBuilder->addFrom($this->from);
        $this->statementBuilder->addWhere($this->where);
        return $this->statementBuilder->getStatement();
    }
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);
    }
1245117
public function toSQL(): string
    {
        switch ($this->type) {
            case self::INSERT:
                $sql = $this->getSQLForInsert();
                break;

            case self::DELETE:
                $sql = $this->getSQLForDelete();
                break;

            case self::UPDATE:
                $sql = $this->getSQLForUpdate();
                break;

            case self::SELECT:
            default:
                $sql = $this->getSQLForSelect();
                break;
        }

        return $sql;
    }
265357
public function getSQLForInsert()
    {
        $columns = array_map(function ($column) {
            return $this->getQuotedName($column);
        }, array_keys(current($this->sqlParts['values'])));

        $values = [];
        foreach ($this->sqlParts['values'] as $part) {
            $record = array_map(function ($value) {
                if ($value instanceof ToSqlInterface) {
                    return $value->toSQL();
                }

                return $this->getAdapter()->getSqlType($value);
            }, $part);

            $values[] = '('.implode(', ', $record).')';
        }

        $table = $this->getQuotedName($this->sqlParts['from']['table']);

        return sprintf(
            'INSERT INTO %s (%s) VALUES %s',
            $table,
            implode(', ', $columns),
            implode(', ', $values)
        );
    }
362409
public function toUpdateSQL($attributes = array())
    {
        $sql = [];
        $this->params = [];
        
        $sql[] = sprintf('UPDATE %s SET', $this->table->getTableName());
        $setts = [];
        foreach ($attributes as $key => $value) {
            $setts[] = sprintf('%s = ?', $key);
            $this->addParam($value);
        }
        $sql[] = join(', ', $setts);
        $sql[] = $this->where->toSQL();
        $this->bind($this->where->getParams());

        return join(' ', $sql);
    }
385571
public function build(): string
    {
        $table = $this->quoter->quoteName($this->table);

        $insert = 'INSERT';
        if (!empty($this->priority)) {
            $insert .= ' ' . $this->priority;
        }
        if (!empty($this->ignore)) {
            $insert .= ' ' . $this->ignore;
        }

        if (array_key_exists(0, $this->values)) {
            // multiple rows
            $result = sprintf('%s INTO %s (%s) VALUES', $insert, $table, $this->quoter->quoteFields($this->values[0]));
            foreach ($this->values as $key => $row) {
                $result .= sprintf('%s(%s)', ($key > 0) ? ',' : '', $this->quoter->quoteBulkValues($row));
            }
        } else {
            // single row
            $result = sprintf('%s INTO %s SET %s', $insert, $table, $this->quoter->quoteSetValues($this->values));
        }

        if ($this->duplicateValues) {
            $values = $this->quoter->quoteSetValues($this->duplicateValues);
            $result .= sprintf(' ON DUPLICATE KEY UPDATE %s', $values);
        }
        $result .= ';';

        return $result;
    }
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);
    }
1065533
protected function generateJoinSQL()
        {
            $sql = ' FROM ' . $this->getTable()->getSelectFromSql();
            foreach ($this->query->getJoins() as $join) {
                $sql .= ' ' . $join->getJoinType() . ' ' . $join->getTable()->getSelectFromSql();
                $sql .= ' ON (' . Query::quoteIdentifier($join->getLeftColumn()) . Criterion::EQUALS . Query::quoteIdentifier($join->getRightColumn());

                if ($join->hasAdditionalCriteria()) {
                    $sql_parts = [];

                    foreach ($join->getAdditionalCriteria() as $criteria) {
                        $criteria->setQuery($this->query);
                        $sql_parts[] = $criteria->getSql();
                        foreach ($criteria->getValues() as $value) {
                            $this->query->addValue($value);
                        }
                    }

                    $sql .= ' AND ' . join(' AND ', $sql_parts);
                }

                $sql .= ')';
            }

            return $sql;
        }
1034341
protected function sqlInsert(): string
    {
        $inserts = [];
        foreach ($this->datafields as $fieldname => $field) {
            $value = (array_key_exists($fieldname, $this->values)) ? $this->values[$fieldname] : null;
            $escapedFieldName = $this->dbal->sqlFieldEscape($field['name']);
            $inserts[$escapedFieldName] = $this->dbal->sqlQuote($value, $field['commontype'], true);
        }
        if (! count($inserts)) {
            throw new \LogicException('Recordset: Insert does not have any fields to insert');
        }
        return 'INSERT INTO ' . $this->dbal->sqlTableEscape($this->entity)
        . ' (' . implode(', ', array_keys($inserts)) . ')'
        . ' VALUES (' . implode(', ', $inserts) . ')'
        . ';';
    }
407787
protected function buildStatement(): string
    {
        $this->statementBuilder->prepareRawStatement($this->statement, $this->bindings);
        return $this->statementBuilder->getStatement();
    }
938361
protected function _buildSQL()
	{
		if( $this->_stmt !== null ) {
			return $this->_stmt;
		}

		$i = 1;
		foreach( $this->_parts as $part )
		{
			$this->_stmt .= $part;
			if( isset( $this->_binds[$i] ) ) {
				$this->_stmt .= $this->_binds[$i];
			}
			$i++;
		}

		return $this->_stmt;
	}
115330
public function dbgSelect() {
		$sql = $this->buildSQL();
		$params = $this->getParameters();

		return $this->replaceParams($sql, $params);
	}
1166493
public function buildCountStatement()
	{
		if( !$this->keys )
			throw new RuntimeException( 'No Columns defined.' );
		if( !$this->tables )
			throw new RuntimeException( 'No Tables defined.' );

		$tables		= array();
		$tables		= "\nFROM\n\t".implode( ",\n\t", $this->tables );
		$conditions	= "";
		$groupings	= "";
		$havings	= "";
		if( $this->conditions )
			$conditions	= "\nWHERE\n\t".implode( " AND\n\t", $this->conditions );
		if( $this->groupings )
			$groupings	= "\nGROUP BY\n\t".implode( ",\n\t", $this->groupings );
		if( $this->havings )
			$havings	= "\nHAVING\n\t".implode( ",\n\t", $this->havings );
		$column	= preg_replace( '/(.+)( AS .+)/i', '\\1', $this->keys[0] );
		$statement = "SELECT COUNT(".$column.") as rowcount".$tables.$conditions.$groupings.$havings;
		return $statement;
	}
693719
public function toSQL()
    {
        $this->res['sql'] = self::sortSqlArray($this->res['sql']);

        $res = $this->res['sql'][0] . ' ' . $this->getFlagsSQL() . ' ' . $this->res['select_expr'][0];
        $join_references_i = $join_conditions_i = 0;

        if (isset($this->res['where_conditions']) && $this->res['where_conditions'] && !in_array('WHERE', $this->res['sql'])) {
            trigger_error('Where conditions were set manually, but WHERE construction was not found in initial query. If you need to add conditions, WHERE construction should be in your query added manually.');
        }

        if (isset($this->res['order_conditions']) && $this->res['order_conditions'] && !in_array('ORDER BY', $this->res['sql'])) {
            trigger_error('Order conditions were set manually, but ORDER BY construction was not found in initial query. If you need to add conditions, ORDER BY construction should be in your query added manually.');
        }

        if (isset($this->res['group_conditions']) && $this->res['group_conditions'] && !in_array('GROUP BY', $this->res['sql'])) {
            trigger_error('Group conditions were set manually, but GROUP BY construction was not found in initial query. If you need to add conditions, GROUP BY construction should be in your query added manually.');
        }

        if (isset($this->res['having_conditions']) && $this->res['having_conditions'] && !in_array('HAVING', $this->res['sql'])) {
            trigger_error('Having conditions were set manually, but HAVING construction was not found in initial query. If you need to add conditions, HAVING construction should be in your query added manually.');
        }

        if (isset($this->res['limit_conditions']) && $this->res['limit_conditions'] && !in_array('LIMIT', $this->res['sql'])) {
            trigger_error('Limit conditions were set manually, but LIMIT construction was not found in initial query. If you need to add conditions, LIMIT construction should be in your query added manually.');
        }

        for ($i = 1, $so = count($this->res['sql']); $i < $so; $i++) {
            switch ($this->res['sql'][$i]) {
                default:
                    $res .= $this->res['sql'][$i] . ' ';
                    break;
                case 'FROM':
                    if (!isset($this->res['table_references'][0])) {
                        break;
                    }
                    $res .= ' FROM ' . $this->res['table_references'][0];
                    break;
                case 'JOIN':
                case 'LEFT JOIN':
                case 'RIGHT JOIN':
                case 'INNER JOIN':
                    $res .= ' ' . $this->res['sql'][$i] . ' ' . $this->res['join_references'][$join_references_i++] . ' ON ' . $this->res['join_conditions'][$join_conditions_i++]->toSQL();
                    break;
                case 'WHERE':
                    if (!isset($this->res['where_conditions'][0])) {
                        break;
                    }
                    $res .= ' WHERE ' . $this->res['where_conditions'][0]->toSQL();
                    break;
                case 'HAVING':
                    if (!isset($this->res['having_conditions'][0])) {
                        break;
                    }
                    $res .= ' HAVING ' . $this->res['having_conditions'][0];
                    break;
                case 'ORDER BY':
                    if (!isset($this->res['order_conditions'][0])) {
                        break;
                    }
                    $res .= ' ORDER BY ' . $this->res['order_conditions'][0];
                    break;
                case 'GROUP BY':
                    if (!isset($this->res['group_conditions'][0])) {
                        break;
                    }
                    $res .= ' GROUP BY ' . $this->res['group_conditions'][0];
                    break;
                case 'LIMIT':
                    if ($this->res['limit_conditions'][0]->isEmpty()) {
                        break;
                    }
                    $res .= ' LIMIT ' . $this->res['limit_conditions'][0];
                    break;
            }
        }
        return $res;
    }
1164412
public function buildSql()
    {
        $sqlDbMapContent = "# Sqlfile -> Database map\n";
        foreach ($this->getDatabases() as $datasource => $database) {
            $platform = $database->getPlatform();
            $filename = $database->getName() . '.sql';

            if ($this->getGeneratorConfig()->getBuildProperty('disableIdentifierQuoting')) {
                $platform->setIdentifierQuoting(false);
            }

            $ddl = $platform->getAddTablesDDL($database);

            $file = $this->getWorkingDirectory() . DIRECTORY_SEPARATOR . $filename;
            if (file_exists($file) && $ddl == file_get_contents($file)) {
                // Unchanged
            } else {
                file_put_contents($file, $ddl);
            }

            $sqlDbMapContent .= sprintf("%s=%s\n", $filename, $datasource);
        }

        file_put_contents($this->getSqlDbMapFilename(), $sqlDbMapContent);
    }