Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing subqueries in FROM section #4476

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 141 additions & 28 deletions system/Database/BaseBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -251,22 +251,26 @@ class BaseBuilder
/**
* Constructor
*
* @param string|array $tableName
* @param ConnectionInterface $db
* @param array $options
* @param Closure|BaseBuilder|SqlExpression|array|string|null $tableName
* @param ConnectionInterface $db
* @param array $options
* @throws DatabaseException
*/
public function __construct($tableName, ConnectionInterface &$db, array $options = null)
{
if (empty($tableName))
if (empty($tableName) && (is_array($tableName) || is_string($tableName)))
{
throw new DatabaseException('A table must be specified when creating a new Query Builder.');
}

/** @var BaseConnection $db */
$this->db = $db;

$this->tableName = $tableName;
if (is_string($tableName))
{
$this->tableName = $tableName;
}

$this->from($tableName);

if (! empty($options))
Expand Down Expand Up @@ -586,8 +590,8 @@ public function distinct(bool $val = true)
*
* Generates the FROM portion of the query
*
* @param mixed $from can be a string or array
* @param boolean $overwrite Should we remove the first table existing?
* @param Closure|BaseBuilder|SqlExpression|array|string|null $from Table
* @param boolean $overwrite Should we remove the first table existing?
*
* @return $this
*/
Expand All @@ -599,6 +603,11 @@ public function from($from, bool $overwrite = false)
$this->db->setAliasedTables([]);
}

if ($this->isSubquery($from))
{
return $this->fromSub($from);
}

foreach ((array) $from as $val)
{
if (strpos($val, ',') !== false)
Expand Down Expand Up @@ -626,6 +635,26 @@ public function from($from, bool $overwrite = false)
return $this;
}

/**
* Adding subquery to FROM section
*
* @param Closure|BaseBuilder|SqlExpression $from Table
*
* @return $this
*/
protected function fromSub($from): self
{
$from = $this->subqueryProcessing($from);

$from = $this->parenthesesWrapper($from);

$this->trackAliases($from);

$this->QBFrom[] = $from;

return $this;
}

//--------------------------------------------------------------------

/**
Expand Down Expand Up @@ -821,10 +850,10 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type
$k .= " $op";
}

if ($v instanceof Closure)
if ($this->isSubquery($v))
{
$builder = $this->cleanClone();
$v = '(' . str_replace("\n", ' ', $v($builder)->getCompiledSelect()) . ')';
$query = $this->subqueryProcessing($v);
$v = $this->parenthesesWrapper(str_replace("\n", ' ', $query));
}
else
{
Expand Down Expand Up @@ -934,9 +963,9 @@ public function orWhereNotIn(string $key = null, $values = null, bool $escape =
* Generates a HAVING field IN('item', 'item') SQL query,
* joined with 'AND' if appropriate.
*
* @param string $key The field to search
* @param array|string|Closure $values The values searched on, or anonymous function with subquery
* @param boolean $escape
* @param string $key The field to search
* @param Closure|BaseBuilder|SqlExpression|array|string|null $values The values searched on, or anonymous function with subquery
* @param boolean $escape
*
* @return $this
*/
Expand Down Expand Up @@ -1012,15 +1041,15 @@ public function orHavingNotIn(string $key = null, $values = null, bool $escape =
* @used-by whereNotIn()
* @used-by orWhereNotIn()
*
* @param string $key The field to search
* @param array|Closure|null $values The values searched on, or anonymous function with subquery
* @param boolean $not If the statement would be IN or NOT IN
* @param string $type
* @param boolean $escape
* @param string $clause (Internal use only)
* @throws InvalidArgumentException
*
* @param string $key The field to search
* @param Closure|BaseBuilder|SqlExpression|array|null $values The values searched on, or anonymous function with subquery
* @param boolean $not If the statement would be IN or NOT IN
* @param string $type
* @param boolean $escape
* @param string $clause (Internal use only)
* @return $this
*@throws InvalidArgumentException
*
*/
protected function _whereIn(string $key = null, $values = null, bool $not = false, string $type = 'AND ', bool $escape = null, string $clause = 'QBWhere')
{
Expand All @@ -1035,7 +1064,7 @@ protected function _whereIn(string $key = null, $values = null, bool $not = fals
// @codeCoverageIgnoreEnd
}

if ($values === null || (! is_array($values) && ! ($values instanceof Closure)))
if ($values === null || (! is_array($values) && ! $this->isSubquery($values)))
{
if (CI_DEBUG)
{
Expand All @@ -1060,10 +1089,10 @@ protected function _whereIn(string $key = null, $values = null, bool $not = fals

$not = ($not) ? ' NOT' : '';

if ($values instanceof Closure)
if ($this->isSubquery($values))
{
$builder = $this->cleanClone();
$ok = str_replace("\n", ' ', $values($builder)->getCompiledSelect());
$query = $this->subqueryProcessing($values);
$ok = $this->parenthesesWrapper(str_replace("\n", ' ', $query));
}
else
{
Expand All @@ -1074,7 +1103,7 @@ protected function _whereIn(string $key = null, $values = null, bool $not = fals
$prefix = empty($this->$clause) ? $this->groupGetType('') : $this->groupGetType($type);

$whereIn = [
'condition' => $prefix . $key . $not . ($values instanceof Closure ? " IN ($ok)" : " IN :{$ok}:"),
'condition' => $prefix . $key . $not . ($this->isSubquery($values) ? " IN $ok" : " IN :{$ok}:"),
'escape' => false,
];

Expand Down Expand Up @@ -3394,9 +3423,9 @@ protected function resetSelect()
}

// Reset QBFrom part
if (! empty($this->QBFrom))
if (! empty($this->QBFrom) && is_string($this->tableName))
{
$this->from(array_shift($this->QBFrom), true);
$this->from($this->tableName, true);
}
}

Expand Down Expand Up @@ -3517,11 +3546,95 @@ protected function setBind(string $key, $value = null, bool $escape = true): str
* Returns a clone of a Base Builder with reset query builder values.
*
* @return $this
*
* @deprecated Use instead $this->db->table(null) or new static(null, $this->db)
*/
protected function cleanClone()
{
return (clone $this)->from([], true)->resetQuery();
}

//--------------------------------------------------------------------

/**
* Checks a variable for a subquery
*
* @param mixed $value Expect subquery
*
* @return boolean
*/
protected function isSubquery($value): bool
{
return $value instanceof Closure
|| $value instanceof BaseBuilder
|| $value instanceof SqlExpression;
}

/**
* Subquery closure processing
*
* @param Closure|BaseBuilder $subquery Subquery closure
*
* @return string
* @throws DatabaseException
*/
protected function subqueryProcessing($subquery): string
{
if (! $this->isSubquery($subquery))
{
throw new DatabaseException('Expected subquery');
}

return $subquery instanceof SqlExpression
? $subquery->getValue()
: $this->getSubqueryBuilder($subquery)->getCompiledSelect();
}

/**
* Subquery builder
*
* @param Closure|BaseBuilder $subquery Subquery
*
* @return BaseBuilder
* @throws DatabaseException
*/
protected function getSubqueryBuilder($subquery): self
{
if (! ($subquery instanceof Closure) && ! ($subquery instanceof BaseBuilder))
{
throw new DatabaseException(
'Closure or instance of BaseBuilder class expected, ' . gettype($subquery) . ' is given.'
);
}

if ($subquery instanceof Closure)
{
$subquery($builder = $this->db->table(null));

$subquery = $builder;
}

if (spl_object_hash($subquery) === spl_object_hash($this))
{
throw new DatabaseException(
'The subquery does not have to be an instance of the parent Base Builder class.'
);
}

return $subquery;
}

/**
* Wraps an expression in parentheses
*
* @param string $expression Expression
*
* @return string
*/
protected function parenthesesWrapper(string $expression): string
{
$expression = trim($expression);
return strpos($expression, '(') === 0 ? $expression : '(' . $expression . ')';
}

}
19 changes: 13 additions & 6 deletions system/Database/BaseConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -954,23 +954,30 @@ abstract protected function _transRollback(): bool;
/**
* Returns an instance of the query builder for this connection.
*
* @param string|array $tableName
* @param Closure|BaseBuilder|SqlExpression|array|string|null $tableName Table
*
* @return BaseBuilder
* @throws DatabaseException
*/
public function table($tableName)
{
if (empty($tableName))
{
throw new DatabaseException('You must set the database table to be used with your query.');
}

$className = str_replace('Connection', 'Builder', get_class($this));

return new $className($tableName, $this);
}

/**
* Returns a wrapper for a raw SQL subquery
*
* @param string $statement SQL statement
*
* @return SqlExpression
*/
public function raw(string $statement): SqlExpression
{
return new SqlExpression($statement);
}

//--------------------------------------------------------------------

/**
Expand Down
13 changes: 9 additions & 4 deletions system/Database/SQLSRV/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

namespace CodeIgniter\Database\SQLSRV;

use Closure;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
Expand Down Expand Up @@ -301,6 +300,12 @@ private function getFullName(string $table): string
{
$alias = '';

// subquery filter
if (strpos($table, '(') !== false)
{
return $table;
}

if (strpos($table, ' ') !== false)
{
$alias = explode(' ', $table);
Expand Down Expand Up @@ -712,10 +717,10 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type
$k .= " $op";
}

if ($v instanceof Closure)
if ($this->isSubquery($v))
{
$builder = $this->cleanClone();
$v = '(' . str_replace("\n", ' ', $v($builder)->getCompiledSelect()) . ')';
$query = $this->subqueryProcessing($v);
$v = $this->parenthesesWrapper(str_replace("\n", ' ', $query));
}
else
{
Expand Down
Loading