Commit 4d13925b authored by romanb's avatar romanb

[2.0] Some hydration and DQL parser work.

parent 96ef7eca
......@@ -96,16 +96,19 @@ class Collection implements Countable, IteratorAggregate, ArrayAccess
}
/**
* Removes an element with a specific key from the collection.
* Removes an element with a specific key/index from the collection.
*
* @param mixed $key
* @return mixed
*/
public function remove($key)
{
$removed = $this->_elements[$key];
unset($this->_elements[$key]);
return $removed;
if (isset($this->_elements[$key])) {
$removed = $this->_elements[$key];
unset($this->_elements[$key]);
return $removed;
}
return null;
}
/**
......
......@@ -329,7 +329,7 @@ class OraclePlatform extends AbstractPlatform
*/
public function getSetTransactionIsolationSql($level)
{
return 'ALTER SESSION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSql($level);
return 'SET TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSql($level);
}
/**
......@@ -342,8 +342,8 @@ class OraclePlatform extends AbstractPlatform
{
switch ($level) {
case Doctrine_DBAL_Connection::TRANSACTION_READ_UNCOMMITTED:
return 'READ COMMITTED';
case Doctrine_DBAL_Connection::TRANSACTION_READ_COMMITTED:
return 'READ COMMITTED';
case Doctrine_DBAL_Connection::TRANSACTION_REPEATABLE_READ:
case Doctrine_DBAL_Connection::TRANSACTION_SERIALIZABLE:
return 'SERIALIZABLE';
......
......@@ -58,13 +58,11 @@ abstract class AbstractQuery
/**
* @var array $params Parameters of this query.
* @see Query::free that initializes this property
*/
protected $_params = array();
/**
* @var array $_enumParams Array containing the keys of the parameters that should be enumerated.
* @see Query::free that initializes this property
*/
protected $_enumParams = array();
......@@ -117,7 +115,6 @@ abstract class AbstractQuery
public function __construct(EntityManager $entityManager)
{
$this->_em = $entityManager;
$this->free();
}
/**
......@@ -207,8 +204,8 @@ abstract class AbstractQuery
/**
* Sets a query parameter.
*
* @param string|integer $key
* @param mixed $value
* @param string|integer $key The parameter position or name.
* @param mixed $value The parameter value.
*/
public function setParameter($key, $value)
{
......@@ -319,7 +316,7 @@ abstract class AbstractQuery
}
/**
* Defines the processing mode to be used during hydration process.
* Defines the processing mode to be used during hydration.
*
* @param integer $hydrationMode Doctrine processing mode to be used during hydration process.
* One of the Query::HYDRATE_* constants.
......@@ -521,7 +518,7 @@ abstract class AbstractQuery
/**
* Executes the query and returns a reference to the resulting Statement object.
*
* @param <type> $params
* @param array $params
*/
abstract protected function _doExecute(array $params);
}
......@@ -165,7 +165,7 @@ abstract class AbstractHydrator
* the values applied.
*
* @return array An array with all the fields (name => value) of the data row,
* grouped by their component (alias).
* grouped by their component alias.
*/
protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents)
{
......@@ -177,7 +177,7 @@ abstract class AbstractHydrator
if (isset($this->_rsm->ignoredColumns[$key])) {
$cache[$key] = false;
} else if (isset($this->_rsm->scalarMappings[$key])) {
$cache[$key]['fieldName'] = $this->_rsm->getScalarAlias($key);
$cache[$key]['fieldName'] = $this->_rsm->scalarMappings[$key];
$cache[$key]['isScalar'] = true;
} else if (isset($this->_rsm->fieldMappings[$key])) {
$classMetadata = $this->_rsm->getOwningClass($key);
......@@ -283,8 +283,7 @@ abstract class AbstractHydrator
*/
protected function _getCustomIndexField($alias)
{
return isset($this->_rsm->indexByMap[$alias]) ?
$this->_rsm->indexByMap[$alias] : null;
return isset($this->_rsm->indexByMap[$alias]) ? $this->_rsm->indexByMap[$alias] : null;
}
/**
......
......@@ -107,7 +107,7 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
/**
* The class descriptor of the owning entity.
*/
private $_ownerClass;
private $_typeClass;
/**
* Whether the collection is dirty and needs to be synchronized with the database
......@@ -117,6 +117,8 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
*/
private $_isDirty = false;
private $_initialized = false;
/**
* Creates a new persistent collection.
*/
......@@ -125,7 +127,7 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
parent::__construct($data);
$this->_type = $class->name;
$this->_em = $em;
$this->_ownerClass = $class;
$this->_typeClass = $class;
}
/**
......@@ -137,7 +139,6 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
public function setKeyField($fieldName)
{
$this->_keyField = $fieldName;
return $this;
}
/**
......@@ -162,14 +163,14 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
$this->_owner = $entity;
$this->_association = $assoc;
if ($assoc->isInverseSide()) {
// for sure bi-directional
$this->_backRefFieldName = $assoc->getMappedByFieldName();
// For sure bi-directional
$this->_backRefFieldName = $assoc->mappedByFieldName;
} else {
$targetClass = $this->_em->getClassMetadata($assoc->getTargetEntityName());
if ($targetClass->hasInverseAssociationMapping($assoc->getSourceFieldName())) {
// bi-directional
$this->_backRefFieldName = $targetClass->inverseMappings[
$assoc->getSourceFieldName()]->getSourceFieldName();
$targetClass = $this->_em->getClassMetadata($assoc->targetEntityName);
if (isset($targetClass->inverseMappings[$assoc->sourceFieldName])) {
// Bi-directional
$this->_backRefFieldName = $targetClass->inverseMappings[$assoc->sourceFieldName]
->sourceFieldName;
}
}
}
......@@ -192,7 +193,7 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
*/
public function getOwnerClass()
{
return $this->_ownerClass;
return $this->_typeClass;
}
/**
......@@ -204,14 +205,14 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
*/
public function remove($key)
{
//TODO: Register collection as dirty with the UoW if necessary
//$this->_em->getUnitOfWork()->scheduleCollectionUpdate($this);
//TODO: delete entity if shouldDeleteOrphans
/*if ($this->_association->isOneToMany() && $this->_association->shouldDeleteOrphans()) {
$this->_em->delete($removed);
}*/
$removed = parent::remove($key);
$this->_changed();
if ($removed) {
$this->_changed();
}
return $removed;
}
......@@ -226,8 +227,9 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
public function set($key, $value)
{
parent::set($key, $value);
//TODO: Register collection as dirty with the UoW if necessary
if ( ! $this->_hydrationFlag) $this->_changed();
if ( ! $this->_hydrationFlag) {
$this->_changed();
}
}
/**
......@@ -240,18 +242,17 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
*/
public function add($value)
{
$result = parent::add($value);
if ( ! $result) return $result; // EARLY EXIT
parent::add($value);
if ($this->_hydrationFlag) {
if ($this->_backRefFieldName) {
// Set back reference to owner
if ($this->_association->isOneToMany()) {
$this->_ownerClass->getReflectionProperty($this->_backRefFieldName)
$this->_typeClass->getReflectionProperty($this->_backRefFieldName)
->setValue($value, $this->_owner);
} else {
// ManyToMany
$this->_ownerClass->getReflectionProperty($this->_backRefFieldName)
$this->_typeClass->getReflectionProperty($this->_backRefFieldName)
->getValue($value)->add($this->_owner);
}
}
......@@ -277,19 +278,39 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
//$this->_changed();
}
/**
* Checks whether an element is contained in the collection.
* This is an O(n) operation.
*/
public function contains($element)
{
//TODO: Probably need to hit the database here...?
/*if ( ! $this->_initialized) {
return $this->_checkElementExistence($element);
if ( ! $this->_initialized) {
//TODO: Probably need to hit the database here...?
//return $this->_checkElementExistence($element);
}
return parent::contains($element);*/
return parent::contains($element);
}
/**
* @override
*/
public function count()
{
if ( ! $this->_initialized) {
//TODO: Initialize
}
return parent::count();
}
private function _checkElementExistence($element)
{
}
private function _initialize()
{
}
/**
......@@ -359,10 +380,7 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
*/
private function _compareRecords($a, $b)
{
if ($a === $b) {
return 0;
}
return 1;
return $a === $b ? 0 : 1;
}
/**
......@@ -394,11 +412,6 @@ final class PersistentCollection extends \Doctrine\Common\Collections\Collection
private function _changed()
{
$this->_isDirty = true;
/*if ( ! $this->_em->getUnitOfWork()->isCollectionScheduledForUpdate($this)) {
//var_dump(get_class($this->_snapshot[0]));
//echo "NOT!";
//$this->_em->getUnitOfWork()->scheduleCollectionUpdate($this);
}*/
}
/**
......
This diff is collapsed.
......@@ -889,15 +889,19 @@ class Parser
$identificationVariable = $this->_IdentificationVariable();
if ( ! isset($this->_queryComponents[$identificationVariable])) {
$this->syntaxError("Identification variable.");
$this->syntaxError("Identification variable '$identificationVariable' was not declared.");
}
$qComp = $this->_queryComponents[$identificationVariable];
$parts[] = $identificationVariable;
$class = $qComp['metadata'];
if ( ! $this->_lexer->isNextToken('.')) {
$this->syntaxError();
if ($class->isIdentifierComposite) {
$this->syntaxError();
}
$parts[] = $class->identifier[0];
}
while ($this->_lexer->isNextToken('.')) {
......@@ -917,6 +921,11 @@ class Parser
$parts[] = $part;
}
/*$lastPart = $parts[count($parts) - 1];
if ($class->hasAssociation($lastPart)) {
}*/
$pathExpr = new AST\StateFieldPathExpression($parts);
if ($assocSeen) {
......
......@@ -130,7 +130,7 @@ class SqlWalker
}
//if ($this->_query->getHydrationMode() == \Doctrine\ORM\Query::HYDRATE_OBJECT) {
if ($class->isInheritanceTypeSingleTable() || $class->isInheritanceTypeJoined()) {
$tblAlias = $this->getSqlTableAlias($class->getTableName());
$tblAlias = $this->getSqlTableAlias($class->getTableName() . $dqlAlias);
$discrColumn = $class->discriminatorColumn;
$columnAlias = $this->getSqlColumnAlias($discrColumn['name']);
$sql .= ", $tblAlias." . $discrColumn['name'] . ' AS ' . $columnAlias;
......@@ -158,7 +158,7 @@ class SqlWalker
$this->_currentRootAlias = $dqlAlias;
$sql .= $rangeDecl->getClassMetadata()->getTableName() . ' '
. $this->getSqlTableAlias($rangeDecl->getClassMetadata()->getTableName());
. $this->getSqlTableAlias($rangeDecl->getClassMetadata()->getTableName() . $dqlAlias);
foreach ($firstIdentificationVarDecl->getJoinVariableDeclarations() as $joinVarDecl) {
$sql .= $this->walkJoinVariableDeclaration($joinVarDecl);
......@@ -204,7 +204,7 @@ class SqlWalker
$parts = $pathExpr->getParts();
$qComp = $this->_queryComponents[$parts[0]];
$columnName = $qComp['metadata']->getColumnName($parts[1]);
$sql = $this->getSqlTableAlias($qComp['metadata']->getTableName()) . '.' . $columnName;
$sql = $this->getSqlTableAlias($qComp['metadata']->getTableName() . $parts[0]) . '.' . $columnName;
$sql .= $orderByItem->isAsc() ? ' ASC' : ' DESC';
return $sql;
}
......@@ -244,8 +244,8 @@ class SqlWalker
$targetQComp = $this->_queryComponents[$joinedDqlAlias];
$targetTableName = $targetQComp['metadata']->getTableName();
$targetTableAlias = $this->getSqlTableAlias($targetTableName);
$sourceTableAlias = $this->getSqlTableAlias($sourceQComp['metadata']->getTableName());
$targetTableAlias = $this->getSqlTableAlias($targetTableName . $joinedDqlAlias);
$sourceTableAlias = $this->getSqlTableAlias($sourceQComp['metadata']->getTableName() . $joinAssocPathExpr->getIdentificationVariable());
// Ensure we got the owning side, since it has all mapping info
if ( ! $targetQComp['relation']->isOwningSide()) {
......@@ -346,7 +346,7 @@ class SqlWalker
}
}
$sqlTableAlias = $this->getSqlTableAlias($class->getTableName());
$sqlTableAlias = $this->getSqlTableAlias($class->getTableName() . $dqlAlias);
$columnName = $class->getColumnName($fieldName);
$columnAlias = $this->getSqlColumnAlias($columnName);
$sql .= $sqlTableAlias . '.' . $columnName . ' AS ' . $columnAlias;
......@@ -389,7 +389,7 @@ class SqlWalker
$this->_selectedClasses[$dqlAlias] = $class;
}
$sqlTableAlias = $this->getSqlTableAlias($class->getTableName());
$sqlTableAlias = $this->getSqlTableAlias($class->getTableName() . $dqlAlias);
// Gather all fields
$fieldMappings = $class->fieldMappings;
......@@ -464,7 +464,7 @@ class SqlWalker
$firstIdentificationVarDecl = $identificationVarDecls[0];
$rangeDecl = $firstIdentificationVarDecl->getRangeVariableDeclaration();
$sql .= $rangeDecl->getClassMetadata()->getTableName() . ' '
. $this->getSqlTableAlias($rangeDecl->getClassMetadata()->getTableName());
. $this->getSqlTableAlias($rangeDecl->getClassMetadata()->getTableName() . $rangeDecl->getAliasIdentificationVariable());
foreach ($firstIdentificationVarDecl->getJoinVariableDeclarations() as $joinVarDecl) {
$sql .= $this->walkJoinVariableDeclaration($joinVarDecl);
......@@ -510,8 +510,12 @@ class SqlWalker
}
$sql .= $this->walkAggregateExpression($expr) . ' AS dctrn__' . $alias;
} else {
// $expr is IdentificationVariable
//...
// IdentificationVariable
// FIXME: Composite key support, or select all columns? Does that make
// in a subquery?
$class = $this->_queryComponents[$expr]['metadata'];
$sql .= ' ' . $this->getSqlTableAlias($class->getTableName() . $expr) . '.';
$sql .= $class->getColumnName($class->identifier[0]);
}
return $sql;
}
......@@ -534,7 +538,7 @@ class SqlWalker
$sql .= $aggExpression->getFunctionName() . '(';
if ($aggExpression->isDistinct()) $sql .= 'DISTINCT ';
$sql .= $this->getSqlTableAlias($qComp['metadata']->getTableName()) . '.' . $columnName;
$sql .= $this->getSqlTableAlias($qComp['metadata']->getTableName() . $dqlAlias) . '.' . $columnName;
$sql .= ')';
return $sql;
}
......@@ -564,7 +568,7 @@ class SqlWalker
$parts = $pathExpr->getParts();
$qComp = $this->_queryComponents[$parts[0]];
$columnName = $qComp['metadata']->getColumnName($parts[1]);
return $this->getSqlTableAlias($qComp['metadata']->getTableName()) . '.' . $columnName;
return $this->getSqlTableAlias($qComp['metadata']->getTableName() . $parts[0]) . '.' . $columnName;
}
/**
......@@ -694,7 +698,8 @@ class SqlWalker
$discrSql = $this->_generateDiscriminatorColumnConditionSql($this->_currentRootAlias);
if ($discrSql) {
$sql .= ' AND ' . $discrSql;
if ($termsSql) $sql .= ' AND';
$sql .= ' ' . $discrSql;
}
return $sql;
......@@ -719,7 +724,7 @@ class SqlWalker
}
$discrColumn = $class->discriminatorColumn;
if ($this->_useSqlTableAliases) {
$sql .= $this->getSqlTableAlias($class->getTableName()) . '.';
$sql .= $this->getSqlTableAlias($class->getTableName() . $dqlAlias) . '.';
}
$sql .= $discrColumn['name'] . ' IN (' . implode(', ', $values) . ')';
} else if ($class->isInheritanceTypeJoined()) {
......@@ -771,7 +776,7 @@ class SqlWalker
{
$sql = '';
if ($existsExpr->isNot()) $sql .= ' NOT';
$sql .= ' EXISTS (' . $this->walkSubselect($existsExpr->getSubselect()) . ')';
$sql .= 'EXISTS (' . $this->walkSubselect($existsExpr->getSubselect()) . ')';
return $sql;
}
......@@ -1033,10 +1038,16 @@ class SqlWalker
}
if ($this->_useSqlTableAliases) {
$sql .= $this->getSqlTableAlias($class->getTableName()) . '.';
$sql .= $this->getSqlTableAlias($class->getTableName() . $dqlAlias) . '.';
}
if (isset($class->associationMappings[$fieldName])) {
//FIXME: Composite key support, inverse side support
$sql .= $class->associationMappings[$fieldName]->joinColumns[0]['name'];
} else {
$sql .= $class->getColumnName($fieldName);
}
$sql .= $class->getColumnName($fieldName);
} else if ($pathExpr->isSimpleStateFieldAssociationPathExpression()) {
throw DoctrineException::updateMe("Not yet implemented.");
} else {
......
......@@ -41,6 +41,8 @@ use Doctrine\ORM\EntityManager;
* @since 2.0
* @version $Revision$
* @author Roman Borschel <roman@code-factory.org>
* @internal This class contains performance-critical code. Work with care and
* regularly run the ORM performance tests.
*/
class UnitOfWork implements PropertyChangedListener
{
......@@ -93,8 +95,7 @@ class UnitOfWork implements PropertyChangedListener
/**
* Map of the original entity data of entities fetched from the database.
* Keys are object ids. This is used for calculating changesets at commit time.
* Note that PHPs "copy-on-write" behavior helps a lot with the potentially
* high memory usage.
* Note that PHPs "copy-on-write" behavior helps a lot with memory usage.
*
* @var array
*/
......@@ -102,7 +103,7 @@ class UnitOfWork implements PropertyChangedListener
/**
* Map of data changes. Keys are object ids.
* Filled at the beginning of a commit() of the UnitOfWork and cleaned at the end.
* Filled at the beginning of a commit of the UnitOfWork and cleaned at the end.
*
* @var array
*/
......@@ -1304,21 +1305,21 @@ class UnitOfWork implements PropertyChangedListener
* @param string $className The name of the entity class.
* @param array $data The data for the entity.
* @return object
* @internal Performance-sensitive method.
* @internal Performance-sensitive method. Run the performance test suites when
* making modifications.
*/
public function createEntity($className, array $data, $query = null)
public function createEntity($className, array $data, $hints = array())
{
$class = $this->_em->getClassMetadata($className);
$id = array();
if ($class->isIdentifierComposite()) {
$identifierFieldNames = $class->identifier;
foreach ($identifierFieldNames as $fieldName) {
if ($class->isIdentifierComposite) {
$id = array();
foreach ($class->identifier as $fieldName) {
$id[] = $data[$fieldName];
}
$idHash = implode(' ', $id);
} else {
$id = array($data[$class->getSingleIdentifierFieldName()]);
$id = array($data[$class->identifier[0]]);
$idHash = $id[0];
}
$entity = $this->tryGetByIdHash($idHash, $class->rootEntityName);
......@@ -1347,7 +1348,7 @@ class UnitOfWork implements PropertyChangedListener
if (isset($class->reflFields[$field])) {
$currentValue = $class->reflFields[$field]->getValue($entity);
if ( ! isset($this->_originalEntityData[$oid][$field]) ||
$currentValue == $this->_originalEntityData[$oid][$field]) {
$currentValue == $this->_originalEntityData[$oid][$field]) {
$class->reflFields[$field]->setValue($entity, $value);
}
}
......
<?php
namespace Doctrine\Tests\Models\CMS;
/**
* Description of CmsEmployee
*
* @author robo
* @DoctrineEntity
* @DoctrineTable(name="cms_employees")
*/
class CmsEmployee
{
/**
* @DoctrineId
* @DoctrineColumn(type="integer")
* @DoctrineGeneratedValue(strategy="auto")
*/
private $id;
/**
* @DoctrineColumn(type="string")
*/
private $name;
/**
* @DoctrineOneToOne(targetEntity="CmsEmployee")
* @DoctrineJoinColumn(name="spouse_id", referencedColumnName="id")
*/
private $spouse;
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
public function getSpouse() {
return $this->spouse;
}
}
......@@ -235,4 +235,31 @@ class SelectSqlGenerationTest extends \Doctrine\Tests\OrmTestCase
$connMock->setDatabasePlatform($orgPlatform);
}
public function testExistsExpressionInWhereWithCorrelatedSubquery()
{
$this->assertSqlGeneration(
'SELECT u.id FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = u.id)',
'SELECT c0_.id AS id0 FROM cms_users c0_ WHERE EXISTS (SELECT c1_.phonenumber FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = c0_.id)'
);
}
public function testExistsExpressionInWhereCorrelatedSubqueryAssocCondition()
{
$this->assertSqlGeneration(
// DQL
// The result of this query consists of all employees whose spouses are also employees.
'SELECT DISTINCT emp FROM Doctrine\Tests\Models\CMS\CmsEmployee emp
WHERE EXISTS (
SELECT spouseEmp
FROM Doctrine\Tests\Models\CMS\CmsEmployee spouseEmp
WHERE spouseEmp = emp.spouse)',
// SQL
'SELECT DISTINCT c0_.id AS id0, c0_.name AS name1 FROM cms_employees c0_'
. ' WHERE EXISTS ('
. 'SELECT c1_.id FROM cms_employees c1_ WHERE c1_.id = c0_.spouse_id'
. ')'
);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment