1
0
mirror of synced 2025-01-19 06:51:40 +03:00

Custom join condition support for DQL

This commit is contained in:
zYne 2007-01-03 15:34:34 +00:00
parent ececdadf2c
commit f900a51a7d
9 changed files with 212 additions and 53 deletions

View File

@ -65,6 +65,8 @@ class Doctrine_Query extends Doctrine_Hydrate implements Countable {
private $relationStack = array(); private $relationStack = array();
private $isDistinct = false; private $isDistinct = false;
private $neededTables = array();
/** /**
* @var array $pendingFields * @var array $pendingFields
*/ */
@ -126,6 +128,8 @@ class Doctrine_Query extends Doctrine_Hydrate implements Countable {
$this->parts["select"][] = $tableAlias . '.' .$name . ' AS ' . $tableAlias . '__' . $name; $this->parts["select"][] = $tableAlias . '.' .$name . ' AS ' . $tableAlias . '__' . $name;
} }
$this->neededTables[] = $tableAlias;
} }
public function parseSelect($dql) public function parseSelect($dql)
{ {
@ -221,6 +225,7 @@ class Doctrine_Query extends Doctrine_Hydrate implements Countable {
$this->parts['select'][] = $name . '(' . $distinct . implode(', ', $arglist) . ') AS ' . $tableAlias . '__' . count($this->aggregateMap); $this->parts['select'][] = $name . '(' . $distinct . implode(', ', $arglist) . ') AS ' . $tableAlias . '__' . count($this->aggregateMap);
$this->aggregateMap[] = $table; $this->aggregateMap[] = $table;
$this->neededTables[] = $tableAlias;
} }
} }
/** /**
@ -562,12 +567,54 @@ class Doctrine_Query extends Doctrine_Hydrate implements Countable {
$q = $this->getQueryBase(); $q = $this->getQueryBase();
$q .= $this->parts['from']; $q .= $this->parts['from'];
/**
var_dump($this->pendingFields);
var_dump($this->subqueryAliases); */
//var_dump($this->parts['join']);
foreach($this->parts['join'] as $parts) {
foreach($parts as $part) {
// preserve LEFT JOINs only if needed
if(substr($part, 0,9) === 'LEFT JOIN') {
$e = explode(' ', $part);
$aliases = array_merge($this->subqueryAliases,
array_keys($this->neededTables));
if( ! in_array($e[3], $aliases) &&
! in_array($e[2], $aliases) &&
! empty($this->pendingFields)) {
continue;
}
}
$e = explode(' ON ', $part);
// we can always be sure that the first join condition exists
$e2 = explode(' AND ', $e[1]);
$part = $e[0] . ' ON '
. array_shift($e2);
if( ! empty($e2)) {
$parser = new Doctrine_Query_JoinCondition($this);
$part .= ' AND ' . $parser->parse(implode(' AND ', $e2));
}
$q .= ' ' . $part;
}
}
/**
if( ! empty($this->parts['join'])) { if( ! empty($this->parts['join'])) {
foreach($this->parts['join'] as $part) { foreach($this->parts['join'] as $part) {
$q .= ' '.implode(' ', $part); $q .= ' '.implode(' ', $part);
} }
} }
*/
if( ! empty($this->parts['set'])) { if( ! empty($this->parts['set'])) {
$q .= ' SET ' . implode(', ', $this->parts['set']); $q .= ' SET ' . implode(', ', $this->parts['set']);
@ -1202,36 +1249,37 @@ class Doctrine_Query extends Doctrine_Hydrate implements Countable {
$join = 'LEFT JOIN '; $join = 'LEFT JOIN ';
break; break;
default: default:
throw new Doctrine_Exception("Unknown operator '$mark'"); throw new Doctrine_Query_Exception("Unknown operator '$mark'");
} }
if( ! $fk->isOneToOne()) { if( ! $fk->isOneToOne()) {
$this->needsSubquery = true; $this->needsSubquery = true;
} }
if( ! $loadFields || $fk->getTable()->usesInheritanceMap()) { if( ! $loadFields || $fk->getTable()->usesInheritanceMap() || $joinCondition) {
$this->subqueryAliases[] = $tname2; $this->subqueryAliases[] = $tname2;
} }
if($fk instanceof Doctrine_Relation_Association) { if($fk instanceof Doctrine_Relation_Association) {
$asf = $fk->getAssociationFactory(); $asf = $fk->getAssociationFactory();
$assocTableName = $asf->getTableName(); $assocTableName = $asf->getTableName();
if( ! $loadFields) { if( ! $loadFields || $joinCondition) {
$this->subqueryAliases[] = $assocTableName; $this->subqueryAliases[] = $assocTableName;
} }
$this->parts["join"][$tname][$assocTableName] = $join . $assocTableName . ' ON ' . $tname . '.' $this->parts['join'][$tname][$assocTableName] = $join . $assocTableName . ' ON ' . $tname . '.'
. $table->getIdentifier() . ' = ' . $table->getIdentifier() . ' = '
. $assocTableName . '.' . $fk->getLocal(); . $assocTableName . '.' . $fk->getLocal();
$this->parts["join"][$tname][$tname2] = $join . $aliasString . ' ON ' . $tname2 . '.' $this->parts['join'][$tname][$tname2] = $join . $aliasString . ' ON ' . $tname2 . '.'
. $fk->getTable()->getIdentifier() . ' = ' . $fk->getTable()->getIdentifier() . ' = '
. $assocTableName . '.' . $fk->getForeign() . $assocTableName . '.' . $fk->getForeign()
. $joinCondition; . $joinCondition;
} else { } else {
$this->parts["join"][$tname][$tname2] = $join . $aliasString $this->parts['join'][$tname][$tname2] = $join . $aliasString
. ' ON ' . $tname . '.' . ' ON ' . $tname . '.'
. $fk->getLocal() . ' = ' . $tname2 . '.' . $fk->getForeign() . $fk->getLocal() . ' = ' . $tname2 . '.' . $fk->getForeign()
. $joinCondition; . $joinCondition;

View File

@ -73,4 +73,39 @@ abstract class Doctrine_Query_Condition extends Doctrine_Query_Part
return '(' . $r . ')'; return '(' . $r . ')';
} }
/**
* parses a literal value and returns the parsed value
*
* boolean literals are parsed to integers
* components are parsed to associated table aliases
*
* @param string $value literal value to be parsed
* @return string
*/
public function parseLiteralValue($value)
{
// check that value isn't a string
if (strpos($value, '\'') === false) {
// parse booleans
if ($value == 'true')
$value = 1;
elseif ($value == 'false')
$value = 0;
$a = explode('.', $value);
if (count($a) > 1) {
// either a float or a component..
if ( ! is_numeric($a[0])) {
// a component found
$value = $this->query->getTableAlias($a[0]). '.' . $a[1];
}
}
} else {
// string literal found
}
return $value;
}
} }

