Skip to content

Commit

Permalink
Sub-select in SELECT clause (without aliases and smart join)
Browse files Browse the repository at this point in the history
  • Loading branch information
jkufner committed Apr 19, 2013
1 parent a814e73 commit 82be210
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
16 changes: 15 additions & 1 deletion FluentPDO/BaseQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,16 @@ protected function buildQuery() {
foreach ($this->clauses as $clause => $separator) {
if ($this->clauseNotEmpty($clause)) {
if (is_string($separator)) {
$query .= " $clause " . implode($separator, $this->statements[$clause]);
$t = $this;
$query .= " $clause " . implode($separator, array_map(function ($x) use ($t, $clause) {
if ($x instanceof SelectQuery) {
$x->disableSmartJoin(); // TODO: pass parent table aliases.
$t->parameters[$clause] = array_merge($t->parameters[$clause], $x->getParameters());
return '('.$x->getQuery().')';
} else {
return $x;
}
}, $this->statements[$clause]));
} elseif ($separator === null) {
$query .= " $clause " . $this->statements[$clause];
} elseif (is_callable($separator)) {
Expand Down Expand Up @@ -239,6 +248,11 @@ protected function quote($value) {
if (is_int($value) || $value instanceof FluentLiteral) { // number or SQL code - for example "NOW()"
return (string) $value;
}
if ($value instanceof SelectQuery) {
$value->disableSmartJoin(); // TODO: pass parent table aliases.
$this->parameters = array_merge($this->parameters, $value->getParameters());
return '('.($value->getQuery()).')';
}
return $this->fpdo->getPdo()->quote($value);
}

Expand Down
2 changes: 1 addition & 1 deletion FluentPDO/CommonQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ protected function buildQuery() {
* @return string rewrited $statement (e.g. tab1.tab2:col => tab2.col)
*/
private function createUndefinedJoins($statement) {
if (!$this->isSmartJoinEnabled) {
if (!$this->isSmartJoinEnabled || $statement instanceof SelectQuery) {
return $statement;
}

Expand Down
31 changes: 31 additions & 0 deletions tests/53-subselect.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
--TEST--
Simple sub-select
--FILE--
<?php
include_once dirname(__FILE__) . "/connect.inc.php";
/* @var $fpdo FluentPDO */

$subquery = $fpdo->from('article')->select(null)->select('COUNT(id)')->where('user_id', new FluentLiteral('user.id'));

$query = $fpdo->from('user')->select($subquery)->where('id', 1);

echo $query->getQuery() . "\n\n";
print_r($query->getParameters()) . "\n";

?>
--EXPECTF--
SELECT user.*, (SELECT COUNT(id)
FROM article
WHERE user_id = ?)
FROM user
WHERE id = ?

Array
(
[0] => FluentLiteral Object
(
[value:protected] => user.id
)

[1] => 1
)

0 comments on commit 82be210

Please sign in to comment.