From 82be210a915f7ba085d9d7fe9894d6e3da4a8a5d Mon Sep 17 00:00:00 2001 From: Josef Kufner Date: Fri, 19 Apr 2013 10:21:00 +0200 Subject: [PATCH] Sub-select in SELECT clause (without aliases and smart join) --- FluentPDO/BaseQuery.php | 16 +++++++++++++++- FluentPDO/CommonQuery.php | 2 +- tests/53-subselect.phpt | 31 +++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 tests/53-subselect.phpt diff --git a/FluentPDO/BaseQuery.php b/FluentPDO/BaseQuery.php index d595259..b41aa29 100644 --- a/FluentPDO/BaseQuery.php +++ b/FluentPDO/BaseQuery.php @@ -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)) { @@ -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); } diff --git a/FluentPDO/CommonQuery.php b/FluentPDO/CommonQuery.php index e747aaa..0441b55 100644 --- a/FluentPDO/CommonQuery.php +++ b/FluentPDO/CommonQuery.php @@ -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; } diff --git a/tests/53-subselect.phpt b/tests/53-subselect.phpt new file mode 100644 index 0000000..1a89e9b --- /dev/null +++ b/tests/53-subselect.phpt @@ -0,0 +1,31 @@ +--TEST-- +Simple sub-select +--FILE-- +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 +)