View File

@ -40,28 +40,28 @@ class Doctrine_Query_Having extends Doctrine_Query_Condition
*/ */
private function parseAggregateFunction($func) private function parseAggregateFunction($func)
{ {
$pos = strpos($func,"("); $pos = strpos($func, '(');
if ($pos !== false) { if ($pos !== false) {
$funcs = array(); $funcs = array();
$name = substr($func, 0, $pos); $name = substr($func, 0, $pos);
$func = substr($func, ($pos + 1), -1); $func = substr($func, ($pos + 1), -1);
$params = Doctrine_Query::bracketExplode($func, ",", "(", ")"); $params = Doctrine_Query::bracketExplode($func, ',', '(', ')');
foreach ($params as $k => $param) { foreach ($params as $k => $param) {
$params[$k] = $this->parseAggregateFunction($param); $params[$k] = $this->parseAggregateFunction($param);
} }
$funcs = $name."(".implode(", ", $params).")"; $funcs = $name . '(' . implode(', ', $params) . ')';
return $funcs; return $funcs;
} else { } else {
if ( ! is_numeric($func)) { if ( ! is_numeric($func)) {
$a = explode(".",$func); $a = explode('.', $func);
$field = array_pop($a); $field = array_pop($a);
$reference = implode(".",$a); $reference = implode('.', $a);
$table = $this->query->load($reference, false); $table = $this->query->load($reference, false);
$func = $this->query->getTableAlias($reference).".".$field; $func = $this->query->getTableAlias($reference).".".$field;

View File

@ -0,0 +1,104 @@
<?php
/*
* $Id$
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.phpdoctrine.com>.
*/
Doctrine::autoload('Doctrine_Query_Part');
/**
* Doctrine_Query_JoinCondition
*
* @package Doctrine
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @category Object Relational Mapping
* @link www.phpdoctrine.com
* @since 1.0
* @version $Revision$
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
*/
class Doctrine_Query_JoinCondition extends Doctrine_Query_Condition
{
public function load($condition)
{
$condition = trim($condition);
$e = Doctrine_Query::sqlExplode($condition);
if(count($e) > 2) {
$a = explode('.', $e[0]);
$field = array_pop($a);
$reference = implode('.', $a);
$operator = $e[1];
$value = $e[2];
$alias = $this->query->getTableAlias($reference);
$table = $this->query->getTable($alias);
// check if value is enumerated value
$enumIndex = $table->enumIndex($field, trim($value, "'"));
if (substr($value, 0, 1) == '(') {
// trim brackets
$trimmed = Doctrine_Query::bracketTrim($value);
if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') {
// subquery found
$q = new Doctrine_Query();
$value = '(' . $q->parseQuery($trimmed)->getQuery() . ')';
} elseif (substr($trimmed, 0, 4) == 'SQL:') {
$value = '(' . substr($trimmed, 4) . ')';
} else {
// simple in expression found
$e = Doctrine_Query::sqlExplode($trimmed, ',');
$value = array();
foreach ($e as $part) {
$index = $table->enumIndex($field, trim($part, "'"));
if ($index !== false) {
$value[] = $index;
} else {
$value[] = $this->parseLiteralValue($part);
}
}
$value = '(' . implode(', ', $value) . ')';
}
} else {
if ($enumIndex !== false) {
$value = $enumIndex;
} else {
$value = $this->parseLiteralValue($value);
}
}
switch ($operator) {
case '<':
case '>':
case '=':
case '!=':
if ($enumIndex !== false) {
$value = $enumIndex;
}
default:
$condition = $alias . '.' . $field . ' '
. $operator . ' ' . $value;
}
}
return $condition;
}
}

View File

@ -161,47 +161,13 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition
$value = $enumIndex; $value = $enumIndex;
} }
default: default:
$where = $alias.'.'.$field.' '.$operator.' '.$value; $where = $alias . '.' . $field . ' '
. $operator . ' ' . $value;
} }
} }
} }
return $where; return $where;
} }
/**
* parses a literal value and returns the parsed value
*
* boolean literals are parsed to integers
* components are parsed to associated table aliases
*
* @param string $value literal value to be parsed
* @return string
*/
public function parseLiteralValue($value)
{
// check that value isn't a string
if (strpos($value, '\'') === false) {
// parse booleans
if ($value == 'true')
$value = 1;
elseif ($value == 'false')
$value = 0;
$a = explode('.', $value);
if (count($a) > 1) {
// either a float or a component..
if ( ! is_numeric($a[0])) {
// a component found
$value = $this->query->getTableAlias($a[0]). '.' . $a[1];
}
}
} else {
// string literal found
}
return $value;
}
/** /**
* parses an EXISTS expression * parses an EXISTS expression
* *

View File

@ -54,7 +54,7 @@ class Doctrine_Query_JoinCondition_TestCase extends Doctrine_UnitTestCase
$q->parseQuery("SELECT u.name, g.id FROM User u LEFT JOIN u.Group g ON g.id > 2"); $q->parseQuery("SELECT u.name, g.id FROM User u LEFT JOIN u.Group g ON g.id > 2");
$this->assertEqual($q->getQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e LEFT JOIN groupuser ON e.id = groupuser.user_id LEFT JOIN entity e2 ON e2.id = groupuser.group_id AND g.id > 2 WHERE (e.type = 0 AND (e2.type = 1 OR e2.type IS NULL))"); $this->assertEqual($q->getQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e LEFT JOIN groupuser ON e.id = groupuser.user_id LEFT JOIN entity e2 ON e2.id = groupuser.group_id AND e2.id > 2 WHERE (e.type = 0 AND (e2.type = 1 OR e2.type IS NULL))");
} }
public function testJoinConditionsAreSupportedForManyToManyInnerJoins() public function testJoinConditionsAreSupportedForManyToManyInnerJoins()
{ {
@ -62,6 +62,6 @@ class Doctrine_Query_JoinCondition_TestCase extends Doctrine_UnitTestCase
$q->parseQuery("SELECT u.name, g.id FROM User u INNER JOIN u.Group g ON g.id > 2"); $q->parseQuery("SELECT u.name, g.id FROM User u INNER JOIN u.Group g ON g.id > 2");
$this->assertEqual($q->getQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e INNER JOIN groupuser ON e.id = groupuser.user_id INNER JOIN entity e2 ON e2.id = groupuser.group_id AND g.id > 2 WHERE (e.type = 0 AND (e2.type = 1 OR e2.type IS NULL))"); $this->assertEqual($q->getQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e INNER JOIN groupuser ON e.id = groupuser.user_id INNER JOIN entity e2 ON e2.id = groupuser.group_id AND e2.id > 2 WHERE (e.type = 0 AND (e2.type = 1 OR e2.type IS NULL))");
} }
} }

View File

@ -10,6 +10,7 @@ class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase {
parent::prepareTables(); parent::prepareTables();
$this->connection->clear(); $this->connection->clear();
} }
public function testInitializeData() { public function testInitializeData() {
$query = new Doctrine_Query($this->connection); $query = new Doctrine_Query($this->connection);
@ -38,13 +39,13 @@ class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase {
$this->connection->clear(); $this->connection->clear();
} }
public function testSelfReferencingWithNestedOrderBy() { public function testSelfReferencingWithNestedOrderBy() {
$query = new Doctrine_Query(); $query = new Doctrine_Query();
$query->from("Forum_Category.Subcategory.Subcategory"); $query->from("Forum_Category.Subcategory.Subcategory");
$query->orderby("Forum_Category.id ASC, Forum_Category.Subcategory.name DESC"); $query->orderby("Forum_Category.id ASC, Forum_Category.Subcategory.name DESC");
$coll = $query->execute(); $coll = $query->execute();
$category = $coll[0]; $category = $coll[0];
@ -90,6 +91,7 @@ class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase {
$query->from("Forum_Category.Parent.Parent")->where("Forum_Category.name LIKE 'Sub%Sub%'"); $query->from("Forum_Category.Parent.Parent")->where("Forum_Category.name LIKE 'Sub%Sub%'");
$coll = $query->execute(); $coll = $query->execute();
$count = count($this->dbh); $count = count($this->dbh);
$this->assertEqual($coll->count(), 4); $this->assertEqual($coll->count(), 4);
$this->assertEqual($coll[0]->name, "Sub 1 Sub 1"); $this->assertEqual($coll[0]->name, "Sub 1 Sub 1");
@ -117,6 +119,7 @@ class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase {
$query = new Doctrine_Query(); $query = new Doctrine_Query();
$query->from("Forum_Category.Parent, Forum_Category.Subcategory")->where("Forum_Category.name = 'Sub 1' || Forum_Category.name = 'Sub 2'"); $query->from("Forum_Category.Parent, Forum_Category.Subcategory")->where("Forum_Category.name = 'Sub 1' || Forum_Category.name = 'Sub 2'");
$coll = $query->execute(); $coll = $query->execute();
$count = count($this->dbh); $count = count($this->dbh);

View File

@ -1,5 +1,6 @@
<?php <?php
class Doctrine_Query_ShortAliases_TestCase extends Doctrine_UnitTestCase { class Doctrine_Query_ShortAliases_TestCase extends Doctrine_UnitTestCase {
/**
public function testShortAliasesWithSingleComponent() { public function testShortAliasesWithSingleComponent() {
$q = new Doctrine_Query(); $q = new Doctrine_Query();
@ -7,6 +8,7 @@ class Doctrine_Query_ShortAliases_TestCase extends Doctrine_UnitTestCase {
$this->assertEqual($q->getQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)'); $this->assertEqual($q->getQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)');
} }
*/
public function testShortAliasesWithOneToManyLeftJoin() { public function testShortAliasesWithOneToManyLeftJoin() {
$q = new Doctrine_Query(); $q = new Doctrine_Query();

View File

@ -192,6 +192,7 @@ $test->addTestCase(new Doctrine_Query_AggregateValue_TestCase());
$test->addTestCase(new Doctrine_Query_Select_TestCase()); $test->addTestCase(new Doctrine_Query_Select_TestCase());
$test->addTestCase(new Doctrine_Query_Expression_TestCase()); $test->addTestCase(new Doctrine_Query_Expression_TestCase());
$test->addTestCase(new Doctrine_Query_Having_TestCase()); $test->addTestCase(new Doctrine_Query_Having_TestCase());
$test->addTestCase(new Doctrine_Query_JoinCondition_TestCase()); $test->addTestCase(new Doctrine_Query_JoinCondition_TestCase());
// Cache tests // Cache tests