[DC-1065] http://www.doctrine-project.org/jira/browse/DC-98 Created: 17/Jul/14  Updated: 17/Jul/14

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: BizLogic Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: bug, generation, model, patch
Environment:

Linux, PHP


Attachments: File Builder.php    
Issue Links:
Duplicate
duplicates DC-98 Generated base class file names get e... Resolved

 Description   

Doctrine 1.2.4 does not respect the variable baseClassPrefixFiles when generating models.
Generated base files will always have the prefix specified in the baseClassPrefix variable.

Example PHP Code:
		Doctrine_Core::generateModelsFromDb(
			BASEDIR.'/application/models',
			array('doctrine'),
			array(	
				'generateTableClasses'	=> true, 
				'baseClassPrefix'		=> 'Generated_',
				'baseClassesDirectory'	=> 'Generated',
				'baseClassPrefixFiles'	=> false,
				'classPrefixFiles'		=> false
			)
		);

A patched version of ./Doctrine/Import/Builder.php is attached



 Comments   
Comment by BizLogic [ 17/Jul/14 ]

http://www.doctrine-project.org/jira/browse/DC-98?focusedCommentId=23753&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-23753





[DC-1050] Doctrine_Relation_ForeignKey ignores ATTR_COLL_KEY attribute Created: 06/Mar/12  Updated: 03/May/14

Status: Open
Project: Doctrine 1
Component/s: Attributes, Relations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Uli Hecht Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 64Bit
PHP 5.3
Symfony 1.4


Attachments: Text File ForeignKey.php.patch     Microsoft Word Form01 - Diagnóstico-12012011.doc     File Proposta do sistema de Gestão de ligas.odt     File Proposta do sistema de meio ambiente.odt    

 Description   

Doctrine_Relation_ForeignKey::fetchRelatedFor() executes the following code at line 70:

$coll = $this->getTable()>getConnection()>query($dql, $id);
$related = $coll[0];

As you can see it accesses the first element by using index "0" in $coll and hence ignores a modified ATTR_COLL_KEY-setting, for instance:

$this->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'id');

Fortunately I had two models (ForeignA and ForeignB) in my project which both have an one-to-one relation to a third model (Main). That helped me finding this bug which causes the following strange behavior:

// program 1:

$m = new Main();
$m->name = 'M1';
$m->setForeignA(new ForeignA()); // has ATTR_COLL_KEY changed to 'id'
$m->setForeignB(new ForeignB());
$m->save();

// program 2:

$m = Doctrine_Core::getTable('M1')->findOneBy('name', 'M1');
$m->getForeignA()->exists(); // false
$m->getForeignB()->exists(); // true

-------------------------

The big problem about this issue is that behavior is inconsistent. If you don't split the example above into two separate programs/processes you won't have problems, since Doctrine accesses the reference which was stored when calling save().

You will get into trouble using functional tests in Symfony. Since there is only a single process for all requests I wasn't able to reproduce a problem caused by this bug which appeared in the production environment.

-------------------------

Edit:

Doctrine_Connection::queryOne() is affected as well!

A solution is to replace

$coll = $this->getTable()>getConnection()>query($dql, $id);
$related = $coll[0];

by

$related = $this->getTable()>getConnection()>query($dql, $id)->getFirst();



 Comments   
Comment by Uli Hecht [ 07/Mar/12 ]

Suggested patch

Comment by joao guermandi [ 03/May/14 ]

Implementação





[DC-791] [PostgreSQL] In case model is build from existing database sequence name is invalid and doctrine throw exception Created: 16/Jul/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Schema Files
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: Przemysław Ciąćka Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony 1.4.5, postgresql 8.4, debian lenny, nginx


Attachments: PNG File doctrine.png    

 Description   

Firstly I created database directly in postgresql.
After that I generated schema from existsing database and after all i built model.

When I try to insert new record to database I received following error:

sequence "Category_id_seq" does not exist

In schema file sequence name is defined like this: sequence: '"Address_id_seq"'
There's are apostrophes and quotes.

In Category model file is same like above, apostrophes and quotes.

When I remove quotes from sequence in model files everything is ok and there're no problems with insert new row to database.



 Comments   
Comment by Enrico Stahn [ 13/Aug/10 ]

There are 2 solutions to your problem. The first is to change the sequence name in the schema, the second is to change the doctrine configuration.

The default behavior of doctrine is to add a "_seq" to each sequence name. If you remove this part from you sequence name then it sould work as expected. The second option is to change the behavior of doctrine with the following configuration parameter:

 
Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT, '%s'); 

default: Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT, '%s_seq');

Comment by Przemysław Ciąćka [ 25/Aug/10 ]

Problem are quotes in sequence name.
Sequence names in schema built from existing database have quotes in their names, e.g ' "Address_seq" ' and Doctrine try to execute sequence with quotes but in database names exist without quotes.

Temporarly I fixed it by add str_replace() into importer from PostgreSQL - now in schema sequence names are without quotes.





[DC-1022] Doctrine migration does not set version when MySQL autocommit is false Created: 26/Jul/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Adam Fineman Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

RHEL 6.0, mysql 5.1.52


Attachments: Text File migration.patch    

 Description   

With autocommit set to off in mysqld, Doctrine_Migration::setCurrentVersion() does not have any effect. This is because the method uses raw PDO calls, which are discarded without either autocommit or an explicit COMMIT;.

We patched Doctrine as in the attachment. It works for us, but may not be the best general solution.

The patch only fixes this one issue. There are likely many areas in Doctrine that rely upon autocommit behavior in MySQL. We will continue to look for them, and supply patches as we find them. However, as we are only concerned about MySQL, our solutions will probably not apply to other PDO drivers.






[DC-978] Doctrine_Connection_Mssql dies on modifyLimitSubquery every time Created: 27/Feb/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Andrej Pavlovic Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

windows



 Description   

Looking at the latest version of Doctrine_Connection_Mssql in git repo:
https://github.com/doctrine/doctrine1/blob/b4dc8e66a89a7e17cd195c489b18005e19ca9ea5/lib/Doctrine/Connection/Mssql.php

In Doctrine_Query:getLimitSubquery() there is a call to Doctrine_Connection_Mssql::modifyLimitSubquery().

public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, $offset = false, $isManip = false)
{
	return $this->modifyLimitQuery($query, $limit, $offset, $isManip, true);
}

This in turn calls Doctrine_Connection_Mssql::modifyLimitQuery() wihtout passing the $queryOrigin parameter:

    public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false, $isSubQuery = false, Doctrine_Query $queryOrigin = null)
    {
        if ($limit === false || !($limit > 0)) {
            return $query;
        }

        $orderby = stristr($query, 'ORDER BY');

        if ($offset !== false && $orderby === false) {
            throw new Doctrine_Connection_Exception("OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons.");
        }
        
        $count = intval($limit);
        $offset = intval($offset);

        if ($offset < 0) {
            throw new Doctrine_Connection_Exception("LIMIT argument offset=$offset is not valid");
        }

        $orderbySql = $queryOrigin->getSqlQueryPart('orderby');
        $orderbyDql = $queryOrigin->getDqlPart('orderby');

        if ($orderby !== false) {
            $orders = $this->parseOrderBy(implode(', ', $queryOrigin->getDqlPart('orderby')));

            for ($i = 0; $i < count($orders); $i++) {
...

From just looking at the above code, the query chokes on the first call to a $queryOrigin method. It seems like there is a lot of missing code here which should work with the $query directly when $queryOrigin is not available...

What is the point of $orderbySql and $orderbyDql variables when they are not used anywhere?

This code looks like it's half way done and untested.






[DC-951] Error in generating the field size and error in the generation of the date fields for postgres Created: 24/Dec/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.2
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: fernando guerrero Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

apacha2, linux, Symfony 1.4



 Description   

collaboration of vtamara@pasosdejesus.org and jeronimo0000@gmail.com

While we developed a tool with symfony 1.4 and postgresql database we found errors in the generated schema.yml which I describe below

1 - Error in generating of field size of varchars
2 - Error in the generation of date fields

We found the following solution

— Doctrine/Import/Pgsql.php.orig 2010-12-23 17:48:00.160271000 -0500
+++ Doctrine/Import/Pgsql.php 2010-12-23 18:01:59.252271002 -0500
@@ -168,11 +168,14 @@
$columns = array();
foreach ($result as $key => $val) {
$val = array_change_key_case($val, CASE_LOWER);

  • if (strtolower($val['type']) === 'character varying') {
    + if (strtolower($val['type']) === 'varchar') { // get length from varchar definition $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']); $val['length'] = $length; }

    + if ($val['type'] == 'date')

    { + $val['type'] = $val['complete_type'] = 'timestamp'; + }

$decl = $this->conn->dataDict->getPortableDeclaration($val);






[DC-880] Versionable + I18n creates additional migration with irrelevant data Created: 06/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Behaviors, I18n, Migrations, Relations
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Thomas Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

PHP 5.2, Symfony 1.4, Diem 5.1, Doctrine 1.2.2



 Description   

First run of generate-migrations-diff and migrate creates 2 migration diff files. First one for new tables, second one for new indexes and foreign keys. Than if I run generate-migrations-diff again another version is created although nothing was changed and following is inside:

  • 1st entry tries to drop a foreign key never been created and not existing in file
  • next entry tries to create a foreign key already existing
  • 3rd entry tries to create an existing index

After a long try and errorI found out that it's only happening with I18n plus Versionable behavior.

As I already have spent much time for a report please have also a look at: http://forum.diem-project.org/viewtopic.php?f=2&t=173&sid=5e0e3349c0e15a169bc9990a3104b3f6#p465

As I'm quite new to Doctrine and Symfony systems I cannot get further, but willing for more investigation if just one could give me a hint where to start.



 Comments   
Comment by Andrew Coulton [ 10/Oct/10 ]

I think this is because the versionable behaviour doesn't define a table name in the Doctrine_Template_Versionable class. As a result, if using model prefixes, the prefixes are not discarded from the table names when the behaviour model classes are built. This means that the tables have different names to what is expected, so they have different index keys, so the indexes are dropped and recreated as part of the migration.

I have committed unit tests and patch for this issue (which applies to Searchable also) to http://github.com/acoulton/doctrine1/tree/DC-880

Comment by Daniele Dore [ 19/Sep/11 ]

I experienced the same problem in the latest version 1.2.4, and the patch proposed by Andrew Coulton solves the problem.
Why the fix is not included in official release?





[DC-879] MSSQL - missing function date_part() in Expression/Mssql.php [+patch] Created: 05/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Missing function date_part() in Expression/Mssql.php. I don't know why the set of expressions is different for each driver. This makes it hard to develop database independent.






[DC-828] MSSQL - ORDER BY on text columns throws mssql error 306 [+patch] Created: 16/Aug/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Enrico Stahn Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   
  • Table: foo (id:integer, title:text)
  • Created Query: SELECT [id], [title] FROM [foo] ORDER BY [title]

Throws:

Server: Msg 306, Level 16, State 2, Line 1
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.

Solution:

  • Created Query: SELECT [id], [title] FROM [foo] ORDER BY CAST([title] AS VARCHAR(8000))

References:

Patch will be supplied soon ...



 Comments   
Comment by Enrico Stahn [ 20/Aug/10 ]

http://github.com/estahn/doctrine1/compare/DC-828
http://github.com/estahn/doctrine1/tree/DC-828

I guess we need more TestCases for the SubQuery stuff.

Comment by Enrico Stahn [ 02/Sep/10 ]

I made a mistake with github, the updated branch can be found at
http://github.com/estahn/doctrine1/tree/DC-828-2





[DC-825] Versionable does not work with column alias on primary keys [+patch] Created: 13/Aug/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File 0001-TestCase-for-issue-DC-825.patch     Text File 0002-DC-825-fix-generation-of-the-versionable-table.patch     Text File 0003-DC-825-fix-generation-of-model-classes-with-column-a.patch    

 Description   

Using the Versionable behavior on a model which has a column with an alias and which is also primary causes the generation of a wrong version of the versionable table.

Example:

 
ModelFoo:
  model_id as id
  username
  password

Generates tables:
model_foo (model_id, username, password, version)
model_foo_version (id, model_id, userrname, password, version)

It should be:
model_foo (model_id, username, password, version)
model_foo_version (model_id, userrname, password, version)



 Comments   
Comment by Enrico Stahn [ 13/Aug/10 ]

TestCase and Fix
http://github.com/estahn/doctrine1/tree/DC-825

Comment by Enrico Stahn [ 18/Aug/10 ]

The supplied patches are not up-to-date. Pls use http://github.com/estahn/doctrine1/tree/DC-825





[DC-1035] ORA-01791 due to bad driver name in Doctrine_Adapter_Oracle Created: 01/Sep/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: Jayson LE PAPE Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 64 bits, PHP 5.2.11, Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi, Symfony 1.4.13



 Description   

When i execute this code:

 
$q = Doctrine_Query::create()
            ->from('AGENT ag')
            ->leftJoin('ag.CHANTIER_AGENT cag)
            ->orderBy('ag.nom')
            ->limit(10)
            ->execute();
$q2 = Doctrine_Query::create()
            ->from('AGENT ag')
            ->leftJoin('ag.CHANTIER_AGENT cag)
            ->orderBy('ag.nom')
            ->limit(10)
            ->execute();

Doctrine executes :

 
SELECT a.pk AS a__pk, a.ts AS a__ts, a.ck_agent AS a__ck_agent, a.matricule AS a__matricule, a.nom AS a__nom, 
a.prenom AS a__prenom, a.agent_maitrise AS a__agent_maitrise, c.pk AS c__pk, c.ts AS c__ts, c.ck_chantier_agent AS c__ck_chantier_agent, 
c.ek_chantier AS c__ek_chantier, c.fk_chantier AS c__fk_chantier, c.ek_agent AS c__ek_agent, c.fk_agent AS c__fk_agent 
FROM AGENT a 
LEFT JOIN CHANTIER_AGENT c ON a.ck_agent = c.ek_agent 
WHERE a.ck_agent IN (
SELECT a2.ck_agent FROM ( 
SELECT DISTINCT a2.ck_agent, a2.nom FROM AGENT a2 LEFT JOIN CHANTIER_AGENT c2 ON a2.ck_agent = c2.ek_agent ORDER BY a2.nom ) 
a2 WHERE ROWNUM <= 10) ORDER BY a.nom

SELECT a.pk AS a__pk, a.ts AS a__ts, a.ck_agent AS a__ck_agent, a.matricule AS a__matricule, a.nom AS a__nom, 
a.prenom AS a__prenom, a.agent_maitrise AS a__agent_maitrise, c.pk AS c__pk, c.ts AS c__ts, c.ck_chantier_agent AS c__ck_chantier_agent, 
c.ek_chantier AS c__ek_chantier, c.fk_chantier AS c__fk_chantier, c.ek_agent AS c__ek_agent, c.fk_agent AS c__fk_agent 
FROM AGENT a 
LEFT JOIN CHANTIER_AGENT c ON a.ck_agent = c.ek_agent 
WHERE a.ck_agent IN (
SELECT a2.ck_agent FROM ( 
SELECT DISTINCT a2.ck_agent FROM AGENT a2 LEFT JOIN CHANTIER_AGENT c2 ON a2.ck_agent = c2.ek_agent ORDER BY a2.nom ) 
a2 WHERE ROWNUM <= 10) ORDER BY a.nom

This causes "Oracle DB Error ORA-01791 not a SELECTed expression" because the sql query don't have a2.nom in SELECT DISTINCT and it's indispensable for ORDER BY a2.nom
The problem is caused by the variable $attributes in Doctrine_Adapter_Oracle :

 
protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME    => "oci8",
                                  Doctrine_Core::ATTR_ERRMODE        => Doctrine_Core::ERRMODE_SILENT);

The problem is in Query.php line 1417 :

	if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc') {

The driver name declared in Doctrine_Adapter_Oracle not in this conditional.
To resolve this we have to modify the declaration of $attributes in Doctrine_Adapter_Oracle to :

protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME    => "oracle",
                                  Doctrine_Core::ATTR_ERRMODE        => Doctrine_Core::ERRMODE_SILENT);

An other problem is probably located at line 1409

 if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {

and 1497

        if (($driverName == 'oracle' || $driverName == 'oci') && $this->_isOrderedByJoinedColumn()) {

if don't correct the declaration of $attributes in Doctrine_Adapter_Oracle.






[DC-1034] ORA-00904 in Doctrine_Connection_Oracle Created: 01/Sep/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: Jayson LE PAPE Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 64 bits, PHP 5.2.11, Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi, Symfony 1.4.13



 Description   

When i execute this code:

 
$q = Doctrine_Query::create()
            ->from('AGENT ag')
            ->leftJoin('ag.CHANTIER_AGENT cag)
            ->orderBy('ag.nom')
            ->limit(10)
            ->offset(10)
            ->execute();

Doctrine executes :

 
SELECT a.pk AS a__pk, a.ts AS a__ts, a.ck_agent AS a__ck_agent, a.matricule AS a__matricule, a.nom AS a__nom, a.prenom AS a__prenom, a.agent_maitrise AS a__agent_maitrise, 
c.pk AS c__pk, c.ts AS c__ts, c.ck_chantier_agent AS c__ck_chantier_agent, c.ek_chantier AS c__ek_chantier, c.fk_chantier AS c__fk_chantier, c.ek_agent AS c__ek_agent, c.fk_agent AS c__fk_agent 
FROM AGENT a 
LEFT JOIN CHANTIER_AGENT c ON a.ck_agent = c.ek_agent 
WHERE a.ck_agent IN 
(SELECT b.ck_agent 
FROM ( SELECT a.*, ROWNUM AS doctrine_rownum 
FROM ( SELECT DISTINCT a2.ck_agent, a2.nom FROM AGENT a2 LEFT JOIN CHANTIER_AGENT c2 ON a2.ck_agent = c2.ek_agent ORDER BY a2.nom ) 
a2 ) 
b 
WHERE doctrine_rownum BETWEEN 11 AND 20) 
ORDER BY a.nom

The problem is in function _createLimitSubquery in Doctrine_Connection_Oracle :

 
                    $query= 'SELECT '.$this->quoteIdentifier('b').'.'.$column.' FROM ( '.
                                 'SELECT '.$this->quoteIdentifier('a').'.*, ROWNUM AS doctrine_rownum FROM ( '
                                   . $query . ' ) ' . $this->quoteIdentifier('a') . ' '.
                              ' ) ' . $this->quoteIdentifier('b') . ' '.
                              'WHERE doctrine_rownum BETWEEN ' . $min .  ' AND ' . $max;

Error occures, because table name is AGENT and Doctrine give the first letter of the table name for identifier.
To correct this. Use more than one letter in the quoteIdentifier.

 
                    $query = 'SELECT '.$this->quoteIdentifier('limb').'.'.$column.' FROM ( '.
                                 'SELECT '.$this->quoteIdentifier('lima').'.*, ROWNUM AS doctrine_rownum FROM ( '
                                   . $query . ' ) ' . $this->quoteIdentifier('lima') . ' '.
                              ' ) ' . $this->quoteIdentifier('limb') . ' '.
                              'WHERE doctrine_rownum BETWEEN ' . $min .  ' AND ' . $max;





[DC-1032] [PATCH] Doctrine_Collection::isModified() does not support deep like Doctrine_Record but probably should Created: 23/Aug/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Relations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Improvement Priority: Trivial
Reporter: Christian Roy Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File DC-1032.patch    

 Description   

$record instanceof Doctrine_Record;
$collection instanceof Doctrine_Collection;

Using the $record object I can find out if it has been modified : $record->isModified().
I can also have this check all the relations also by passing true : $record->isModified(true);

However, the $collection object only support the first level and not the relations of its member records,
$collection->isModified() returns false if one of the entry has one its relations modified (as it should).

The improvement would be to allow this method to accept true, like it's $record counterpart, which would return true instead.

See attached patch.






[DC-1021] i am executing doctrine type query i am geting error please gave me reply Created: 24/Jul/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: cherukuri Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

windows ,wamp,php



 Description   

$query = new Doctrine_Query();
$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,c.country_id,c.country_name')
//$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,ea.Country')
->from('Entities e')
->leftJoin('e.EntityAddresses ea ON ea.entity_id = e.entity_id AND ea.address_type ="M"')
->leftJoin('ea.Country c ON ea.country = c.country_id')
->leftJoin('e.ActiveFactories s')
->where('e.status=1');
if(!empty($alpha))
{
$query->andWhere("e.entity_name like '".$alpha."%'");
}
$query->andWhere("s.company_id=".$parentId)
->andWhere("e.entity_type=2")
->andWhere('s.status=1')
->groupBy('e.entity_id');






[DC-1008] missing oci_type in Doctrine_Adapter_Statement_Oracle->bindParam Created: 31/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Tomasz Madeyski Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

in bindParam method there is:
switch ($type) {
case Doctrine_Core::PARAM_STR:
$oci_type = SQLT_CHR;
break;
}
I think there should be other oci_types too. I had to add:
case Doctrine_Core::PARAM_INT:
$oci_type = SQLT_INT;
because I got ORA-06502: PL/SQL: numeric or value error: character string buffer too small. while executing
$stmt->bindParam(":result", $result, Doctrine_Core::PARAM_INT);

After adding SQLT_INT everything is ok






[DC-931] Newly generated Migration Classes failing to load due to method used to determine class name Created: 19/Nov/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.0-ALPHA1, 1.2.0-ALPHA2, 1.2.0-ALPHA3, 1.2.0-BETA1, 1.2.0-BETA2, 1.2.0-BETA3, 1.2.0-RC1, 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Adam Benson Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

LAMP



 Description   

The loadMigrationClassesFromDirectory() method in Doctrine_Migration uses array_diff on get_declared_classes() between including each classes script.

When a new migration class is generated by Doctrine_Core::generateMigrationsFromDiff it's class is loaded, which means loadMigrationClassesFromDirectory silently fails to load the newly generated migration on the same request. This means that scripts that first generate migrations and then apply them must be executed twice - first to generate then to apply.

The following example code is used to check if the database has been modifed, generate migrations between the base version and the latest models, and then migrate the database if needed:

automigrate.php
Doctrine_Core::generateYamlFromModels(ROOT_PATH.'tmp/yaml/', ROOT_PATH.'models/');
$result = Doctrine_Core::generateMigrationsFromDiff(ROOT_PATH.'tmp/migrations/', ROOT_PATH.'data/yaml/', ROOT_PATH.'tmp/yaml/');

unlink(ROOT_PATH.'data/yaml/schema.yml');
rename(ROOT_PATH.'tmp/yaml/schema.yml', ROOT_PATH.'data/yaml/schema.yml');

$migration = new Doctrine_Migration(ROOT_PATH.'tmp/migrations');

$currentVersion = $migration->getCurrentVersion();
$latestVersion = $migration->getLatestVersion();
if ($currentVersion < $latestVersion) {
	$migration->migrate();
	$this->app->addMessage("Database migration completed (from version $currentVersion to version $latestVersion)","success");
} else {
	$this->app->addMessage("Database is up to date and doesn't require migration (at version $currentVersion)","success");
}






[DC-747] Sequence name of build process is different to the one used in UnitOfWorks (based on DC521 with updated TestCase) Created: 17/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

doctrine 1.2.4, symfony 1.4, snow leopard, php 5.3.1, postgresql 8.3


Attachments: File DC747TestCase.php    

 Description   

I moved our project from doctrine 1.2.1 to 1.2.4. The build process stops because of this patch. We are using primary keys with an alias. It seems that the generation of the sequence name in the build-process is different to the one used in UnitOfWorks.

Example:

Authority:
columns:
a_id:

{ name: a_id as id, type: integer, primary: true, autoincrement: true }

name:

{ type: string }

This will generate a sequence called "authority_a_id", but it will try no "currval" the sequence "authority_id".

I'll try to provide a UnitTest. The current seems broken.

php -l Ticket/DC521TestCase.php
PHP Parse error: syntax error, unexpected $end, expecting T_FUNCTION in Ticket/DC521TestCase.php on line 143

Parse error: syntax error, unexpected $end, expecting T_FUNCTION in Ticket/DC521TestCase.php on line 143
Errors parsing Ticket/DC521TestCase.php



 Comments   
Comment by Enrico Stahn [ 17/Jun/10 ]

Here is the test updated with the current ticket number.

Comment by Enrico Stahn [ 17/Jun/10 ]

Updated. Now it should work/not work as expected.

Comment by Enrico Stahn [ 17/Jun/10 ]

This isn't a blocker anymore because of the workaround i've found.

  • remove autoincrement
  • add sequence name manually

Example:

Authority:
columns:
a_id:

{ name: a_id as id, type: integer, primary: true, sequence: authority_a_id }

name:

{ type: string }




[DC-1020] In the Timestampable Listener, the 'alias' behavior option is not used when determining the database fieldname Created: 19/Jul/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Timestampable
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Will Mitchell Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.3.5, MySQL 5.5.9; as well as PHP 5.3.6, MySQL 5.0.92


Attachments: Zip Archive Doctrine_Timestampable_Alias.zip    

 Description   

I noticed this issue after setting up timestampable behavior on an aliased column in a legacy table:

 
<?php

abstract class Content_Article extends Doctrine_Record
{

  public function setTableDefinition()
  {
    $this->setTableName('t_content');
    
    $this->hasColumn('id', 'integer', 11, array('primary' => true, 'autoincrement' => true));
    // ...
    $this->hasColumn('datePost as posted_at', 'timestamp');
    $this->hasColumn('dateEdit as updated_at', 'timestamp');
    // ...
    
  }
  
  public function setUp()
  { 
    // ..
    $this->actAs('Timestampable', array('created' => array( 'name' => 'datePost',
                                                            'alias' => 'posted_at'),
                                        'updated' => array( 'name' => 'dateEdit',
                                                            'alias' => 'updated_at')));
  }

}

Before I added timestampable to this model, I was setting the timestamp fields manually, which worked fine.

I had to look at the source to find the alias option in the timestampable behavior, since it does not appear to be in the 1.2 documentation. (If this issue is invalid because it's not an officially supported option, I apologize).

After I added timestampable to the model, Doctrine began throwing an exception when I tried to save a new record:

Error: Doctrine_Record_UnknownPropertyException [ 0 ]: Unknown record property / related component "datePost" on "Content_Article" ~ [...]/Doctrine-1.2.4/Doctrine/Record/Filter/Standard.php

It appears that the alias option is used when setting the table definition in the behavior template, but not used by the template's listener when creating, updating, etc.

I'm attaching a zip with a copy of the changes I made to fix this in 1.2.4 and a git patch.






[DC-998] MySQL Driver possibly subject to sql injections with PDO::quote() Created: 19/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.0-ALPHA1, 1.2.0-ALPHA2, 1.2.0-ALPHA3, 1.2.0-BETA1, 1.2.0-BETA2, 1.2.0-BETA3, 1.2.0-RC1, 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Anthony Ferrara Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

All



 Description   

Prior to 5.3.6, the MySQL PDO driver ignored the character set parameter to options. Due to MySQL's C api (and MySQLND), this is required for the proper function of mysql_real_escape_string() (the C API call). Since PDO uses the mres() C call for PDO::quote(), this means that the quoted string does not take into account the connection character set.

Starting with 5.3.6, that was fixed. So now if you pass the proper character set to PDO via driver options, sql injection is impossible while using the PDO::quote() api call.

PDO proof of concept
$dsn = 'mysql:dbname=INFORMATION_SCHEMA;host=127.0.0.1;charset=GBK;';
$pdo = new PDO($dsn, $user, $pass);
$pdo->exec('SET NAMES GBK');
$string = chr(0xbf) . chr(0x27) . ' OR 1 = 1; /*';
$sql = "SELECT TABLE_NAME
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_NAME LIKE ".$pdo->quote($string)." LIMIT 1;";
$stmt = $pdo->query($sql);
var_dump($stmt->rowCount());

Expected Result: `int(0)`.
Actual Result: `int(1)`.

There are 2 issues to fix. First, the documentation does not indicate that you can pass the `charset` option to the MySQL Driver. This should be fixed so that users are given the proper option to set character sets.

Secondly, `Connection::setCharset()` should be modified for MySQL to throw an exception, since the character set is only safely setable using the DSN with PDO. This is a limitation of the driver and could be asked as a feature request for the PHP core. Either that, or a big warning should be put on the documentation of the API to indicate the unsafe character set change

Note that this is the same issue reported for Doctrine2 with link: http://www.doctrine-project.org/jira/browse/DBAL-111



 Comments   
Comment by Fabien Potencier [ 23/May/11 ]

Any news on this one? It has been "fixed" in Doctrine2 and must be also fixed in Doctrine1.





[DC-883] Help for Test CLI does not list available test groups Created: 10/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Andrew Coulton Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

The CLI Test Runner is supposed to print a list of available test groups when used with the --help parameter, but this fails as the Doctrine_Test::run() method erroneously expects php sort() to return an array rather than a boolean.

Fixed by http://github.com/acoulton/doctrine1/tree/DC-883






[DC-881] Doctrine_Manager::parsePdoDsn() doesn't work properly [+patch] Created: 08/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Doctrine_Manager::parsePdoDsn('dblib:host=127.0.0.1:1433;dbname=foo') does not return proper results.

patch and test case @ github






[DC-852] CLONE -Fix returned type value : SQL integers to PHP integers when getting a value from the database. Created: 01/Sep/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Attributes, Data Fixtures, Native SQL, Query, Record
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hi Jon,

I have a request for you to improve Doctrine. When declaring a column as an integer, it seems that Doctrine returns a string when getting the value of that column. For example, if I have a "status" column, which can take 0, 1 or 2 as its value, Doctrine will return these values as string, which is not really logical and returning the good PHP type is the goal of an ORM. I'm fond of the triple equal symbol to test a value and I did not understand why this did not work at start :

// in my myModel class
class myModel extends Doctrine_Record
{
const STATUS_VALIDATED = 1;

public function isValidated()

{ return self::STATUS_VALIDATED === $this->getStatus(); }

}

That's why getStatus() gives me a string instead of an integer, whereas the column is declared as an integer in my schema. I'm forced to cast myself the returned value of getStatus() in my model.



 Comments   
Comment by Enrico Stahn [ 01/Sep/10 ]

Proposal for a solution: http://github.com/estahn/doctrine1/compare/master...DC-852

Comment by Jonathan H. Wage [ 01/Sep/10 ]

So if you enable this attribute you live with the fact that casting a string to an integer that is longer than php max integer will give weird results?

Comment by Enrico Stahn [ 02/Sep/10 ]

i'm far from happy with this solution. if an integer that is greater than php max int gets casted it will be casted into a value of type double. if you enable that attribute only values that could successfully casted into an integer will be casted otherwise an exception will be thrown.





[DC-741] Sort of Migration Class Problem With More Than 9 Classes Created: 16/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Cli
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Dolly Aswin Harahap Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Ubuntu 10.04, PHP 5.3.2, Doctrine 1.2.2


Attachments: Text File DC-741.patch    

 Description   

I have problem when do a migration with more than 9 classes. (Version1, Version2, Version3, ..., Version10)

php doctrine-cli.php migrate 10

When migration class lower than 10, migration well done.
The migration always return another class, not Version10.

I have do a simple research, and found the problem is on the sort of the class name.
It use SORT_NUMERIC, and it is not suitable to sort them.

So, I change the sort method to Natural Sort, to fix this issue.



 Comments   
Comment by Dolly Aswin Harahap [ 16/Jun/10 ]

Here I attach patch to fix this issue. Please check it.

Comment by Jonathan H. Wage [ 24/Aug/10 ]

I am not able to produce the error, things are always in the correct order. I added a test here: http://trac.doctrine-project.org/changeset/7683

Can you help me with how to reproduce the error?





[DC-1000] Wrong parsing on HAVING clause Created: 28/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Pierrot Evrard Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony 1.4.12-DEV / Windows XP / Apache 2.0 / MySQL 5.1.37 / PHP 5.3.0


Attachments: Text File Doctrine-DC-1000.patch    

 Description   

With Doctrine::ATTR_QUOTE_IDENTIFIER enabled, when you launch a query with a complex having clause, Doctrine_Query_Having class does not handle it correctly.

By example, when you track the having clause interpretation:

$query->addHaving( 'SUM( IF( s.id = ? , 1 , 0 ) ) = 0' , 7 );

At some point, Doctrine_Query_Having at line 70 return something like "`s10`.`id = ?`" instead of "`s10`.`id` = ?".

I just fix it using:

return $this->query->parseClause($func);

instead of:

return $this->_parseAliases($func);

Now, the parseAliases function is not used anymore...

See patch attached...

Loops






[DC-997] Doctrine collections are overwritten when created by inner join queries that agree on the WHERE Created: 13/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Richard Forster Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

OS X 10.6.6 with PHP 5.3.3, Windows with PHP 5.3.1


Attachments: File models.yml     Zip Archive test.zip    

 Description   

In brief:
Doing $result1 = Doctrine_Query::create()>... followed by $result2 = Doctrine_Query::create()>... can lead to a situation where the content of $result1 has become the value in $result2.

In detail:
The attached models.yml defines two simple tables with a One-to-Many relationship; we have people and names and each person can have multiple names. The DB can be propagated along the lines of:

INSERT INTO `tblname` VALUES (1,1,'alpha'),(2,2,'beta'),(3,3,'gamma'),(4,4,'delta'),(5,5,'epsilon'),(6,1,'aleph');
INSERT INTO `tblperson` VALUES (1),(2),(3),(4),(5);

Applying the query:

$results1 = Doctrine_Query::create()
->from('Person ppa')
->innerJoin('ppa.Name n')
->where('ppa.id = ?', 1)
->andWhere('n.text = ?', 'alpha')
->execute()
->getFirst()
->Name;

and then producing output though

print 'Results (1): '.count($results1)."\n";
foreach ($results1 as $result) print $result['text'] . "\n";
print "\n\n";

produces the expected:

Results (1): 1
alpha

Doing a similarly query to a new variable:

$results2 = Doctrine_Query::create()
->from('Person ppa')
->innerJoin('ppa.Name n')
->where('ppa.id = ?', 1)
->andWhere('n.text = ?', 'aleph')
->execute()
->getFirst()
->Name;

and printing with

print 'Results (2): '.count($results2)."\n";
foreach ($results2 as $result) print $result['text'] . "\n";
print "\n\n";

produces the expected:

Results (2): 1
aleph

but printing out the first result object again at this point gives:

Results (1): 1
aleph

which is unexpected - "aleph" rather than "alpha".

If, the second query was altered to

->where('ppa.id = ?', 2)
->andWhere('n.text = ?', 'beta')

then all three output results are as expected.

test.zip contains corresponding test files.






[DC-984] Pessimistic locking locks entire table rather than record Created: 16/Mar/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Transactions
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Barry O'Donovan Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Standard LAMP stack using current SVN from http://svn.doctrine-project.org/branches/1.2/lib/Doctrine/Locking/Manager


Attachments: File Doctrine_Locking_Manager_Pessimistic.diff    

 Description   

When using pessimistic locking as described in:

http://www.doctrine-project.org/projects/orm/1.2/docs/manual/component-overview:locking-manager:examples/zh

the locking manager locks the entire table rather than the specific object.

This should be clear from the attached patch which corrects the issue (assuming I have correctly interpreted the intention of pessimistic locking!).

The current behavior will have worked as expected for users but it will have locked far more than was intended and may thus have affected performance.

NB: I can confirm this works for non-composite keys but please review and test for composite keys as I have no such tables to hand.



 Comments   
Comment by Barry O'Donovan [ 18/Oct/11 ]

Folks - just wondering if anyone had a chance to look at this as, while not critical, it does appear to be a genuinely major performance issue.

Comment by Grégoire Paris [ 13/Dec/12 ]

Duplicate with more information : http://www.doctrine-project.org/jira/browse/DC-185





[DC-746] Sluggable canUpdate overridden after subsequent updates Created: 17/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Adam Benson Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

WAMP stack - PHP 5.3



 Description   

When allowing the user to manually change a slug using 'canUpdate' the slug reverts back to it's default generated value upon subsequent saves. Pre-Update on the Sluggable Listener Template seems to incorrectly decide to regenerate the default value.

Example:

$this->actAs('Sluggable', array('unique'=>true, 'fields'=>array('title'), 'canUpdate'=>true));
$record->description = "An example Item";
$record->title = "Example Title";
$record->save();

echo $record->slug; //"example-title" (Correct)

$record->description = "An example Item";
$record->title = "Example Title";
$record->slug = "custom-slug";
$record->save();

echo $record->slug; //"custom-slug" (Correct - First Save)

$record->description = "An example Item";
$record->title = "Example Title";
$record->slug = "custom-slug";
$record->save();
echo $record->slug; //"example-title" (Incorrect - Subsequent Save. Has regenerated it's default slug and lost the user defined one - even though we have passed the users custom one to the object prior to saving it.).


 Comments   
Comment by Christian Seaman [ 05/Oct/10 ]

As far as I can see this is a problem with the logic in Sluggable::preUpdate() , I recently posted a comment about this here:
http://groups.google.com/group/doctrine-user/browse_thread/thread/d40c6ac733738d4a

In short, I think that the code should be changed from:

Sluggable.php
    public function preUpdate(Doctrine_Event $event)
    {
        if (false !== $this->_options['unique']) {
            $record = $event->getInvoker();
            $name = $record->getTable()->getFieldName($this->_options['name']);

            if ( ! $record->$name || (
                false !== $this->_options['canUpdate'] &&
                ! array_key_exists($name, $record->getModified())
            )) {
                $record->$name = $this->buildSlugFromFields($record);
            } else if ( ! empty($record->$name) &&
                false !== $this->_options['canUpdate'] &&
                array_key_exists($name, $record->getModified()
            )) {
                $record->$name = $this->buildSlugFromSlugField($record);
            }
        }
    }

To this (i.e. remove the canUpdate conditions from the first inner if):

Sluggable.php (modified)
    public function preUpdate(Doctrine_Event $event)
    {
        if (false !== $this->_options['unique']) {
            $record = $event->getInvoker();
            $name = $record->getTable()->getFieldName($this->_options['name']);

            if ( ! $record->$name) { // i.e. remove the other conditions - you should only build the slug from other fields if it's empty
                $record->$name = $this->buildSlugFromFields($record);
            // possibly add an "else if !canUpdate then make sure the old value is preserved" here
            } else if ( ! empty($record->$name) &&
                false !== $this->_options['canUpdate'] &&
                array_key_exists($name, $record->getModified()
            )) {
                $record->$name = $this->buildSlugFromSlugField($record);
            }
        }
    }

I have modified my local version of the Doctrine code to use this modification and it seems to (a) not have the problem you reported above and (b) generally work ok. However, I have not run the test suite against it.

C

Comment by Adam Benson [ 19/Nov/10 ]

Updated affected versions

Comment by Adam Benson [ 19/Nov/10 ]

Thanks for the update Christian, perhaps you could share your fix as a patch?

Comment by Jean-Sébastien GERARD [ 21/Jan/11 ]

Hi, I'm working on a multilingue web portal with Symfony 1.4 and Doctrine 1.2.3, and man, your fix saves my life
I use Sluggable slaved by i18n and without your fix Sluggable simply does not do the job, instead it messes up all slugs when updating, eventually you can't retrieve object anymore based on it. I would not set it as only minor bug ?
thanks, anyway.





[DC-389] query cache doesn't cache _isLimitSubqueryUsed Created: 26/Dec/09  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Caching, Query
Affects Version/s: 1.1.5, 1.1.6
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Peter Kovacs Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Postgres db, php5.2, linux



 Description   

The problem is that _isLimitSubqueryUsed is not cached with query cache.
It gets calculated when building query, but when the query is coming
from cache it's not.
Because of this, line 1087 of Query/Abstract.php is never executed,
when coming from cache:
if ($this->isLimitSubqueryUsed() &&
$this->_conn->getAttribute(Doctrine::ATTR_DRIVER_NAME) !==
'mysql')

{ $params = array_merge((array) $params, (array) $params); } Maybe it is on purpose, but I didn't get any answer on the google-groups. Here is a diff I use now: Index: trunk/gui/doctrine-library/Doctrine/Query/Abstract.php =================================================================== --- a/trunk/gui/doctrine-library/Doctrine/Query/Abstract.php +++ b/trunk/gui/doctrine-library/Doctrine/Query/Abstract.php @@ -1286,4 +1286,5 @@ $cached = unserialize($cached); $this->_tableAliasMap = $cached[2]; + $this->_isLimitSubqueryUsed = $cached[3]; $customComponent = $cached[0]; @@ -1346,5 +1347,5 @@ }

  • return serialize(array($customComponent, $componentInfo,
    $this->getTableAliasMap()));
    + return serialize(array($customComponent, $componentInfo,
    $this->getTableAliasMap(), $this->isLimitSubqueryUsed()));
    }


 Comments   
Comment by Pablo Grass [ 27/Jun/11 ]

This still seems to be a problem in version 1.2.4, rendering the query cache unusable for our project.
The suggested fix works fine, and seems to hold litte potential for trouble.

Anyone still listening/reading here? We are aware of the EOL, but would love to produce a test case to anyone ("official") trying to fix this - just not sure if it is still worth bothering...





[DC-1018] Circular references to named entities break during data importing Created: 14/Jul/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Mike Seth Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If the schema specifies that records relate to each other in both directions:

{{
Kitten:
columns:
basket_id: integer
relations:
Basket:
local: basket_id

Basket:
columns:
fluffiest_kitten_id: integer
relaitons:
FluffiestKitten:
type: one
class: Kitten
local: fluffiest_kitten_id
}}

Then a data dump for such a schema won't properly load one of the keys, e.g:

{{
Kitten:
Kitten1:
Basket: Basket1

Basket:
Basket1:
FluffiestKitten: Kitten1
}}

Will result in either fluffiest_kitten_id or basket_id being set to 0

See also ticket DC-555






[DC-999] Query cache key can be incorrectly generated Created: 28/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Caching, Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jakub Zalas Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None


 Description   

1. We have two versions of the application on the same server.
2. Second application has an updated database. New field is added to one of the models.
3. When the second app is hit first, query is stored in APC.
4. First app finds cached query and tries to call it. Exception is thrown as it doesn't know anything about the new field yet.

Situation often happens on shared development machine when one developer adds a field but others don't have in their models yet. It also happens on staging server if it's shared with production.

I suspect it only affects queries without explicitly listed fields.

To quickly fix the issue in my symfony project I extended Doctrine_Cache_Apc to implement namespaces (https://gist.github.com/944524). More appropriate place to fix it would be Doctrine_Query_Abstract::calculateQueryCacheHash().



 Comments   
Comment by Pablo Grass [ 27/Jun/11 ]

Could this be a duplicate of http://www.doctrine-project.org/jira/browse/DC-389 ?
Are you querying a model with a *-to-many relation and applying a limit?

See also http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language:limit-and-offset-clauses:the-limit-subquery-algorithm





[DC-901] Several test cases using CRLF endings Created: 24/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Damian Bushong Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 x86_64, PHP 5.3



 Description   

Hi there. I'm finding several test cases that are using CRLF line endings, instead of the standard UNIX LF line endings as it seems the rest of the codebase uses.

The test case files are as follows:

tests/Ticket/2158TestCase.php
tests/Ticket/2251TestCase.php
tests/Ticket/2334TestCase.php
This is causing my git pull on the doctrine 1 github repository to fail due to so called "unmerged" files, and has rendered my git submodule for doctrine just about useless.

I'd appreciate it if someone would run a fromdos on these files and commit them.






[DC-887] disabling deep option with toArray() drops relations in result Created: 13/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Lex Brugman Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File doctrine_toarray-deep_fix.patch    

 Description   

Using the toArray() on a Doctrine_Record object with the deep option set to true (default) correctly converts the whole object to an array including the relations.
But when the deep option is disabled the relations are not converted to array's (as expected) but they are lost, I would expect them to still be there in their original form (objects).

I've attached a fix. Another solution would be to add a flag that disables deep array conversion but enables relation persistence.






[DC-856] Doctrine_Core::getPath() not working when inside phar, due to a bug in php Created: 03/Sep/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Miha Vrhovnik Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

It seems that there is a bug in php, and realpath doesn't work when path is inside of phar archive.
function Doctrine_Core::getPath()
if ( ! self::$_path)

{ self::$_path = realpath(dirname(__FILE__) . '/..'); }

can be easily changed to
if ( ! self::$_path)

{ self::$_path = dirname(dirname(__FILE__)); }

 Comments   
Comment by Pierre-Gildas MILLON [ 04/Jan/11 ]

http://bugs.php.net/bug.php?id=52769





[DC-1029] Extensions of Doctrine_Template_I18n incompatible with Doctrine_Import Created: 18/Aug/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Data Fixtures, I18n, Import/Export
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Trivial
Reporter: Pierrot Evrard Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7, XAMPP 1.7.4 with APC and Curl, symfony 1.4.8


Attachments: Text File DC-1029.patch    

 Description   

Extending Doctrine_Template_I18n class make Doctrine_Import on YAML data with translation fails...

Why ? Just because of this line :

Doctrine_Import.php, line 135 :
if ($table->hasRelation($key) && is_array($value) && ! $table->hasTemplate('Doctrine_Template_I18n')) {

In fact, having a template named "Doctrine_Template_I18n" is not strong enough to be sure that the current object has an I18n behavior.

The bug is very simple to reproduce :

1. Get a classic I18n fixtures like :

Article:
Translation:
en:
title: Lorem Ipsum

2. Then make a simple extension of the I18n template (do not do anything else but extends the Doctrine_Template_I18n class) :

class My_Doctrine_Template_I18n extends Doctrine_Template_I18n {}

3. Load the extension, assign it to your model and try to import your fixtures again. It will not work anymore.

Thanks



 Comments   
Comment by Pierrot Evrard [ 18/Aug/11 ]

See this patch where to check if the table has the I18n plugin, I check if one of the templates has a getI18n() method.

This is probably not strong enough but it can do the job until you find a better solution.

Thanks

Comment by Pierrot Evrard [ 18/Aug/11 ]

Another possibility to check that templates are I18n template, will be to create an Doctrine_I18n_Interface. Also, every template that include this interface can be considered as I18n templates.

What do you think about that ?

NB: May the interface can define the method getI18n() to be declared...





[DC-1028] Doctrine Migrate functions for current version and for creating the migrations table Created: 16/Aug/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: Stephen Ostrow Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

I always tend to find myself needing to implement migrations after the fact. It would be really nice to have a method of having doctrine creating the migration_version table as well as a method of setting that value and getting that value.

This would in-turn allow the implementation in a framework such as symfony to allow you insert the table after the fact, allow you to update the migration version without running the migration and to let you know what version you're currently on.






[DC-1001] Doctrine Caching page does not mention the "prefix" option Created: 29/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Caching, Documentation
Affects Version/s: None
Fix Version/s: None

Type: Documentation Priority: Minor
Reporter: Arend van Waart Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 1
Labels: None


 Description   

http://www.doctrine-project.org/documentation/manual/1_1/en/caching

When not using a prefix with multiple / yet similay projects a mixup of query caching will occur (for example with sfDoctrineGuard queries). This is very easialy fixed with a prefix - but I only realized after two months - that this feature actually existed. There is no mention of this in the documention.

A mention of the feature

$q = Doctrine_Query::create()
->useResultCache(new Doctrine_Cache_Apc(array('prefix'=>'myproject_')));

Would have helped me and I think it will also help others.



 Comments   
Comment by Pablo Grass [ 27/Jun/11 ]

I concur with Arend - mentioning of 'prefix' in the documentation could make this valuable feature much less of a pain to find...
Still holds true in 1.2. documentation: http://www.doctrine-project.org/projects/orm/1.2/docs/manual/caching/en





[DC-960] Bug in OCI8 adapter's freeCursor function causes exception with HYDRATE_ON_DEMAND Created: 26/Jan/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.0-ALPHA1, 1.2.0-ALPHA2, 1.2.0-ALPHA3, 1.2.0-BETA1, 1.2.0-BETA2, 1.2.0-BETA3, 1.2.0-RC1, 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: vadik56 Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

doctrine, symfony, linux, hpux


Attachments: File closeCursor.diff    

 Description   

oci_free_statement should be changed to oci_cancel inside Doctrine_Adapter_Statement_Oracle::closeCursor(). Otherwise exception is thrown if HYDRATE_ON_DEMAND is used followed by foreach loop.

Doctrine2 should also be affected by this bug.

Change:
public function closeCursor()

{ $this->bindParams = array(); return oci_free_statement($this->statement); }

To:
public function closeCursor()

{ $this->bindParams = array(); return oci_cancel($this->statement); }




[DC-898] (PATCH) Migration fails when addColumn with type 'boolean' used with default value, resulting in incorrect 'ALTER TABLE' query in MySQL Created: 22/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jakub Argasiński Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OS X 10.6 Snow Leopard / Zend Server CE 5.0.3 (irrelevant)


Attachments: Text File fix_boolean_default_mysql_column_migration.patch    

 Description   

I use MySQL. In my up() method in migration class, I have:

$this->addColumn($table, 'is_master', 'boolean', null, array('notnull' => true, 'default' => false));

Running 'migrate' results in a following exception:
Error #1 - SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'is_master'. Failing Query: "ALTER TABLE books_authors ADD is_master TINYINT(1) DEFAULT '' NOT NULL"
#0 /usr/local/zend/share/pear/Doctrine/Connection.php(1025): Doctrine_Connection->rethrowException(Object(PDOException), Object(Doctrine_Connection_Mysql), 'ALTER TABLE boo...')
#1 /usr/local/zend/share/pear/Doctrine/Export.php(621): Doctrine_Connection->execute('ALTER TABLE boo...')
#2 /usr/local/zend/share/pear/Doctrine/Migration/Process.php(89): Doctrine_Export->alterTable('books_authors', Array)
#3 /usr/local/zend/share/pear/Doctrine/Migration.php(522): Doctrine_Migration_Process->processCreatedColumn(Array)
#4 /usr/local/zend/share/pear/Doctrine/Migration.php(479): Doctrine_Migration->_doMigrateStep('up', 1)
#5 /usr/local/zend/share/pear/Doctrine/Migration.php(328): Doctrine_Migration->_doMigrate(1)
#6 /usr/local/zend/share/pear/Doctrine/Core.php(1016): Doctrine_Migration->migrate(NULL)
#7 /usr/local/zend/share/pear/Doctrine/Task/Migrate.php(41): Doctrine_Core::migrate('/Users/argasek/...', NULL)
#8 /usr/local/zend/share/pear/Doctrine/Cli.php(516): Doctrine_Task_Migrate->execute()
#9 /usr/local/zend/share/pear/Doctrine/Cli.php(498): Doctrine_Cli->executeTask(Object(Doctrine_Task_Migrate), Array)
#10 /usr/local/zend/share/pear/Doctrine/Cli.php(452): Doctrine_Cli->_run(Array)
#11 /Users/argasek/Sites/blipoteka/scripts/doctrine-cli.php(28): Doctrine_Cli->run(Array)
#12

{main}

However, I would expect ALTER query to look like this:

ALTER TABLE books_authors ADD is_master TINYINT(1) DEFAULT 0 NOT NULL

I guess there's a problem with getDefaultFieldDeclaration() in Doctrine_Export_Mysql, it lacks convertBooleans() call being present at Doctrine_Export.






[DC-863] Connection.UnitOfWork::buildFlushTree when loading data from yml file, Incorrect ordering of tables by their relations Created: 10/Sep/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection, Data Fixtures
Affects Version/s: 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Ochoo Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

symfony 1.4.6, windows 7, apache2.2, php5.3.3, mySQL 5.1.49-community


Attachments: File schema.yml     File test.yml    

 Description   

I don't know where exactly to start, I'm new here, and i'm not even sure this is a bug. BUT

We have a database structure with most important tables' PK's as string fields, which function as FK on other tables the basic structure is:

Artist
-Album
-Song
-Comments

each artist has multiple songs
each artist has multiple albums
each album has multiple songs that belong to the same artist as the album belongs to
each song has multiple comments

thus, the UnitOfWork - builtFlushTree should generate

[0]=>Artist
[1]=>Album
[2]=>Song
[3]=>Comments

but instead i get:
[0] => Album
[1] => Artist
[2] => Song
[3] => Lyrics

which in turn generates:

QLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`lyrics`.`album`, CONSTRAINT `album_artist_fk_stripped_name_artist_stripped_name` FOREIGN KEY (`artist_fk_stripped_name`) REFERENCES `artist` (`stripped_name`) ON DELETE CASCADE ON UPDATE CASC)
obviously.

I've been going through symfony/doctrine code for a whole day trying to figure out why I can't load-data. in the end i get to this buildFlushTree function.
probably have to go deeper. but so far this is it

PS. It's my decision to use string fields as PK's and FK even though it's a bad practice, but just because it is a bad practice I shouldn't be unable to work with it.



 Comments   
Comment by Ochoo [ 10/Sep/10 ]

found a tiny BUG, submitting the fix.

EDIT: scratch the rest from here.

<!-----------
still, fixing the bug does not resolve the issue
BECAUSE:
the whole logic of ordering the tables is flawed! it can be proved, don't have time to do so. but trying to come up with a fix myself

instead of looping through the tables and then through each tables' related tables, either have a recursive function OR implement user defined array sort function, latter of which seems like the proper and correct way to go
-->

Comment by Ochoo [ 10/Sep/10 ]

unfortunately i'm unable to commit any changes i have made. just me being a newbie, any help is appreciated

Comment by Ochoo [ 10/Sep/10 ]

on UnitOfWork.php of Doctrine ORM 1.2.3
Revision 7684
right after the line 752:
array_splice($flushList, $index, 0, $relatedClassName);
there should be:
$index++;

Comment by atali daoud [ 29/Nov/10 ]

@Ochoo: Even with your bugfix, it doesn't seem to work.

Comment by Ochoo [ 01/Dec/10 ]

thanks atali, i haven't checked it on 1.2.3, just did and you're right. the "bug fix" worked on 1.2.0 but not on 1.2.3. I'm gonna look into it, at least i'll try. but this is a bug right?





[DC-373] Relating to Translation table (generated by Doctrine_I18n) doesn't work correctly after resetting connection Created: 20/Dec/09  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection, I18n
Affects Version/s: 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Kousuke Ebihara Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

PHP 5.2.11 (with Suhosin-Patch 0.9.7)
PHP 5.3.6


Attachments: File DC373TestCase.php    

 Description   

Relating to Translation table (generated by Doctrine_I18n) doesn't work correctly after resetting connection.

First, I defined the following schema.yml::

 
  Example:
    actAs:
      I18n:
        fields: [title]
    columns:
        title: string(128)

Next, I prepared the following fixture file::

 
  Example:
    Example_1:
      Translation:
        en:
          title: "Title"
        ja:
          title: "題名"

Next, I run "build-all-reload" task. The table was created and data was loaded.

And I write the following code::

 
  Doctrine_Core::loadModels('models');
  $example = Doctrine_Core::getTable('Example')->find(1);
  
  var_dump(
    $example->Translation['en']->title,
    $example->Translation['ja']->title
  );
  
  Doctrine_Manager::resetInstance();
  Doctrine_Manager::getInstance()->openConnection(DSN, 'doctrine');
  
  $example2 = Doctrine_Core::getTable('Example')->find(1);
  var_dump(
    $example2->Translation['en']->title,
    $example2->Translation['ja']->title
  );

I try executing my code, but I got the following error::

  string(5) "Title"
  string(6) "題名"
  
  Doctrine_Connection_Mysql_Exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'e.title' in 'field list' in /path/to/doctrine/Doctrine/Connection.php on line 1082
  
  Call Stack:
      0.0055      65352   1. {main}() /path/to/my/code/test.php:0
      0.2776    5873388   2. Doctrine_Table->find() /path/to/my/code/test.php:52
      0.2793    5881152   3. Doctrine_Query->fetchOne() /path/to/doctrine/Doctrine/Table.php:1611
      0.2793    5881296   4. Doctrine_Query_Abstract->execute() /path/to/doctrine/Doctrine/Query.php:281
      0.2793    5881892   5. Doctrine_Query_Abstract->_execute() /path/to/doctrine/Doctrine/Query/Abstract.php:1026
      0.3127    5890712   6. Doctrine_Connection->execute() /path/to/doctrine/Doctrine/Query/Abstract.php:976
      0.3164    5892632   7. Doctrine_Connection_Statement->execute() /path/to/doctrine/Doctrine/Connection.php:1006
      0.3181    5907408   8. Doctrine_Connection->rethrowException() /path/to/doctrine/Doctrine/Connection/Statement.php:269


 Comments   
Comment by Arnaud Charlier [ 02/Nov/10 ]

Good Morning,

First, thanks a lot for your work on Doctrine. It's a real great tool we love to use.

Currently in one of our big application we have exactly the same issue.
It seems when we close the connection, the reference with the objectTranslation is lost.
Re-open the connection seems not able to reinstantiate this Translation link to the objectTranslation.

Currently we have no solution, but we are still investigating this.

I'm available to go deep in the code with you, but any Doctrine Team help will be really nice.

Thanks to let me know as soon as possible.

Arnaud

Comment by Joe Siponen [ 27/May/11 ]

I've just now battled with the very same problem in Doctrine 1.2 (the version bundled with symfony 1.4) and the problem seems to be caused by the fact that Doctrine_Record_Generator simply isn't written such that it is able to reinitialize generators for unloaded table instances after a connection is closed. This problem also manifests itself after a table has been loaded in a connection and one tries retrieve a table again after Doctrine_Connection->evictTables() has been called. This makes it impossible to to open more than one connection at a time in a request/script when using behaviors that dynamically modify table instances (such as the i18n behavior).

Doctrine_Record_Generator determines if it needs to run its initialization methods simply by checking if the to-be generated class, as defined by the className option, exists using a class_exists call. This means that the first time this method is called the initialization happens but for every subsequent call no initialization is made. Now, in the i18m behavior, the important initialization happens in its setTableDefinition method in which it removes any of the translated fields from the table instance that is been setup and redefines them as relations on the to-be-created Translation class. It then finishes off by dynamically declaring the new class for the translation record using its generateClassFromTable method.

Thus, the first time everything goes smoothly and the i18n generator's setTableDefinition is called and the table instance is properly initialized. Everything will now work as expected while the current connection is open since the connection instance keeps the i18n modified table instances alive and well for callers.

But, when the current connection is closed the i18n modified table instances it holds are also removed (goes out of scope). Then, when a new connection is opened, this new connection will start without having any table instances. This means that the next time one asks the new connection for a table instance of the same class with the i18n behavior the i18n behaviors will fail to initialize because the generator at this time believes its class has actually been initialized which, in turn, means that the table using the i18n behavior isn't properly initialized. No initialization means that this table will now include the non-existant i18n fields in the select part of its queries (those are in the translation table) causing those queries to fail miserably.

I believe this could be fixed by adding a static attribute to Doctrine_Record_Generator that tracks the spl_object_hash of the underlying dbh instance variable of the doctrine connection of the table parameter. If the hash is the same the next time that the initialize method is called the generator can decide not to reinitialize itself but if it detects that the hash of the current connection is different then that is definitely a clue to the generator that it needs to reinitialize itself (i.e. run all of the initialization methods but generateClassFromTable which should't be called more than once).

Maybe do it like this perhaps:

 
abstract class Doctrine_Record_Generator extends Doctrine_Record_Abstract
{
  public function initialize(Doctrine_Table $table)
  {
    /* ... */ 
  
    $currentConnectionHash = spl_object_hash($table->getConnection()->getDbh());
    
    //Next part is called if this is the first connection made or if this is a new open connection with new table instances
    if ($currentConnectionHash != self::$lastConnectionHash)
    {
      self::$lastConnectionHash = $currentConnectionHash;
      
      $this->buildTable();

      $fk = $this->buildForeignKeys($this->_options['table']);

      $this->_table->setColumns($fk);

      $this->buildRelation();

      $this->setTableDefinition();
      $this->setUp();
      
      if ($this->_options['generateFiles'] === false && class_exists($this->_options['className'])) {
        $this->generateClassFromTable($this->_table); //Don't generate the class more than once ever
      }
      
      $this->buildChildDefinitions();

      $this->_table->initIdentifier();
    }
  }
}
Comment by Joe Siponen [ 16/Jun/11 ]

Failing test case attached

Comment by Kousuke Ebihara [ 08/Jun/12 ]

Good job, Joe Siponen! Thanks for your nice patch!

I can't understand why the Doctrine team discontinued maintenance of Doctrine 1 without any fixes for some serious issues like this problem...

Joe, would you send your patch by pull-request in GitHub? They might notice this problem and try to fix in official repository by your request. If you cannnot, I will do it as your proxy. (Of course I'm going to describe your credit)

Comment by Kousuke Ebihara [ 11/Sep/12 ]

I've tested Joe Siponen's patch, it would be good in a situation of single connection, but it doesn't work in multiple connections.

So I modified your patch to fit my needs. I'm testing my arranged patch and I want to publish it ASAP...





[DC-1038] Missing Foreign Key Constraint in SQL Created: 24/Sep/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Stephan Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Hi,

I have the problem, that a foreign key constraint is not created in the SQL schema. This occurs, when the primary key is not the column 'id'.

Here is an example:

User:
columns:
username:
type: string(30)
notnull: false
email:
type: string(80)
notnull: true
gender:
type: enum
values: [0,m,f]
notblank: true
notnull: true
birthday:
type: date

Address:
columns:
user_id:
type: integer(4)
unsigned: 1
notnull: true
primary: true
some_data:
type: string(100)
relations:
User:
local: user_id
foreign: id
foreignType: one

The foreign key from contacts to users is not created in der SQL schema. But if I delete the attribute 'primary' at the column 'user_id' (and a primary key 'id' will generated), everything is okay.

Can you help me please?

With kind regards
Stephan






[DC-1004] ATTR_TBLNAME_FORMAT not used when creating models from database Created: 08/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: 1.2.3

Type: Bug Priority: Major
Reporter: Robin Parker Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File doctrine_bug_diff.diff    

 Description   

if you set prefix to "xyz_%s" and have the model "BackgroundColor" it will become the table => "xyz_background_color"
if you have the table "xyz_background_color" with unknown model and create the the model from the table, you will get => "XyzBackgroundColor".

The fix (diff):

368a369,370
> $tablePrefix = $manager->getAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT);
>
381d382
<
385c386
< $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table));

> $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize(preg_replace(sprintf('/\A%s\z/', str_replace('%s', '(.*?)', $tablePrefix)), '$1', $table)));
396c397
< $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table));

> $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize(preg_replace(sprintf('/\A%s\z/', str_replace('%s', '(.*?)', $tablePrefix)), '$1', $table)));



 Comments   
Comment by Robin Parker [ 08/May/11 ]

The diff output as .diff





[DC-1003] _processWhereIn does not allow the use of named query parameters Created: 05/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Minor
Reporter: alex pilon Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

karmic, php 5.2.10, apache2


Attachments: Text File _processWhereIn-named-parameter-v2.patch     Text File _processWhereIn-named-parameter.patch    

 Description   

When writing a query such as

$query = $query->where('entity.myValue = :value', array(':value'=>5));

you are unable to then

$query = $query->whereIn('entity.otherValue', array(':otherValues'=>array(1,2,3)));

Doctrine complains that you may not mix positional and named query parameters.

The attached patch fixes this by checking if the key of the passed in parameter is non numeric and if so setting the "value" of the parameter place holder to the value of the key.



 Comments   
Comment by alex pilon [ 05/May/11 ]

I discovered an issue with the above patch. I am working on a better version.

Comment by alex pilon [ 06/May/11 ]

Here is a second version.. it is a little bit sloppy. Is there a resource I can find on here that will help me to improve code quality/unit test this?





[DC-1002] Typos in filename and php tags Created: 02/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: nervo Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Two typos in Doctrine files prevents usage of symfony core_compile.yml system, or any similar compiler system :

  • According to its class name, "Doctrine_Validator_HtmlColor", the file "Doctrine/Validator/Htmlcolor.php", should be named "HtmlColor.php" (note the uppercase "C" of "Color")
  • The php tag of the file "Doctrine/Locking/Exception.php" is uppercased. It should be "<?php" instead of "<?PHP"





[DC-944] Precedence problem in SQL generation allows bypass of pending joins Created: 03/Dec/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Walter Hop Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.2, 5.3


Attachments: File Query.pendingjoin.diff    

 Description   

'Pending join conditions' are used by listeners to inject extra SQL conditions into a query. They are often used to add basic constraints on every query. An example is the bundled SoftDelete template. Its listener adds extra constraints such as s.deleted_at IS NULL to a query, to make sure that deleted rows are never retrieved on a query.

However, in the emitted SQL, Doctrine_Query does not use parentheses to group normal SQL conditions together. The pending join condition is simply added to the string without encapsulating existing expressions. This makes it possible to bypass the pending join conditions entirely by using the OR operator.

Example

For instance, the following query exhibits this problem:

$query = Doctrine_Query::create()
->from("SoftDeleteTest")
->where("name=?", "faulty")
->orWhere("name=?", "faulty");

This query emits the following SQL:

SELECT s.name AS s_name, s.deleted_at AS s_deleted_at FROM soft_delete_test s WHERE (s.name = 'faulty' OR s.name = 'faulty' AND (s.deleted_at IS NULL))

which returns also a deleted row.

Expected behavior

One would expect the pending join conditions always to hold, and to have precedence over regularly added SQL conditions. This could be accomplished in the most simple fashion by:

SELECT s.name AS s_name, s.deleted_at AS s_deleted_at FROM soft_delete_test s WHERE ( ( s.name = 'faulty' OR s.name = 'faulty' ) AND (s.deleted_at IS NULL));

As the existing expressions are now encapsulated by parentheses, it is no longer possible to bypass the pending join conditions injected by the query listener.

Full test case details:

init.sql

create database softdelete;
grant all privileges on softdelete.* to softdelete@localhost identified by 'uahwqeruwer';

use softdelete;
CREATE TABLE soft_delete_test (name VARCHAR(255), 
    deleted_at DATETIME DEFAULT NULL, 
    PRIMARY KEY(name)) ENGINE = INNODB;

insert into soft_delete_test values ('fine', null);
insert into soft_delete_test values ('faulty', now());

run.php

<?php

require "./1.2.3/lib/Doctrine.php";

spl_autoload_register(array('Doctrine', 'autoload'));

require "SoftDeleteTest.php";

$conn = Doctrine_Manager::connection("mysql://softdelete:uahwqeruwer@localhost/softdelete");
$conn->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);

$query = Doctrine_Query::create()
    ->from("SoftDeleteTest")
    ->where("name=?", "faulty")
    ->orWhere("name=?", "faulty");

$found = $query->execute();
foreach ($found as $f) {
    echo "ERROR! Found a deleted row: $f->name\n";
}
echo "Done.\n";

SoftDeleteTest.php (copied from Doctrine manual)

<?php

class SoftDeleteTest extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('name', 'string', null, array(
                'primary' => true
            )
        );
    }

    public function setUp()
    {
        $this->actAs('SoftDelete');
    }
}


 Comments   
Comment by Walter Hop [ 03/Dec/10 ]

Fixing quote formatting

Comment by Walter Hop [ 03/Dec/10 ]

Final formatting fixes.





[DC-902] Xcache Cache Driver is not documented Created: 26/Oct/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Caching
Affects Version/s: 1.2.0-ALPHA1, 1.2.0-ALPHA2, 1.2.0-ALPHA3, 1.2.0-BETA1, 1.2.0-BETA2, 1.2.0-BETA3, 1.2.0-RC1, 1.2.0, 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Piotr Leszczyński Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None
Environment:

All



 Description   

Xcache Cache Driver is not documented at all. Is it working? Is it stable? Can we use it?






[DC-831] Importing fixtures fails when GoogleI18n used with "Couldn't create collection index. Record field 'lang' was null." Created: 17/Aug/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Data Fixtures, I18n, Import/Export
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jakub Argasiński Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OS X 10.6.4, Zend Server CE 5.0.2 (irrelevant, I guess)


Attachments: Text File fix_google18n_and_similiar_import_problem.patch    

 Description   

There's a problem with Doctrine_Data_Import. When trying to load a fixture record with translations, and GoogleI18n (or similar) instead of I18n is used (via actAs()), the following crash happens:
Couldn't create collection index. Record field 'lang' was null.

#0 /Users/argasek/Sites/fwm/library/doctrine/Doctrine/Access.php(131): Doctrine_Collection->add(Object(Fwm_Shop_Catalog_CategoryTranslation))
#1 /Users/argasek/Sites/test/library/doctrine/Doctrine/Data/Import.php(241): Doctrine_Access->offsetSet(NULL, Object(Test_Shop_Catalog_CategoryTranslation))
#2 /Users/argasek/Sites/test/library/doctrine/Doctrine/Data/Import.php(335): Doctrine_Data_Import->_processRow('(catalog_catego...', Array)
#3 /Users/argasek/Sites/test/library/doctrine/Doctrine/Data/Import.php(118): Doctrine_Data_Import->_loadData(Array)
#4 /Users/argasek/Sites/test/library/doctrine/Doctrine/Data.php(222): Doctrine_Data_Import->doImport(false)
#5 /Users/argasek/Sites/test/library/doctrine/Doctrine/Core.php(1011): Doctrine_Data->importData('/Users/argasek/...', 'yml', Array, false)
#6 /Users/argasek/Sites/test/library/doctrine/Doctrine/Task/LoadData.php(43): Doctrine_Core::loadData('/Users/argasek/...', false)
#7 /Users/argasek/Sites/test/library/doctrine/Doctrine/Cli.php(516): Doctrine_Task_LoadData->execute()
#8 /Users/argasek/Sites/test/library/doctrine/Doctrine/Cli.php(498): Doctrine_Cli->executeTask(Object(Doctrine_Task_LoadData), Array)
#9 /Users/argasek/Sites/test/library/doctrine/Doctrine/Cli.php(452): Doctrine_Cli->_run(Array)
#10 /Users/argasek/Sites/test/scripts/doctrine-cli.php(29): Doctrine_Cli->run(Array)
#11

{main}

I have narrowed down the problem to the line 135 of Doctrine/Data/Import.php, ie.

if ($table->hasRelation($key) && is_array($value) && ! $table->hasTemplate('Doctrine_Template_I18n')) {

In case of GoogleI18n, $table->hasTemplate('Doctrine_Template_I18n') returns false.

I have no idea how to patch this in a sane way. Adding another condition (&& ! $table->hasTemplate('Doctrine_Template_GoogleI18n') serves well as a workaround, but such condition would be required for any class similar to Doctrine_Template_GoogleI18n. I guess the condition should check if it's a Doctrine_Template_I18n template or any template iherited from this class?...



 Comments   
Comment by Jakub Argasiński [ 17/Aug/10 ]

I have provided a quick workaround patch for this problem, with an approach described in my report, ie. checking whether table has a template being an instance of or a child of Doctrine_Template_I18n.





[DC-769] Variable type different for return value from Doctrine_Record->toArray() depending on whether the object is from a select, or a save. Created: 27/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.1
Fix Version/s: 1.2.1, 1.2.2

Type: Bug Priority: Major
Reporter: Dennis Gearon Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Ubuntu9.10, PHP 5.2.6, Symfony 1.4.1, Postgres8.4



 Description   

With a object that is created via a save(), and the record's primary key is a INT fed by a SEQUENCE, the type of the variable is an INT.

With an object that is hydrated from the database via a SELECT, the record's primary key INT will come back in 'toArray()' as a STRING.

That means that checking for type has to know what context it came from, user, INSERT, or SELECT. Not fun.

This also screws up converting arrays to JSON, 'cause the STRINGS get quotation marks and the INTS do not.

As a general rule, everything FROM the database seems to be strings. Yes, I know, everything 'on the wire' or 'through a socket' comes out as text. And it's a lot faster to leave it that way.

But having the type be different depending on the database operation? Not sure I like that.



 Comments   
Comment by Jonathan H. Wage [ 24/Aug/10 ]

Can you provide a test case so that we can see if we can come up with a patch?





[DC-1057] Inserts instead of updates for related objects Created: 20/Jul/12  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Relations
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Grzegorz Godlewski Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None
Environment:

linux, apache2, php 5.3



 Description   

Ok, so the object relations go like this:

  • Comparison
    • [1:N] Product (FK:comparison_id)
      • [1:N] Rules (FK:product_id, FK:option_id)
      • [1:N] Parameters (FK:product_id)
        • [1:N] Options (FK:parameter_id)

The testing code looks like following:

== CODE START ==

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
$comp = new Application_Model_Comparison();

/* Filling $comp with data */

for ($i = 0; $i < 10; $i++) {

    $product = new Application_Model_Product();

    // Options referenced in Rules
    $options = array();

    for ($j = 0; $j < 10; $j++) {

        $param = new Application_Model_Parameter();

        for ($k = 0; $k < 10; $k++) {

            $option = new Application_Model_Option();

            $param->Options->add($option);

            // Register a single option for this parameter
            if (!isset($options[$j])) {
                $options[$j] = $option;
            }
        }

        $product->Parameters->add($param);
    }

    for ($j = 0; $j < 10; $j++) {
        $rule = new Application_Model_Rule();

        $rule->Option = $options[$j];
        $product->Rules->add($rule);
    }

    $comp->Products->add($product);
}

/**
 * The first save() goes nicely, all objects
 * are created (INSERTed)
 */ 

$comp->save();

// Remove every second product
$pCount = $comp->Products->count();

for ($i = 0; $i < $pCount; $i += 2) {
    $comp->Products->remove($i);
}

/**
 * Fails while trying to save
 *
 * Comparison->Product->Parameter->Option
 * INSERT ... `parameter_id` cannot be NULL
 *
 * Comparison->Product->Rule
 * INSERT ... `product_id` cannot be NULL
 */

$comp->save();

== CODE END ==

The first save() cleans up the relation information in the graph. All child objects are INSERTED instead of UPDATE.






[DC-1048] MSSQL Connection Created: 16/Jan/12  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Constantine Tkachenko Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Microsoft Windows Server 2008 R2; IIS 7; PHP 2.3.8; Doctrine 1.2.4; Symfony 1.4.16



 Description   

Function spliti(); is deprecated.
It need to be change to (in my own opinion):

$field_array = str_ireplace(' as ', ' as ', $field_array);
$aux2 = explode(' as ', $field_array);

thnx.






[DC-1026] PgSQL driver does not create indexes on foreign key columns Created: 08/Aug/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Szurovecz János Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Just like in Doctrine 2 (http://www.doctrine-project.org/jira/browse/DBAL-50):

The PostgreSQL database does not create indexes for foreign key columns, the user has to create them by hand. I think that indexes for foreign keys should be created automatically






[DC-993] Many-to-many Relation defined one way Created: 05/Apr/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Relations
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Klaas van der Weij Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None
Environment:

MySQL database, Lenny



 Description   

When a many-tomany relation has been defined on only one of the end of the relation, and ofcourse in the cross-refClass, things get weird. I'll use the user-groups relation (as found in the documentation) as example.

If in the group model has not defined the hasMany, then a user can be instantiated and saved. When instantiated, the relation groups would return an empty array, groups can ben added like:

$u = new User();
var_dump($u->groups);
$u->groups[] = new Group();
var_dump($u->groups);

This would output an empty array, and subsequently an array containing the new group.

However, if a user would be retrieved from the database, and the relation groups would be called, then the following message will appear (which is not helpfull at alllll, I've spend hours figuring it out!):

Uncaught exception 'Doctrine_Record_UnknownPropertyException' with message 'Unknown record property / related component "groups"' .....

I will never forget this, but it's not described in the documentation and the error is not helping either. So either one of these step hvae to be taken. Or even better, making it work without requiring the hasMany in group, to users.






[DC-840] MSSQL - strange behavior with multiple addWhere conditions and ">" [+patch] Created: 25/Aug/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Trivial
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

In the first example below the second parameter wasn't replaced by the given value. I tracked it down and i suppose it's because of the ">" sign. It's the same for "<". Equal-Operator (=) works fine.

        $q = Doctrine_Query::create()
            ->select('password, modified_at')
            ->from('Ticket_DCXXX_Model')
            ->andWhere('password = ?', 'abc')
            ->andWhere('modified_at > ?', '2010-01-01')
SELECT [t].[id] AS [t__id], [t].[password] AS [t__password], [t].[modified_at] AS [t__modified_at]
FROM [ticket__d_c_x_x_x__model] [t]
WHERE ([t].[password] =  'abc' AND [t].[modified_at] > ?)
        $q = Doctrine_Query::create()
            ->select('password, modified_at')
            ->from('Ticket_DCXXX_Model')
            ->andWhere('modified_at > ?', '2010-01-01')
            ->andWhere('password = ?', 'abc')
SELECT [t].[id] AS [t__id], [t].[password] AS [t__password], [t].[modified_at] AS [t__modified_at]
FROM [ticket__d_c_x_x_x__model] [t]
WHERE ([t].[modified_at] >  '2010-01-01' AND [t].[password] =  'abc')


 Comments   
Comment by Enrico Stahn [ 25/Aug/10 ]

http://github.com/estahn/doctrine1/compare/master...DC-840

Comment by Enrico Stahn [ 27/Aug/10 ]

see DC-841





[DC-651] [PATCH] Doctrine_Record::option('orderBy', ...) of join's right side being applied to refTable in m2m relationship Created: 26/Apr/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query, Relations
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: 1.2.2, 1.2.3

Type: Bug Priority: Major
Reporter: suhock Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 2
Labels: None
Environment:

CentOS 5.4
PHP 5.3.2
MySQL 5.1.44, for unknown-linux-gnu (x86_64)


Attachments: File DC651TestCase.php     File Query_orderBy_relation.diff     Text File Ticket_DC651.patch    

 Description   

When using the Doctrine_Record::option('orderBy', ...) feature on a table definition, where that table is the target of a many-to-many join, the specified orderBy columns are applied to the relation table's alias. So for example, given the following definitions:

class User extends Doctrine_Record {
  public function setTableDefinition() {
    $this->hasColumn('uid', 'integer', null, array('primary' => true));
    $this->option('orderBy', 'uid');
  }

  public function setUp() {
    $this->hasMany('Group as groups', array('refClass' => 'UserGroup', 'local' => 'user_uid', 'foreign' => 'group_id'));
  }
}

class Group extends Doctrine_Record {
  public function setTableDefinition() {
    $this->hasColumn('gid', 'integer', null, array('primary' => true));
  }

  public function setUp() {
    $this->hasMany('User as users', array('refClass' => 'UserGroup', 'local' => 'group_gid', 'foreign' => 'user_id'));
  }
}

class UserGroup extends Doctrine_Record {
  public function setTableDefinition() {
    $this->hasColumn('user_uid', 'integer', null, array('primary' => true));
    $this->hasColumn('group_gid', 'integer', null, array('primary' => true));
  }

  public function setUp() {
    $this->hasOne('User as user', array('local' => 'user_uid', 'foreign' => 'uid'));
    $this->hasOne('Group as group', array('local' => 'group_gid', 'foreign' => 'gid'));
  }
}

the following queries:

$query = Doctrine_Query::create()
  ->select('u.*')
  ->from('User u')
  ->leftJoin('u.groups g WITH g.gid=?', 1);
echo $query->getSqlQuery() . "\n";

$query = Doctrine_Query::create()
  ->select('g.*')
  ->from('Group g')
  ->leftJoin('g.users u WITH u.uid=?', 1);
echo $query->getSqlQuery() . "\n";

will output the following:

SELECT u.uid AS u__uid FROM user u LEFT JOIN user_group u2 ON (u.uid = u2.user_uid) LEFT JOIN group g ON g.gid = u2.group_id AND (g.gid = ?) ORDER BY u.uid
SELECT g.gid AS g__gid FROM group g LEFT JOIN user_group u2 ON (g.gid = u2.group_gid) LEFT JOIN user u ON u.uid = u2.user_id AND (u.uid = ?) ORDER BY u.uid, u2.uid

The orderBy option() call is applied to the User definition. The SQL for the first query is correct (where User is on the left side of the join). The SQL for the second query (where User is on the right-most side of the join), however, is obviously incorrect (UserGroup doesn't even have a uid column). Basically, User's orderBy option is being applied to both the User table and its respective reference table, UserGroup, when it is the target of a join.

After digging through the source for a while, I believe I've come up with a patch for this issue (which should be checked by someone more knowledgeable of Doctrine's internals). Basically, in the Doctrine_Query::buildSqlQuery() function, a call is made to Doctrine_Relation::getOrderByStatement() with the reference table (UserGroup)'s alias (u2), which in turn makes a call to Doctrine_Table::getOrderByStatement() on the referenced table (User), filling in the ORDER BY clause with User columns using UserGroup's alias. My solution was to reorder the logic so that the test for a reference class is made before the initial call to getOrderByStatement() is made. It seems to work against my test case and the test cases in the repository. I'll post my patch momentarily.

This bug was first mentioned in the comments in DC-313, but the original ticket comes across as more of a feature request for the hasMany() orderBy feature.



 Comments   
Comment by suhock [ 26/Apr/10 ]

attached a test case for this bug

Comment by suhock [ 26/Apr/10 ]

patch against /branches/1.2 HEAD (should also work apply to 1.2.2 tag)

Comment by Dan Ordille [ 30/Aug/10 ]

I can confirm this as an issue. However I don't think the above patch adequately fixes the problem it seems like with it an order by is still added for the ref column however the relation alias is lost.

My query with the patch became
SELECT g.gid AS g__gid FROM group g LEFT JOIN user_group u2 ON (g.gid = u2.group_gid) LEFT JOIN user u ON u.uid = u2.user_id AND (u.uid = ?) ORDER BY u.uid, uid

I made an another patch that prevents this extra order by clause from being added and have attached it.

Comment by suhock [ 21/Sep/10 ]

I tried out the new patch (Query_orderby_relation.diff), but it provides a reversed diff (patching goes from a patched version to the original). After applying it manually, it fails the provided test case and several additional test cases from the repository.

The original patch DOES pass the provided test case, when applied against 1.2.2, 1.2.3, or the 1.2 branch from the repository. It does not pass, however, Doctrine_Query_Orderby_TestCase. As the previous poster mentioned, it fails to resolve aliases in instances where the 'orderBy' option is specified in a relation definition.

I deleted the original patch and am providing a revised patch (Ticket_DC651.patch) against branch 1.2 HEAD (also works with 1.2.3), which fixes this issue. It passes all working test cases, including Doctrine_Query_Orderby_TestCase and DC651TestCase.

Comment by José De Araujo [ 31/Aug/11 ]

I had this issue recently on a application I'm working on as described the oderBy option was applied on the joined table on a column that even doesn't exist in it. I used the DC651 patch provided and it solved the issue, so far I haven't seen any side effect to it.





[DC-1016] Set method in update query ignores 'false' if passed as boolean Created: 05/Jul/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Paweł Barański Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony 1.4.11 , Ubuntu 11, PHP 5.3



 Description   

I had to define this function:

public function deactivate($segment_id)

{ $query = $this->createQuery() ->update('Segment s') ->set('s.is_active ', false) //not working // ->set('s.is_active ', (int)false) //works ok // ->set('s.is_active ', true) //works ok ->where('s.id = ?', $segment_id); // var_dump($query->getSqlQuery());die; return $query->execute(); }

Problem is that when setting a column using boolean false you get invalid SQL query like this:
UPDATE segment SET is_active = WHERE (id = ?)

Workaround is to do it like this: set('s.is_active ', (int)false) , but since setting the same column with boolean true works, false should work too.






[DC-1007] Cannot update a field to NULL with MSSQL connection Created: 25/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: guitio2002 Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows 7 32 bits with Apache 2.2.x, PHP 5.2.17, Sql Server 2008, Symfony 1.4.11 and Doctrine 1.2.4



 Description   

When trying to update a field to NULL in a MSSQL database, Doctrine generates the following request:

    UPDATE table SET fieldThatMustBeNull = , anotherField = 'blabla';

therefore generating a syntax error.

A fix would be to override the update method in the Doctrine_Connection_Mssql and add the following behavior:

Doctrine_Connection_Mssql
    public function update(Doctrine_Table $table, array $fields, array $identifier)
    {
        if (empty($fields)) {
            return false;
        }

        $set = array();
        foreach ($fields as $fieldName => $value) {
            if ($value instanceof Doctrine_Expression) {
                $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ' . $value->getSql();
                unset($fields[$fieldName]);
            } else if (is_null($value)) {
                $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = NULL';
                unset($fields[$fieldName]);
            } else {
                $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ?';
            }
        }

        $params = array_merge(array_values($fields), array_values($identifier));

        $sql  = 'UPDATE ' . $this->quoteIdentifier($table->getTableName())
              . ' SET ' . implode(', ', $set)
              . ' WHERE ' . implode(' = ? AND ', $this->quoteMultipleIdentifier($table->getIdentifierColumnNames()))
              . ' = ?';

        return $this->exec($sql, $params);
    }





[DC-843] MSSQL - Equal-to Operator doesn't work with columns of type text in where condition [+patch] Created: 26/Aug/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Enrico Stahn Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Example:

Doctrine::getTable('Ticket_DCXXX2_Model')->findByUsernameAndFoo('foo', 'bar');

foo is of type "text". Doctrine generates "where .... foo = 'bar'", but this will throw an mssql exception because you cant use the equal to operator in mssql for text and varchar types. Doctrine should consider this database related behavoir, shouldn't it?



 Comments   
Comment by Enrico Stahn [ 26/Aug/10 ]

TestCase added http://github.com/estahn/doctrine1/compare/master...DC-843

Comment by Enrico Stahn [ 27/Aug/10 ]

Patch added to github (see above)

commit msg: DC-843 fix (TestCase need fix for DC-841 to run successfully)

Comment by Enrico Stahn [ 02/Sep/10 ]

I made a mistake with github, the updated branch can be found at
http://github.com/estahn/doctrine1/tree/DC-843-2





[DC-758] CascadeDelete not work properly on Versionable and on the AuditLog Created: 21/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jaime Suez Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OS X Snow Leopard, LAMP and Macports



 Description   
 
Schema:

Personal:
  actAs:
    Versionable:
      deleteVersions: false
      cascadeDelete: false

When you use this configuration and try to delete one of the record linked with the versionned one, an exception about foreign key is raised because the id of the versioned record has a foreign key to the id of the record.

It's necessary to could work with cascadeDelete: false... because like that it's needed to use softDelete and the deleted record's will be stored on the version table, but with the advantage that you don't have the performance problem of soft delete behaviour.

Thanks!






[DC-1049] error with Timestamp data Validation Created: 26/Feb/12  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Validators
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Coiby Xu Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux


Attachments: File Timestamp.php    

 Description   

The default value for timestamp is "0000-00-00 00:00:00", so
$e = explode('T', trim($value))
should be changed to
$e = explode(' ', trim($value))

public function validate($value)
{
if (is_null($value))

{ return true; }

$e = explode('T', trim($value));
$date = isset($e[0]) ? $e[0]:null;
$time = isset($e[1]) ? $e[1]:null;

$dateValidator = Doctrine_Validator::getValidator('date');
$timeValidator = Doctrine_Validator::getValidator('time');

if ( ! $dateValidator->validate($date))

{ return false; }

if ( ! $timeValidator->validate($time)) { return false; }

return true;
}






[DC-1037] Migration does not quote identifiers when checking migration version Created: 07/Sep/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: John Kary Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux version 2.4.21-63.ELsmp (mockbuild@x86-005.build.bos.redhat.com) (gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-59)) #1 SMP Wed Oct 28 23:15:46 EDT 2009, Symfony 1.4.14-DEV, Oracle 11g



 Description   

I happen to be using Symfony 1.4.14-DEV (r33007) and am trying to setup migrations with Oracle, which is using Doctrine_Core::ATTR_QUOTE_IDENTIFIER. This issue is in core Doctrine.

To reproduce:

1. Make a change to your schema.yml
2. Create the migrations diff by executing php symfony doctrine:generate-migrations-diff
3. New file have been created at ./lib/migration/doctrine/*_version1.php
4. Try to migrate using command php symfony doctrine:migrate
5. Results in error:

ORA-00942: table or view does not exist : SELECT version FROM migration_version. Failing Query: "SELECT version FROM migration_version"

Cause: The current connection is using quoted identifiers, so the query used to create the migration_version table when migrations are first instantiated was properly created as "migration_version" (notice quotes). But the raw SQL query used in Doctrine_Migration::getCurrentVersion() is not quoting the table or column identifiers, so Oracle can't find the table.

There are several places in Doctrine_Migration where the table and column identifiers are not quoted, thus breaking migrations when using a database with strict rules on the case of identifiers.

Even though I'm developing against Oracle, this also likely affects other drivers.



 Comments   
Comment by John Kary [ 07/Sep/11 ]

Pull request open which quotes all identifiers in Doctrine_Migration and fixes this issue:
https://github.com/doctrine/doctrine1/pull/41





[DC-1036] Doctrine_Export_Oracle::alterTable() not properly quoting column identifier for change Created: 07/Sep/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: John Kary Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This bug was introduced by the person reporting the bug #DC-592.

When trying to generate an ALTER TABLE statement with Doctrine_Core::ATTR_QUOTE_IDENTIFIER enabled, the column identifier is not quoted, and a blank identifier is instead quoted, generating the following SQL:

ALTER TABLE "mytable" MODIFY (username "" VARCHAR2(200))

The proper SQL to be generated should be:

ALTER TABLE "mytable" MODIFY ("username" VARCHAR2(200))


 Comments   
Comment by John Kary [ 07/Sep/11 ]

Pull request opened with failing test case and bug fix:
https://github.com/doctrine/doctrine1/pull/40





[DC-1006] Custom geometric query error with orderBy Created: 22/May/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: Attributes
Affects Version/s: None
Fix Version/s: 1.2.2

Type: Bug Priority: Minor
Reporter: Leonardo Lazzaro Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symfony 1.4.11 and Doctrine 1.2.4. Ubuntu 11.04 Apache2 with mod php5. php5 version PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch



 Description   

Mi Doctrine_Query with this Geometric Query fails with orderBy , but with where works.

$distance = "glength(linestringfromwkb(linestring(GeomFromText('POINT( ".$object->getLatitude()." ".$object->getLongitude() .")'),l.point))) "

This works:
SomeObjectTable::getInstance()>createQuery()>where($distance.' < ?',0.05 )

But this one fails at version 1.2.4, with older version was working.
SomeObjectTable::getInstance()>createQuery()>where($distance.' < ?',0.05 )->orderBy($distance)

Well the problem is at line 74 of OrderBy.php :
$componentAlias = implode('.', $e);

the rendered query in the distance has some ".", for example:
POINT( -34.470829 -58.5286102)

then the after line 74 in OrderBy tries to search por '58' class.

I manually added to DataDict in Mysql.php the POINT datatype (this fix solve me the problem in older versions of Doctrine).






[DC-756] Cannot use named parameters in a 'limit(':max') clause Created: 21/Jun/10  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Dennis Gearon Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

ubuntu, apache, symfony version 1.4.4


Attachments: Text File DC-756.partial.patch    

 Description   

$modulus=5;
$offset=2;
$this->Statuses['ready']=1;

This works
---------------------------------
$DetailsList=
Doctrine_Query::create()->from('Data s')
->where('s.status_id=:status_id')
->andWhere('((s.id % :modulus) - :offset)=0')
->orderBy('s.id')
->limit($maxDaysDetailsToProcess)
>execute(array(':status_id'=>$this>Statuses['ready'],
':modulus'=>$modulus,
':offset'=>$offset), Doctrine::HYDRATE_ARRAY);

This does not, it gets the whole table
---------------------------------
$DetailsList=
Doctrine_Query::create()->from('Data s')
->where('s.status_id=:status_id')
->andWhere('((s.id % :modulus) - :offset)=0')
->orderBy('s.id')
->limit(':max')
>execute(array(':status_id'=>$this>Statuses['ready'],
':modulus'=>$modulus,
':offset'=>$offset,
':max'=>$maxDaysDetailsToProcess), Doctrine::HYDRATE_ARRAY);



 Comments   
Comment by Dennis Gearon [ 24/Jun/10 ]

I noticed an error in the code, which does not solve the problem, only confuse whomever works on it Please add

$maxDaysDetailsToProcess=3;

as the fourth line in the code.

Comment by Juan Antonio Galán [ 07/Sep/10 ]

I think I found a solution but it's making some tests fail. Let me explain you what I did:

First I removed any casting to int of the limit value, in order to keep the named parameter in the LIMIT part of the query. Actually this named parameters were converted to 0 due to those int castings.

Then I realized that the params are bound as strings so the resulting query looks like ... LIMIT "2" or whatever you put in the limit value, and mysql throws and error. Then I tryed to modify the function that binds the paramters to bind them as integers when they're not strings. Everything seems to work fine and you could put named parameters in the limit clause, but some tests are failing. If you look at the tests that are failing you'll see that they're failing because of a wrong phone number, the test it's expecting a number large number like 6155139185 but the result array has a number like 1860171889. I'm wondering if there's something wrong when binding numbers bigger than mysql INT as integers.

I attach a diff file with the changes I did, hope it helps





[DC-701] Aggregates functions do not return proper values when using many relationships and limits Created: 24/May/10  Updated: 17/Apr/14

Status: Reopened
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: will ferrer Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

XP Xamp


Attachments: Text File DC_701_adds_disbaleLimitSubquery_testcase.patch     Text File DC_701_adds_hydrateArrayShallow_testcase.patch     Text File DC_701_fix_adds_arrayShallow.patch     Text File DC_701_fix_adds_disableLimitSubQuery.patch    

 Description   

Hi All

I have encountered a problem that seems very core to the way that doctrine works – if you apply an aggregate function to a column in a table and then join to another table via a many relationship while also using a limit, like so:

$q = Doctrine_Query::create();
$q->from('Customer Customer'); 
$q->addSelect('COUNT(Customer.id) as COUNT_customer_id');
$q->addSelect('Customer_Order.id as order_id'); 
$q->leftJoin('Customer.Order Customer_Order'); // Many relationship here
$q->limit(20);

It produces this correct DQL:

SELECT COUNT(Customer.id) as COUNT_customer_id, Customer_Order.id as order_id 
FROM Customer Customer 
  LEFT JOIN Customer.Order Customer_Order 
LIMIT 20

However the SQL it produces will not return an accurate count – the count is restricted by the limit:

SELECT COUNT(p.id) AS p__0, p2.id AS p2__1 
FROM product_customers p 
  LEFT JOIN product_orders p2 ON p.id = p2.customer_id 
WHERE p.id IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20')

This produces a count of 21 instead of what it should be (1000).

The reason for this is because Doctrine's internal functionality does an intermediary query where it gets gets the ids needed from the customer table in order to use them as the IN portion of the constraints on the final query – like so:

SELECT DISTINCT p3.id FROM product_customers p3 LIMIT 20

It may seem strange that I am applying a limit to a query which will aggregate to 1 to row . In the actual queries that alerted me to this problem I am using a group by. The reason I am not reporting this bug with a group by in my example however is that you can not use a group by with a many relationship and a limit in doctrine 1.2.2 as it works currently (see bug: DC-594). However I am personally able to use a limit with a group by and many relationship since I am using a version of the code I patched my self to repair bug DC-594.

Here is my sample schema in case its helpful.

detect_relations: false
package: Example
options:
  type: INNODB
  charset: utf8
Order:
  tableName: orders
  columns:
    order_id:
      type: integer(4)
      primary: true
      notnull: true
    customer_id:
      type: integer(4)
    order_date: timestamp
  relations:
    Customer:
      type: one
      local: customer_id
      foreign: customer_id
  options:
    type: InnoDB
Customer:
  tableName: customers
  columns:
    customer_id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    firstname:
      type: string(45)
    lastname:
      type: string(45)
    streetaddress:
      type: string(45)
    city:
      type: string(45)
    state:
      type: string(45)
    postalcode:
      type: string(45)
  relations:
    Order:
      type: many
      local: customer_id
      foreign: customer_id
  options:
    type: InnoDB

Thanks much.

Will Ferrer

edit: split SQL code to make the discussion readable without huge horizontal scrolling...



 Comments   
Comment by Jonathan H. Wage [ 08/Jun/10 ]

Is this still a problem? I am not sure if this can be patched easily. The limit subquery algorithm is flawed deeply but also a core part of the current way Doctrine 1 works.

Comment by will ferrer [ 08/Jun/10 ]

Hi Jon

This bug is still an issue for me but I think it may be VERY hard to patch since it seems very core to the way Doctrine 1 works.

The project I am working on at the moment is a visual query builder that is highly reliant on Doctrine. In order to prevent users from making queries that would trigger this bug I am currently giving an alert when ever a query that would trigger this bug is created.

It would be great if this were patchable but if not I should be able to get by.

Does Doctrine 2 fix this problem?

Thanks for the help.

Will Ferrer

Comment by Jonathan H. Wage [ 08/Jun/10 ]

In Doctrine 2 the limit subquery algorithm does not exist. It is now up to the developer to write the query to handle the scenario instead of Doctrine "trying" to automate it for you. Since the situation where it is needed it is so rare, and each case can be slightly different it is better to let the developer handle it in those cases.

Comment by will ferrer [ 08/Jun/10 ]

Hi Jon

Does that mean that Doctrine 2 can no longer intelligently handle limits with many relationships, and doesn't have the ability to hydrate a return with sub arrays in it for many relationships?

Thanks again for your help.

Will Ferrer

Comment by Jonathan H. Wage [ 09/Jun/10 ]

That is correct. We do not automatically try and limit the relationships with a "limit subquery" as it causes more problems then it helps.

Comment by will ferrer [ 10/Jun/10 ]

Hi Jon

I was thinking about what you said here – that the "limit subquery" causes more harm than good. It occur to me that I really do like being able to use this method (it comes in very handy very often) but some times it would really help to be able to turn it off (the bug in this thread is a good example such a time). So I figured why not just make an option to turn it off and have the best of both worlds? I looked at the code and found it was really very easy to put in a property which can be set on the query object to enable or disable the use of the limit subquery.

I made the change in my code base and found it very useful for several situations I was dealing with in my own project.

The one thing I couldn't do is make a test case for this new feature – I couldn't find an existing test case that was actually triggering the limit subquery as I understood it to work (I couldn't find a test case that would put an WHERE IN constraint with all the ids gathered in the limit subquery. I tried some test cases that I THOUGHT would activate this feature but it didn't seem that they did).

After adding this feature to my code base I also wanted a new hydrator – one that worked like scalar but would put in array key names that were the same as the ones you would see in HYDRATE_ARRAY. I noticed that HYDRATE_SCALAR already had the ability to do this but it required that a value of false be passed into the $aliasPrefix argument of the _gatherRowData function. I made a custom hydrator I call HYDRATE_ARRAY_SHALLOW that passes in this false value. I then realized this might be handy to add to doctrine so I integrated it into my code base and made a few test cases for it.

There are 2 patches I am now attaching this to thread:

disableLimitSubquery_2010-06-10_Doctrine_1.2_SVN.patch – this patch adds the disableLimitSubquery property to query objects so that users can turn off the use of the subquery for those times when they don't want to use that behavior (fixing the bug in this thread and probably others)

and

disableLimitSubquery_and_HYDRATE_ARRAY_SHALLOW_2010-06-10_Doctrine_1.2_SVN.patch – this is the same as the first patch but also contains the HYDRATE_ARRAY_SHALLOW hydration type I mentioned above (which tends to go well with disableLimitSubquery turned on).

I put these in 2 patches incase you liked 1 feature but disliked the other.

If you like either of this features I would be very happy to see them added to doctrine.

Also if you have any advice on how to improve these features (or info on how to make a good test case for disableLimitSubquery) please let me know.

Hope you are well.

Will Ferrer

Comment by will ferrer [ 10/Jun/10 ]

Reopened because I added a patch that I think in essence fixes the issues.

Comment by Jonathan H. Wage [ 01/Sep/10 ]

Thanks for the issue and patches.

Fixed here http://github.com/doctrine/doctrine1/commit/2ad78e62e360133efc04bf6897bf679c7f3d833b

Comment by will ferrer [ 01/Sep/10 ]

individual patch for this issue with out other features included

Comment by will ferrer [ 01/Nov/10 ]

adding test cases for these features

Comment by will ferrer [ 01/Nov/10 ]

reopened because I posted some test cases to add to doctrine along with the patchs previously posted





[DC-1046] Connection MSSQL replaceBoundParamsWithInlineValuesInQuery Created: 15/Dec/11  Updated: 17/Apr/14

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Peter Eisenberg Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Revision: 104


Attachments: Text File replaceBoundParamsWithInlineValuesInQuery.patch    

 Description   

Hello,

We found a bug in Doctrine1 MSSQL Connection.
When you would like to use the following functionality: find(One)By(p1,p2)
if you use the old functionality (Symfony 1.4 support it) like this: findBy("idAnddata", array("id" => ..., "date" => ..)), you got an MSSQL error, because the values wasn't changed.

Please find the patch for it, I hope it helps to you as well.

Kind regards
Peter



 Comments   
Comment by Peter Eisenberg [ 15/Dec/11 ]

Small changes:
Unfortunately the notice wasn't set in my test environment, and I didn't realized this small error:

please use the following instead of the original:
$replacement = 'is_null(\$value) ? \'NULL\' : \$this->quote(\$params[\'\\1\'])';

another case you got the following error: Use of undefined constant xxx - assumed xxx.

Kind regards,
Peter





[DC-1062] Testing Created: 08/Jan/14  Updated: 08/Jan/14

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.2
Fix Version/s: 1.2.1

Type: Task Priority: Critical
Reporter: Janardan Singh Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None





[DC-1061] ORACLE CHARSET DOCUMENTATION Created: 10/Jul/10  Updated: 28/Dec/13

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: fernando guerrero Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None
Environment:

ORACLE db SYMFONY



 Description   

Openning an Oracle Database with Doctrine and Symfony doesn't support by default utf8 charset.

To support it, it is necessary to specify charset=AL32UTF8 in the dsn of the database in config/databases.yml. Analogous to the example shown at
http://groups.google.com/group/doctrine-user/browse_thread/thread/d0d22145d8bdc83
however we have been able to use it fully only with the oracle driver (instead of oci), for example:

oracle:dbname=//192.168.2.9:1521/nomina_dev;charset=AL32UTF8

Documentation by Alexia Velásquez (alexia.velasquez@hotmail.es, Vladimir Tàmara (vtamara@pasosdeJesus.org) and Fernando Guerrero



 Comments   
Comment by Steve Müller [ 26/Nov/13 ]

I know this ticket is very old. But there is an option to set the charset for OCI8. See:

http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#pdo-oci-oci8

Comment by Steve Müller [ 28/Dec/13 ]

This is a legacy ticket related to Doctrine 1.





[DC-1056] Doctrine is not compatible with PHP 5.4 due to change in serialize() behaviour. Created: 04/Jun/12  Updated: 06/Oct/13

Status: Open
Project: Doctrine 1
Component/s: Record, Relations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Marcin Gil Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

PHP 5.4+


Attachments: Text File Record.php.patch    

 Description   

In PHP 5.4 there is a change in the way the object references are serialized:

Quote:
"Support for object references in recursive serialize() calls
Prior to PHP 5.4, object references where not saved in recursive serialize calls."

This minor change, breaks down serialization of collections when column of type "array" is present - double serialization occurs.
I'm attaching a patch fixing the issue.



 Comments   
Comment by Colin Darie [ 15/Oct/12 ]

I confirm for possible future readers: this patch works perfectly well. (cf github for several forks of doctrine with other bugfixes).

Comment by steven [ 27/Jan/13 ]

Hi all, does somebody knows where can I get a copy of the Doctrine 1.2.4 version but running on php 5.4?
Thise version you're talking about

Thanks

Comment by Marcin Gil [ 28/Jan/13 ]

I sent you URL to our private svn repo.

Comment by steven [ 28/Jan/13 ]

Thanks, you've saved mi life

Comment by Marcin Gil [ 06/Oct/13 ]

New, better patch.

Comment by Marcin Gil [ 06/Oct/13 ]

Hi, I have uploaded a better patch which resolved one more issue.

Comment by Christophe Coevoet [ 06/Oct/13 ]

Please use a pull request on github to submit a patch





[DC-1060] Datetime Fomatting not working on findId in DB2 Platform Created: 24/Sep/13  Updated: 24/Sep/13

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: 1.2.3
Fix Version/s: 1.2.3

Type: Bug Priority: Major
Reporter: Preethi Srinivasan Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

In DB2/Symfony2


Attachments: PNG File Screen Shot 2013-09-24 at 3.55.44 PM.png     PNG File Screen Shot 2013-09-24 at 3.56.13 PM.png    

 Description   

We had to put this fix to check for DateTimeTz in SimpleObjectHydartor to make it work for DB2. Same code works for mysql. Is it possible to put a fix as part of release of next Doctrine so we need not update vendor code locally.
if (isset($cache[$column]['field'])) {
$type = Type::getType($cache[$column]['class']->fieldMappings[$cache[$column]['name']]['type']);
if ($type == 'DateTimeTz')

{ $value = substr($value, 0, 19); }

$value = $type->convertToPHPValue($value, $this->_platform);
}

The error happens when we do a find($id) in
$ep = $em->getRepository('some name')->find($id);






[DC-972] MySQL field aliases with triple ticks Created: 16/Feb/11  Updated: 18/Jul/13

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: Roland Huszti Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None
Environment:

MySQL 5, PHP 5


Attachments: File BaseTerritoryCombined.php    

 Description   

In revision 7691 something has happened. Ever since I updated my Doctrine to that revision all my queries having " ... fieldname AS aliasname ... " go crazy and make the PHP to throw an exception, like this:

'Doctrine_Connection_Mysql_Exception' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 't.`id`' in 'field list'. Failing Query:
"SELECT `t`.`id` AS `t_id`, `t`.```id``` AS `t0`, `t`.```name``` AS `t1`, `t`.`id` AS `t0`, `t`.`name` AS `t_1` FROM `territoryCombined` `t` ORDER BY `t`.`name` asc"'
in ...path here.../doctrine/lib/Doctrine/Connection.php:1082

The problem is that the DQL parser somewhere along the process encapsualtes aliases in ticks, but then it does it again in lib/Doctrine/Formatter.php : quoteIdentifier() , which is called in lib/Doctrine/Connection : quoteIdentifier() , which is called in lib/Doctrine/Query.php : processPendingFields() @ between lines 485 and 512. The problem is that by the time the alias name gets to line 507 it is already encapsualted in ticks, but it does it again. At the end we end up with ```alias``` , which is not good.

It only happens to aliases. If I say select('*') or select("t.id, t.name") then it executes properly. Only the aliases couse problems.

A test query:

$vTerritories = Doctrine_Query::create()
->select("t.id as territory_id, t.name as territory_name")
->from('TerritoryCombined t')
->orderBy('t.name asc')
->fetchArray();

MY PROPOSED PATCH:

If I change the Formatter::quoteIdentifier() to this:

public function quoteIdentifier($str, $checkOption = true)

{ $tmp = $this->conn->identifier_quoting; // I move up this line to here because I need it if ( (substr($str, 0, 1) == $tmp['start']) && (substr($str, -1) == $tmp['end']) ) return $str; // new line; is it already quoted? if yes, then don't do it again // the rest is unchanged }

then it works correctly. Please note I only tested that in MySQL, as we use MySQL in all our projects.



 Comments   
Comment by Mishal [ 18/Jul/13 ]

Bringing dead things back to life

Fixed in: https://github.com/mishal/doctrine1/commit/aca0a00c2278498aef997d208cc91ecd52a9c0d3





[DC-884] Doctrine_Collection::loadRelated uses getLocal instead of getLocalFieldName Created: 11/Oct/10  Updated: 18/Feb/13

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jason Brumwell Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

Windows



 Description   

Having a camelcase fieldname with a lowercase column name causes loadRelated of doctrine collection to throw an unknown property error, fix:

Change

$rel     = $this->_table->getRelation($name);

        if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) {
            foreach ($this->data as $record) {
                $list[] = $record[$rel->getLocal()];
            }
        }

to:

$rel     = $this->_table->getRelation($name);

        if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) {
            foreach ($this->data as $record) {
                $list[] = $record[$rel->getLocalFieldName()];
            }
        }
public function populateRelated($name, Doctrine_Collection $coll)
    {
        $rel     = $this->_table->getRelation($name);
        $table   = $rel->getTable();
        $foreign = $rel->getForeign();
        $local   = $rel->getLocal();

to

public function populateRelated($name, Doctrine_Collection $coll)
    {
        $rel     = $this->_table->getRelation($name);
        $table   = $rel->getTable();
        $foreign = $rel->getForeignFieldName();
        $local   = $rel->getLocalFieldName();


 Comments   
Comment by Sebastian [ 12/Oct/11 ]

Now this is really poor. This trivial bug is known for over a year not but not yet fixed.

Fixing it would save millions of rainforrest trees because people would not have to rely on hundreds of lazy loading queries per page but start to use the getRelation() method.

Comment by Sebastian [ 18/Oct/12 ]

Two years now. :'-(

Comment by Mishal [ 18/Feb/13 ]

Another year, and all people are probably on Doctrine2.

But.... I just pushed your fix #DC-884 to my Doctrine1 fork, if you are interested.

https://github.com/mishal/doctrine1





[DC-356] Error in self referencing (nest relations) and tableName. Created: 14/Dec/09  Updated: 17/Jan/13

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Sergio Gomez Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

Linux, php 5.2.10, apache 2.2.12



 Description   

I have this schema:

  1. Interface
    Interfaz:
    tableName: YT_INTERFAZ
    columns:
    cinterfaz: { type: integer, notnull: true, primary: true, autoincrement: true }

    relations:
    Conexiones:
    class: Interfaz
    local: cinterfazsrc
    foreign: cinterfazdst
    refClass: Conexion
    equal: true

#Link
Conexion:
tableName: YT_CONEXION
columns:
cinterfazsrc:

{ type: integer, primary: true }

cinterfazdst:

{ type: integer, primary: true }

When I try to get $interfaz->Conexiones, I get this message:

Notice: Undefined index: yt_interfaz in /home/sergio/Proyectos/syc/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Hydrator/Graph.php on line 288

Notice: Undefined index: in /home/sergio/Proyectos/syc/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Hydrator/Graph.php on line 289

Fatal error: Call to a member function getFieldName() on a non-object in /home/sergio/Proyectos/syc/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Hydrator/Graph.php on line 290

But If I remove tableName fields in schema declaration, it works perfectly. The name of tableName don't matters, if you use it, it fails.



 Comments   
Comment by Klaas van der Weij [ 15/Feb/11 ]

Same story over here. Same error with the following non-equal nest relation:

<?php

class TXCRDataNodeCRDataNode extends Doctrine_Record
{
    public function setTableDefinition() {
        $this->setTableName('x_CRDataNode_CRDataNode');
        $this->hasColumn('childNodeID', 'integer', 4, array(
             'type' => 'integer',
             'length' => 4,
             'fixed' => false,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => false,
             ));
        $this->hasColumn('parentNodeID', 'integer', 4, array(
             'type' => 'integer',
             'length' => 4,
             'fixed' => false,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => false,
             ));
    }

    public function setUp() {
        parent::setUp();
        $this->hasOne('TCRDataNode as child', array(
             'local' => 'childNodeID',
             'foreign' => 'dataNodeID'));
        $this->hasOne('TCRDataNode as parent', array(
             'local' => 'parentNodeID',
             'foreign' => 'dataNodeID'));
    }
}

class TCRDataNode extends Doctrine_Record
{
    public function setTableDefinition() {
        $this->setTableName('CRDataNode');
        $this->hasColumn('dataNodeID', 'integer', 4, array(
             'type' => 'integer',
             'length' => 4,
             'fixed' => false,
             'unsigned' => false,
             'primary' => true,
             'autoincrement' => false,
             ));
        $this->hasColumn('value', 'string', 255, array(
             'type' => 'string',
             'length' => 255,
             'fixed' => false,
             'unsigned' => false,
             'primary' => false,
             'notnull' => false,
             'autoincrement' => false,
             ));
    }
    public function setUp() {
        $this->hasMany('TCRDataNode as childNodes', array(
            'local' => 'parentNodeID',
            'foreign' => 'childNodeID',
            'refClass' => 'TXCRDataNodeCRDataNode'));
        $this->hasMany('TCRDataNode as parentNodes', array(
            'local' => 'childNodeID',
            'foreign' => 'parentNodeID',
            'refClass' => 'TXCRDataNodeCRDataNode'));
    }
}

$dn = Doctrine_Core::getTable('TCRDataNode')->find(5300);

?>

.. and then when I ..

<?php

$pn = $dn->parentNodes;

?>

.. it goes like:

Notice: Undefined index: crdatanode in /home/shared/library/doctrine_1.2.2/Doctrine/Hydrator/Graph.php on line 288

Notice: Undefined index: in /home/shared/library/doctrine_1.2.2/Doctrine/Hydrator/Graph.php on line 289

Fatal error: Call to a member function getFieldName() on a non-object in /home/shared/library/doctrine_1.2.2/Doctrine/Hydrator/Graph.php on line 290

Using Doctrine 1.2.2

It seemed like the same thing as presented in the documentation

Comment by Klaas van der Weij [ 17/Feb/11 ]

This aching issue - as I traced the cord back to the wall - appears to originate from the fact that I use UPPERCASES in the names of my databas tables. When I user all lowercases: no problem. Hence it worked on my WAMP server (Windows just lowercases it all). Even when I so much as start the entity-table which an UPPERCASE: bang! Fatal error.

This is not logical and, I presume, is a definite bug.

Please, oh please fix this ..

Comment by Danny Kopping [ 06/Mar/12 ]

As Klaas mentions, this function incorrectly assumes that all databases will be named using lowercase letters.

The problem arises in the following line:
$cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];

If one removes the "strtolower" function call, it will work for tables named with uppercase letters, but this is obviously quite an inelegant solution.

Could you suggest an alternative solution? I'll be happy to make the change, test it and issue a pull request in GitHub

Comment by Danny Kopping [ 06/Mar/12 ]

I've just tested this scenario in as many different possible combinations as I could think of (all tables uppercase/PascalCase, all tables lowercase, some Pascal, some lowercase) and just by removing the "strtolower" function, the issue seems to be resolved.

Comment by Jay Klehr [ 17/Jan/13 ]

We've encountered this as well, tried a lot of different things in our models/schema to get around it, but nothing worked.

Made a test case here: https://github.com/diablomedia/doctrine1/blob/master/tests/Ticket/DC356TestCase.php

Modified the doctrine core as suggested by Danny, but this change causes other Doctrine test to fail (Particularly tests/TableTestCase.php).





[DC-185] The pessimistic offline locking manager locks the entire table Created: 04/Nov/09  Updated: 13/Dec/12

Status: Reopened
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.1.4, 1.1.5, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Fabian Brussa Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 7
Labels: None
Environment:

Windows XP, WampServer Version 2.0


Attachments: File DC185TestCase.php     Text File row_based_locking.patch    

 Description   

Scenario:
$entity = Doctrine::getTable('Steps')->find($pID);
$lockingManager = new Doctrine_Locking_Manager_Pessimistic( Doctrine_Manager::connection() );
$lockingManager->releaseAgedLocks(300);
$gotLock = $lockingManager->getLock($entity, 'user1' );

Running this code locks the entire table "Steps", and not just the record.

in the table "doctrine_lock_tracking", in the fields: "object_type" and "object_key" are saved in this case: "Steps" and "IDStep".
I think that here must be saved "Steps" and "120" (the value of IDStep).



 Comments   
Comment by Fabian Brussa [ 18/Nov/09 ]

Is anybody looking into this issue ?

Comment by Jonathan H. Wage [ 18/Nov/09 ]

Can you provide a test case that shows the issue? It is hard to look into the issue without a test to run When I look at the code and our tests everything is passing and fine so I am not sure what your issue could be. Re-open if you have more information to provide.

Comment by Fabian Brussa [ 19/Nov/09 ]

ok, I attach the test case

Comment by Fabian Brussa [ 03/Dec/09 ]

Have you already been able to look at the testcase ??

Comment by Fabian Brussa [ 14/Jan/10 ]

Any news ??

Comment by Piotr Leszczyński [ 25/Jun/10 ]

This issue is still valid for Doctrine 1.2. Doctrine_Locking_Manager_Pessimistic is UNUSABLE without this bug fixed!

Comment by Markus Wößner [ 02/Jul/10 ]

Having a look at "Doctrine_Locking_Manager_Pessimistic::getLock()" it becomes clear what causes this misbehaviour:

    public function getLock(Doctrine_Record $record, $userIdent)
    {
        $objectType = $record->getTable()->getComponentName();
        $key        = $record->getTable()->getIdentifier();

        $gotLock = false;
        $time = time();

        if (is_array($key)) {
            // Composite key
            $key = implode('|', $key);
        }

        try {
            $dbh = $this->conn->getDbh();
            $this->conn->beginTransaction();

            $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable
                                  . ' (object_type, object_key, user_ident, timestamp_obtained)'
                                  . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)');

            $stmt->bindParam(':object_type', $objectType);
            $stmt->bindParam(':object_key', $key);
            $stmt->bindParam(':user_ident', $userIdent);
            $stmt->bindParam(':ts_obtained', $time);

There is NO hint about the Record's identifier VALUE but only about the identifier's NAME (mostly "id") which appears to be redundant information. Instead of ...

        $key = $record->getTable()->getIdentifier();

..there should be something like ..

        $key = $record->get($record->getTable()->getIdentifier());

In case of composite keys a string concatenation, prefixed by identifier's name might work but I would recommend using "md5()" on resulting value to limit its length since field "object_key" is limited to 250 chars.

Comment by Florian Zumkeller-Quast [ 02/Jul/10 ]

Based on the previous comment by Markus Wößner i created a patch for row based locking.

It concatenates the PK fields and their values to a string and calculates the sha-1 hash as a unique string representing that record. This string is then used as key so that we'll only lock the single Record and not the whole table.

I hope you'll give this patch a try - It solved this problem for me.

Comment by Markus Wößner [ 02/Jul/10 ]

I applied patch from Mr. Florian Zumkeller-Quast and provided testcase didn't fail anymore. I think this should do it. By the way I find it strange that this issue isn't already fixed. I guess locking is not very much used by Doctrine users.

Comment by Jérôme Weber [ 21/Nov/11 ]

I applied patch too and it works now. I guess too that nobody use Lockings but when you use it ... without the patch it fails.

Comment by Grégoire Paris [ 13/Dec/12 ]

Duplicate of http://www.doctrine-project.org/jira/browse/DC-984





[DC-1059] Generate Entity From Database Created: 27/Sep/12  Updated: 27/Sep/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Draeli Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Problem already report here : https://github.com/symfony/symfony/issues/5617#issuecomment-8934524
But the idea is, on generation of entity from database MySQL, Int and Tinyint type are tranform as booelan.






[DC-1051] Timestampable listener does not set timestamp fields on a copy of a Doctrine_Record Created: 14/Mar/12  Updated: 06/Sep/12

Status: Open
Project: Doctrine 1
Component/s: Timestampable
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jeremy Johnson Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File Timestampable.php    

 Description   

The Timestampable Listener only sets the timestamp if the timestamp field has not been modified:

if ( ! isset($modified[$createdName])) {
  $event->getInvoker()->$createdName = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection());
}

When saving a copy of a Doctrine_Record that doesn't already have the timestamp fields set fails to be updated, leading to integrity constraint violation ("created_at cannot be NULL"). The reason is that all unset fields in the copy are set to an instance of Doctrine_Null, which is considered to be modifed according to the condition tested for above. To fix the issue, I modified the code above to read:

if ( ! isset($modified[$createdName]) || $modified[$createdName] instanceof Doctrine_Null) {
  $event->getInvoker()->$createdName = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection());
}


 Comments   
Comment by blopblop [ 06/Sep/12 ]

Your fix works great, I have also added the fix for the preupdate function and in one more place in the preinsert function.
Lines affected: 65, 73, 91.
Attached the file with the fixes:
( C:\php5\PEAR\symfony\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Template\Listener\Timestampable.php )

[code]
/**

  • Set the created and updated Timestampable columns when a record is inserted
    *
  • @param Doctrine_Event $event
  • @return void
    */
    public function preInsert(Doctrine_Event $event)
    {
    if ( ! $this->_options['created']['disabled'])
    Unknown macro: { $createdName = $event->getInvoker()->getTable()->getFieldName($this->_options['created']['name']); $modified = $event->getInvoker()->getModified(); if ( ! isset($modified[$createdName]) || $modified[$createdName] instanceof Doctrine_Null) { $event->getInvoker()->$createdName = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection()); } }

if ( ! $this->_options['updated']['disabled'] && $this->_options['updated']['onInsert']) {
$updatedName = $event->getInvoker()>getTable()>getFieldName($this->_options['updated']['name']);
$modified = $event->getInvoker()->getModified();
if ( ! isset($modified[$updatedName]) || $modified[$updatedName] instanceof Doctrine_Null)

{ $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); }
}
}

/**
* Set updated Timestampable column when a record is updated
*
* @param Doctrine_Event $evet
* @return void
*/
public function preUpdate(Doctrine_Event $event)
{
if ( ! $this->_options['updated']['disabled']) {
$updatedName = $event->getInvoker()>getTable()>getFieldName($this->_options['updated']['name']);
//echo "updatedName: "; var_dump(updatedName);
$modified = $event->getInvoker()->getModified();
if ( ! isset($modified[$updatedName]) || $modified[$updatedName] instanceof Doctrine_Null) { $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); }

}
}
[/code]
------------------

Also there is another problem too. If you dont disable the widgets of the fields updated_at and created_at, sometimes they are sending the date time information in the $form, and the function preUpdate doesnt update the update_at because the date time has been sent. The best option is to disable the widgets and form validation in global scope, here:
<?php

/**

  • Project form base class.
    *
  • @package dbvui
  • @subpackage form
  • @author Your name here
  • @version SVN: $Id: sfDoctrineFormBaseTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
    */
    abstract class BaseFormDoctrine extends sfFormDoctrine
    {
    public function setup()
    {
    //Following code will remove Required validators from these fields.
    if (isset($this->validatorSchema))
    {
    if (isset($this->validatorSchema['created_at'])) { unset($this->validatorSchema['created_at']); }

if (isset($this->validatorSchema['updated_at']))

{ unset($this->validatorSchema['updated_at']); }

}

if (isset($this->widgetSchema))
{
//following code will remove fields from form
if (isset($this->widgetSchema['created_at']))

{ unset($this->widgetSchema['created_at']); }

if (isset($this->widgetSchema['updated_at']))

{ unset($this->widgetSchema['updated_at']); }

}
}
}

Comment by blopblop [ 06/Sep/12 ]

fixed





[DC-396] Add timezone support for time and timestamp datatype in PostgreSQL Created: 05/Jan/10  Updated: 19/Aug/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.1
Fix Version/s: None

Type: New Feature Priority: Major
Reporter: Vladislav Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None

Attachments: File timestampable.diff    

 Description   

Please add support for the types of time with timezone and timestamp with timezone in the Doctrine when using PostgreSQL.



 Comments   
Comment by Alex Potter [ 19/Aug/12 ]

I came across this problem because I prefer to store timezone information instead of local dates.

I believe this is resolved by the attached patch, which patches the Timestampable template and it's listener to create and maintain 'timestamp with timezone' in Postgresql.





[DC-946] Oracle Doctrine_RawSql()->count() generates illegal SQL Created: 08/Dec/10  Updated: 06/Aug/12

Status: Open
Project: Doctrine 1
Component/s: Native SQL
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Lars Pohlmann Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: oracle


 Description   

Example RawSQL:

$q = new Doctrine_RawSql();
    $q->select('{k.*}')
          ->from('SHP_MANDANT_KATEGORIE k')
          ->addComponent('k', 'ShpMandantKategorie k')
          ->where( 'k.id_mandant=' . $this->getIdMandant() )
          ->andWhere( 'k.id_parent=' . $this->getIdMandantkategorie() )
          ->andWhere( 'k.aktiv=1' )
          ->orderBy( 'k.sortorder' ); 

$q->count() generates:

SELECT COUNT(*) as num_results 
FROM (SELECT DISTINCT k.id_mandantkategorie 
              FROM SHP_MANDANT_KATEGORIE k 
              WHERE k.id_mandant=2 AND k.id_parent=1520 AND k.aktiv=1) as results

The illegal Part ist the "as results" at the end...



 Comments   
Comment by Lars Pohlmann [ 06/Aug/12 ]

Hi,

will this ever be corrected?
I just came across the same bug in another project...





[DC-1058] Warning: Invalid argument supplied for foreach() in SqlWalker.php line 899 Created: 29/Jul/12  Updated: 29/Jul/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Alexander Cucer Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: paginator
Environment:

Linux, Ubuntu 12, php 5.4



 Description   

Hallo, i get the error
Warning: Invalid argument supplied for foreach() in /var/www/phverbose/vendor/doctrine/Doctrine/ORM/Query/SqlWalker.php line 899

Here is the line
foreach ($assoc['relationToTargetKeyColumns'] as $relationColumn => $targetColumn) {

Here are the relations and the query
http://pastie.org/4352511
http://pastie.org/4352498

Here is the dump of $assoc before warning

array(16) {
["fieldName"]=>
string(5) "sites"
["joinTable"]=>
array(0) {
}
["targetEntity"]=>
string(13) "Entities\Site"
["mappedBy"]=>
string(6) "emails"
["inversedBy"]=>
NULL
["cascade"]=>
array(1)

{ [0]=> string(7) "persist" }

["orphanRemoval"]=>
bool(false)
["fetch"]=>
int(2)
["type"]=>
int(8)
["isOwningSide"]=>
bool(false)
["sourceEntity"]=>
string(14) "Entities\Email"
["isCascadeRemove"]=>
bool(false)
["isCascadePersist"]=>
bool(true)
["isCascadeRefresh"]=>
bool(false)
["isCascadeMerge"]=>
bool(false)
["isCascadeDetach"]=>
bool(false)
}






[DC-617] migration problem Created: 06/Apr/10  Updated: 22/Jun/12

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: MichalKJP Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

Symfony 1.4.3, Linux, PostgreSQL, Pgpool II


Attachments: File testcase.tar.bz2    

 Description   

I attached a testcase that reproduces all problem that I noticed (previously reported in "serious symfony doctrine:migrate issues - symfony 1.4" on symfony-dev)

There is a problem with an empty ON UPDATE when migrate to version 5

  • SQLSTATE[42601]: Syntax error: 7 BŁĄD: błąd składni w lub blisko "ON"
    LINE 1: ... (object_c_id) REFERENCES object_c(id) ON UPDATE ON DELETE ...
    ^. Failing Query: "ALTER TABLE object_b ADD CONSTRAINT object_b_object_c_id_object_c_id FOREIGN KEY (object_c_id) REFERENCES object_c(id) ON UPDATE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE"

When migrateing from 5 to 3
Failing Query: "DROP INDEX object_b_object_c_id_idx" - this index doesn't exist - should be "object_b_object_c_id"

Also
$this->changeColumn('object_a', 'name', 'string', '2048', array(
));
$this->changeColumn('object_b', 'name', 'string', '2048', array(
));
doesn't work for me



 Comments   
Comment by Ludo [ 08/Sep/10 ]

My own Quick Fix for DROP INDEX (into Export class)
Skip Formatter->getIndexName() in Export->dropIndex()
see : http://www.pastie.org/1145916

Comment by MichalKJP [ 08/Sep/10 ]

I already tested this solution and I can confirm that also works for me.

I am afraid that Johnatan spends much time on the new version and did not have time to correct these bugs for the old version. So we still repair migrations manualy.

Comment by James Bell [ 22/Jun/12 ]

We've had this issue for a while - while Ludo's fix does work, there is an SQL injection issue in that the '$name' doesn't get escaped.

You can do this: $name = $this->conn->quoteIdentifier($name); which also steps around the issue for now.

The problem appears to be that the indexes aren't being created with the _idx string on the end when using the migrations. This is probably down to the index creation process rather than the index removal process.





[DC-1055] Bug in select query when executed against postgreSQL Created: 25/May/12  Updated: 25/May/12

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Damian Bergantinnos Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony-1.4.17 php 5.3.5 apache 2.2.17 WIndows xp/7 PostgreSQL 9.1.2


Attachments: File schema.rar    

 Description   

In the attached Squema run this query against postgreSQL.
(it runs ok In mysql)

$lang = 'en';
$session = 1;
$q = Doctrine_Query::create()
->from('Sys_Trace t')
->leftJoin('t.Sys_Session s')
->leftJoin('t.Translation tr WITH tr.lang = ?', array($lang))
->leftJoin('t.Sys_Oper so')
->leftJoin('so.Translation tr2 WITH tr2.lang = ?', array($lang))
>where('t.session_id = ?', array($session));

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "en"






[DC-801] Multiple template implementation (setImpl) Created: 28/Jul/10  Updated: 28/Apr/12

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: B. Ariston Darmayuda Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None


 Description   

I feel curios when looking setImpl code on Doctrine. It set like this:

public function setImpl($template, $class)
{
    $this->_impl[$template] = $class;

    return $this;
}

I've made a template:

class PersonTemplate extends Doctrine_Template
{
    public function setTableDefinition() 
    {
        //... Person fields (e.g. name, address, etc.)
    }
}

Now I create 2 class that implement PersonTemplate

class Student extends Doctrine_Record
{
    public function setUp()
    {
        $this->actAs('PersonTemplate');
    }
}
class Teacher extends Doctrine_Record
{
    public function setUp()
    {
        $this->actAs('PersonTemplate');
    }
}

Then I set implementation on Doctrine_Manager:

Doctrine_Manager::getInstance()->setImpl('PersonTemplate', 'Student')->setImpl('PersonTemplate', 'Teacher');

Now isn't it only Teacher record recognized as implementation of PersonTemplate ( when we see from this code: $this->_impl[$template] = $class; )

So how we can implement a template into seperated different doctrine record?



 Comments   
Comment by Richard C. Hidalgo [ 28/Apr/12 ]

As the doc says "Tip The implementations for the templates can be set at manager, connection and even at the table level." it is supposed one can do:

Doctrine_Manager::getInstance()->getTable('Student')->setImpl('PersonTemplate', 'Student');
Doctrine_Manager::getInstance()->getTable('Teacher')->setImpl('PersonTemplate', 'Teacher');

but for me it throws an exception:

"Couldn't find concrete implementation for template PersonTemplate"

thx





[DC-919] Import/Pgsql.php: listTableColumns - SQL failure with PostgreSQL Created: 07/Nov/10  Updated: 09/Apr/12

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Christian Vogel Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 4
Labels: None
Environment:

Postgres Import Schema


Attachments: File trac_9152_patch_for_Pgsql.php.diff    

 Description   

Hi,

this issue was reported at the symfony project which uses Doctrine 1.2.3:
http://trac.symfony-project.org/ticket/9152
"php symfony doctrine:build-schema failure with PostgreSQL for 1.4.7 and 1.4.8 version"

The SQL Statement 'listTableColumns' fails with an SQL-Error "missing from-clause"
http://trac.doctrine-project.org/browser/tags/1.2.3/lib/Doctrine/Import/Pgsql.php#L96
I can reproduce the error directly in psql or pgadmin. The SQL Statement seems related to DC-697

Even when i turn on the add_missing_from option on the postgres-server it fails with "missing relation".

Now it seems to me, you already fixed this bug in the current 1.2 branch, because the current SQL-Statement is different and it works for me in psql/pgadmin.
http://trac.doctrine-project.org/browser/branches/1.2/lib/Doctrine/Import/Pgsql.php#L96

Could you please close this ticket, if you already fixed this issue, or confirm if it's still an issue?
Attached you find my proposed patch at the symfony project . the current statement in the branch looks too different from my version, so i am not sure to use this patch directly. Tell me if I should work out a proper patch.

error
SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "t"                                               
 	  LINE 6: ...                                                  t.typtype ...                                                       
 	                                                               ^. Failing Query: "SELECT                                           
 	                                                       ordinal_position as attnum,                                                 
 	                                                       column_name as field,                                                       
 	                                                       udt_name as type,                                                           
 	                                                       data_type as complete_type,                                                 
 	                                                       t.typtype AS typtype,                                                       
 	                                                       is_nullable as isnotnull,                                                   
 	                                                       column_default as default,                                                   
 	                                                       (                                                                           
 	                                                         SELECT 't'                                                                 
 	                                                           FROM pg_index, pg_attribute a, pg_class c, pg_type t                     
 	                                                           WHERE c.relname = table_name AND a.attname = column_name                 
 	                                                           AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid           
 	                                                           AND c.oid = pg_index.indrelid AND a.attnum = ANY (pg_index.indkey)       
 	                                                           AND pg_index.indisprimary = 't'                                         
 	                                                           AND format_type(a.atttypid, a.atttypmod) NOT LIKE 'information_schema%' 
 	                                                       ) as pri,                                                                   
 	                                                       character_maximum_length as length                                           
 	                                                     FROM information_schema.COLUMNS                                               
 	                                                     WHERE table_name = 'matable'                                   
 	                                                     ORDER BY ordinal_position"  


 Comments   
Comment by Nahuel Alejandro Ramos [ 09/Nov/10 ]

We apply the diff patch you submit and works perfect. We are using Doctrine 1.2.3 with PostgreSQL 8.4.
We could generates models from database with generateModelsFromDb() method.
Please add this patch to a new release.
Thank you very much.

Comment by Tim Hemming [ 23/Nov/10 ]

We have applied this patch directly to our server-wide Doctrine library and it works fine. We look forward to it becoming a part of the Doctrine distribution.

Comment by Christopher Hotchkiss [ 19/Dec/10 ]

I can confirm that this bug also affects symfony 1.4.8 and the attached fix works perfectly!

Comment by David Landgren [ 21/Feb/11 ]

Confirmed to fix crash with symfony 1.3.8

Comment by Cesar Miggiolaro [ 09/Apr/12 ]

I use the version 1.4.17 and also had the error with postgres 9.1. Applying the correction suggested in DIFF. The system worked.





[DC-1054]  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'b.title' in 'field list' Created: 31/Mar/12  Updated: 31/Mar/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: suriyakala Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None
Environment:

window vista



 Description   

this is the my table creation .

CREATE TABLE billboard(id BIGINT AUTO_INCREMENT,title VARCHAR (255),country_id BIGINT,zone_id BIGINT,place VARCHAR(255),occassion VARCHAR(255),itinerary VARCHAR(255),created_at DATETIME NOT NULL,description TEXT NOT NULL,PRIMARY KEY(id)) ENGINE=INNODB;

public static function getInstance()

{ return Doctrine_Core::getTable('Billboard'); }

this is the my Doctrine Table

// public function getBillboardsForAUser($userId, $limit, $offset=0)
public function getBillboardsForAUser($userId,$limit,$offset=0)
{
$query = $this->createQuery('b')
->where('b.title=?',$title);
// ->where('b.owner_id = ?', $userId);
$followings = Doctrine::getTable('Follow')->getAllFollowing($userId);
foreach($followings as $following)

{ $query->orWhere('b.owner_id = ? ',$following->getOwnerId()); $query->orWhere('b.poster_id = ? ',$following->getOwnerId()); }

$query->orderBy('b.created_at DESC')
->limit($limit)
->offset($offset);
return $query->execute();

}

plz help me what is the problem.



 Comments   
Comment by Benjamin Eberlei [ 31/Mar/12 ]

Doctrine 1, not 2 ticket.





[DC-1031] CLONE -Multiple connections and i18n (raised as unresolved - original ticket marked as resolved) Created: 23/Aug/11  Updated: 28/Mar/12

Status: Open
Project: Doctrine 1
Component/s: Connection, I18n
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: 1.2.3

Type: Bug Priority: Blocker
Reporter: James Bell Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

MySQL 5.1.37
PHP 5.2.11
symfony 1.2.11 DEV

symfony 1.4.13
PHP 5.3.6
Postgres 8.4.8



 Description   

I used to work with a single database named "doctrine". The query was working properly.

I then decided to use 2 databases so I got my schema like this:

connection: doctrine

Category:
actAs:
I18n:
actAs:
Sluggable:
fields: [name]
Timestampable: ~
fields: [name, description]
columns:
id: ~
name:
type: string(255)
notnull: true
description: string

User:
connection: second
columns:
id: ~
name:
type: string(255)
notnull: true

I did setup my connections in config/databases.yml this way:

all:
doctrine:
// ....
second:
// ....

build-model, build-forms, build-filters and cc got ran. But now, I got an exception saying the "Translation" relation doesn't exist. The Base Models include correctly the bindComponent line:

Doctrine_Manager::getInstance()->bindComponent('Category', 'doctrine');

For now, I managed to kind of fixing it with simply swapping the databases order in my config/databases.yml and it's now working again perfectly.

I forgot to mention that in the CategoryTable when i call $this->getConnection()->getName(), it outputs "second"



 Comments   
Comment by James Bell [ 23/Aug/11 ]

Original issue: DC-363 (http://www.doctrine-project.org/jira/browse/DC-363)

There are some additional comments in there that explain the issue as currently being seen in released versions of Doctrine 1.2. Can I help verify that this is the same ticket?

What is needed to help with debug (in addition to the extra information already provided)?

Comment by Andy.L [ 28/Mar/12 ]

meet the same issue and it really blocked my project, seems no one will maintain 1.x. I'm considering whether to replace symfony 1.4 with 2.0.





[DC-1053] Renaming a doctrine 'string' field may result in loss of data as the field's type changes. (MySQL) Created: 26/Mar/12  Updated: 26/Mar/12

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Ben Lancaster Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.3.5-1ubuntu7.2ppa1~lucid with Suhosin-Patch (cli) (built: May 7 2011 03:12:27)
Zend Engine v2.3.0
Xdebug v2.0.5
Turnkey LAMP 10.04 LTS x86_64
Symfony 1.4.11
mysql Ver 14.14 Distrib 5.1.41, for debian-linux-gnu (i486) using readline 6.1



 Description   

Consider the following schema:

schema.yml
MyTable:
  columns:
    some_text:        string

Doctrine creates the table with:

CREATE TABLE `my_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `some_text` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, the following migration should rename the field from some_text to just_text:

<?php
class Version1 extends Doctrine_Migration_Base
{
    public function up()
    {
        $this->renameColumn('my_table', 'some_text', 'just_text');
    }

    public function down()
    {
      $this->renameColumn('my_table', 'just_text', 'some_text');
    }
}

...however the field gets renamed and the type becomes VARCHAR(255), as the resulting SHOW CREATE TABLE my_table shows:

CREATE TABLE `my_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `a_varchar` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Causes data in the column greater than 255 bytes to get truncated






[DC-1052] limit() get lost on multiple joins Created: 20/Mar/12  Updated: 20/Mar/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Michael Kempf Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

$strSql = UserFeedTable::getInstance()>createQuery('q')>
select('q., f., fi., fav.')->
leftJoin('q.Feed f')->
leftJoin('f.FeedItem fi')->
leftJoin('fi.Favorite fav')->
andWhere('q.profile_id = ?', $intUserId)->
andWhere('q.is_active = ?', true)->
limit(10)->getSqlQuery();
var_dump($strSql);

string(1075) "SELECT u.id AS u_id, u.name AS uname, u.image AS uimage, u.lead AS ulead, u.headline AS uheadline, u.sort AS usort, u.is_active AS uis_active, u.is_favorite AS uis_favorite, u.feed_id AS ufeed_id, u.profile_id AS uprofile_id, u.category_id AS ucategory_id, u.created_at AS ucreated_at, u.updated_at AS uupdated_at, f.id AS fid, f.url AS furl, f.name AS fname, f.created_at AS fcreated_at, f.updated_at AS fupdated_at, f2.id AS f2id, f2.lead AS f2lead, f2.description AS f2description, f2.image AS f2image, f2.pub_date AS f2pub_date, f2.link AS f2link, f2.feed_id AS f2feed_id, f2.created_at AS f2created_at, f2.updated_at AS f2updated_at, f3.id AS f3id, f3.profile_id AS f3profile_id, f3.feed_item_id AS f3feed_item_id, f3.created_at AS f3created_at, f3.updated_at AS f3_updated_at FROM user_feed u LEFT JOIN feed f ON u.feed_id = f.id LEFT JOIN feed_item f2 ON f.id = f2.feed_id LEFT JOIN favorite f3 ON f2.id = f3.feed_item_id WHERE u.id IN ('7', '8', '9', '10', '11') AND (u.profile_id = ? AND u.is_active = ?)"

As you can see, the limit is missing.






[DC-585] Hydrate Array does not return full array, when Hydrate Scalar does Created: 18/Mar/10  Updated: 02/Mar/12

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: James Solomon Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 4
Labels: None
Environment:

OS : Ubuntu 9.04
PHP : PHP 5.2.6-3ubuntu4.5


Attachments: Text File Doctrine-DC-585-b.patch     Text File Doctrine-DC-585-c.patch    

 Description   

Description : Upon hydrating as array I will receive one row returned. If I am to hydrate as Scalar, I will get 200+ rows. Also, if i echo the sql ($q->getSqlQuery()) and run that raw, it will also return around 200+ rows.

$q = Doctrine_Query::create()
->select('DISTINCT(co.name) AS field, co.name AS value')
->from('Model_Country co')
->leftJoin('co.City ci');

//here we will get only the first row
$results = $q->execute(array(), Doctrine::HYDRATE_ARRAY);

//Here we will get all 200+ rows
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);

I have yet to dig to deep into this, but if it is indeed a bug, my guess is it is in Doctrine_Hydrator_Graph::hydrateResultSet()

I can provide more data if needed.



 Comments   
Comment by James Solomon [ 18/Mar/10 ]

I have found this in the google group, and he provides more detailed info, and appears to be the same exact issue : http://groups.google.com/group/doctrine-user/msg/8e4a8a673428fff0

Comment by James Solomon [ 18/Mar/10 ]

seems to be another similar issue here : http://www.doctrine-project.org/jira/browse/DC-328

Comment by Juan Antonio Galán [ 19/May/10 ]

I'm having that problem and I taked a look into the code, found this:

I have a query that looks like this:
$q = Doctrine_Query::create()
->select('af.id as id, af.user_id as user')
->from('ActivityFeed af')
->innerJoin('af.user as afu')
->orderBy('af.time DESC');

The sql query without aliases in SELECT or without join is built that way:
SELECT a.id AS a_id, a.user_id AS a_user_id ... -> This is returning all the records

The sql query with aliases in SELECT is built that way:
SELECT a.id AS a_0, a.user_id AS a_1 FROM ... -> This is returning only one record

In Doctrine_Hydrator_Graph::_gatherRowData, line 288 there's the following call:

$fieldName = $table->getFieldName($last);
Where $last is the last part of the column alias, for example "0" in "a__0". This way the call asks the table for the name of the "0" field and the table returns "0" so I think we're not getting the right field name (it must be "id").

I'm not understanding the whole hydration process but replacing

$fieldName = $table->getFieldName($last);

with:

if(isset($this->_queryComponents[ $cache[$key]['dqlAlias']]['agg']))

{ $fieldName = $table->getFieldName($this->_queryComponents[ $cache[$key]['dqlAlias']]['agg'][$last]); }

else

{ $fieldName = $table->getFieldName($last); }

solves the problem almost in my case.

Hope it will help to solve the issue.

Comment by Jonathan H. Wage [ 08/Jun/10 ]

It seems the suggested change causes many failures in our test suite. Can you give it a try and confirm?

Comment by Ben Davies [ 28/Jul/10 ]

Just commenting to say that I can confirm this bug exists. It's happening for me too.
I will try and dig deeper when I have some time.

Comment by Juan Antonio Galán [ 28/Aug/10 ]

As the error is located in Doctrine_Hydrator_Graph, HYDRATE_RECORD has the same behaviour.

I'm trying to find a solution.

Comment by Ben Davies [ 31/Aug/10 ]

This only occurs if your alias your identifier field.
Doctrine needs to know which field is the identifier to hydrate records.
The identifier aliases is formed to x__0, and then, as other commented has found.
Doctrine then has no way of determining which field is the identifier.

Comment by Enrico Stahn [ 15/Oct/10 ]

Hi everybody,

we really need a unit test here. The provided patch breaks all aliased queries in our application. I will provide a patch and it hopefully solves your problem Juan. If not, please provide more information or add another test-method to the provided unit test.

I had to rewrite some of the unit tests cause the order of the fields in the generated sql statement has changed due the provided patch.

Enrico

http://github.com/doctrine/doctrine1/commit/e3ae69c2260dae6dfbceb4e24138b2379f3da2e6#commitcomment-169495
http://github.com/estahn/doctrine1/tree/DC-585

Comment by Pierrot Evrard [ 04/Mar/11 ]

Hi,

I have a little issue with this bug report...

I'm currently using Doctrine 1.2 at revision 7691, and I've encounter a bug when select the primary key of a model with a custom alias (typically $query->addSelect( 'r.id as my_id' )), the issue was that Doctrine automatically add `r`.```id``` AS `r_1` to the select clause, in addition to the correct `r`.`id` AS `r_1` part.

So, I've browse the code to finally found where does this strange thing comes from, and I've found it on Doctrine_Query::parseSelect() method, just at the line 663:

// Fix for http://www.doctrine-project.org/jira/browse/DC-585
// Add selected columns to pending fields
if (preg_match('/^([^\(]+)\.(\'?)(.*?)(\'?)$/', $expression, $field)) {
$this->_pendingFields[$componentAlias][$alias] = $field[3];
}

So I'm wonder : where does this patch is related to this bug report?

Whatever, the bug I've encounter is very simple : the regular expression that extract the field name takes care about ' but not ´.

You will find a patch for the bug DC-585-b in a few minutes... This patch just make the regular expression taking account of ' and ´ and also remove all useless parentheses in expression (by this way PCRE get less matches to capture and we can earn some precious microseconds).

Also, this patch should be completed because the query still have two `r`.`id` AS `r_1` parts, that may cause some other issues with some databases...

IMPORTANT NOTE: The previous revision 7674 of Doctrine_Query does not cause the bug encounter with the few lines of code above, just because they were not there. They really must be review.

Loops

Comment by Pierrot Evrard [ 28/Apr/11 ]

Damn, the bug above was corrected during a few weeks and comes back with the new branch of Doctrine 1.2.14.

Does anybody can re-apply the corrective patch (renamed DC-585-c), please ?

I repeat it agin, but these few lines of code really need to be review.

Loops

Comment by klemen nagode [ 13/Jan/12 ]

I also have this problem .. Anyone know howt o fix it?

$query->execute(array(), Doctrine::HYDRATE_ARRAY); // returns one row only
$query->execute(array(), Doctrine::HYDRATE_RECORD); // returns one row only

$query->execute(array(), Doctrine::HYDRATE_SCALAR); // returns result as expected

Comment by klemen nagode [ 14/Jan/12 ]

I found solution for my problem:

Table had ID field but it was not primary key. When I deleted this column, doctrine started to work as expected.

Comment by Lacton [ 02/Mar/12 ]

I have run into the same issue.

Using the default hydration, I get only one record.

Using "$query->execute(array(), Doctrine::HYDRATE_SCALAR);", I get all the expected records.





[DC-1047] hardDelete not resetting flag if exception is thrown Created: 06/Jan/12  Updated: 06/Jan/12

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Lone Wolf Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File softdelete_exception.patch    

 Description   

To be honest I don't know wich version I have but I believe it to be 1.2.3

The problem is pretty simple, I was trying to do a hardDelete and if it fails I would do a softDelete.
Example

try {
    $record->hardDelete();
}
catch (Exception $e) {
    if ($e instanceof Doctrine_Connection_Mysql_Exception && $e->getPortableCode() == Doctrine_Core::ERR_CONSTRAINT) {
        try {
            $record->delete();
        }
        catch (Exception $e1) {
            throw $e1;
        }
    }
    else {
        throw $e;
    }
}

But when the first exception is thrown from hardDelete() in Doctrine_Template_SoftDelete(line 84) the listener flag for hardDelete is not set to false, so if I try to do the delete, it will still behave as if it was a hardDelete.

The solution would be catch the exception, reset the flag and rethrow it.
Patch attached

Hope this info is enough.






[DC-1045] data-load with invalid filename leads to purging of all the data in the database Created: 06/Dec/11  Updated: 06/Dec/11

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Keszeg Alexandru Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony 1.4


Attachments: Text File diff.patch    

 Description   

Adding an invalid filename to the data-load task results in purging of all the data in the database.

I am attaching a patch that checks the loaded data if there were any values actually loaded from the fixtures.






[DC-1044] record Line 2430 Unlink method Warning: Illegal offset type in sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record.php on line 2459 Created: 05/Dec/11  Updated: 05/Dec/11

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Kyle Clarke Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None


 Description   

When you have a new unpersisted object and you call a method to a referenced object - when calling the unlink() method on referenced object the above error is called.

Warning: Illegal offset type in sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record.php on line 2459

eg

$foo = new foo();

$foo->getBar(); This call will bind a reference of Bar against the foo object.

$foo->unlink('bar');

As no objects are yet persisted, the unlink method tries to match ids on the objects that do not exist.






[DC-1043] Error:"When using..ATTR_AUTO_ACCESSOR_OVERRIDE you cannot.. name "data" ..." when running doctrine:build-schema ... except I'm NOT using that word Created: 30/Nov/11  Updated: 01/Dec/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Maurice Stephens Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Mac OSX 10.6.8 running MAMP Pro 2.0.5 with PHP 5.3.6 ... this is a local symfony install which is also using the apostrophe cms.



 Description   

Was able to resolve this - see comment below - but still think it counts as a bug since the source of the error is so unclear

Hello,
I'm familiarizing myself with symfony at this point, but doctrine seems like a very accessible ORM tool overall. This install will also use the apostrophe plugin though that is more a client request and it is seeming to complicate a lot of issues from what I can see. Right now, I am just trying to create some db tables in schema.yml and build them with doctrine. When running $ php symfony doctrine:build-schema I get the following error: When using the attribute ATTR_AUTO_ACCESSOR_OVERRIDE you cannot use the field name "data" because it is reserved by Doctrine. You must choose another field name.

Which would be clear enough except I'm NOT using "data" as a field name in my schema file: here's what I'm using:

sfTravelLodgingLocationsType:
columns:
lodging_name:

{ type: string(255) }

lodging_code:

{ type: string(255) }

sfTravelLodgingLocations:
columns:
lodging_type_code:

{ type: integer, notnull: true }

name:

{ type: string(255), notnull: true }

address:

{ type: string(255), notnull: true }

city:

{ type: string(255), notnull: true }

distance:

{ type: integer, notnull: true }

phone:

{ type: string(255), notnull: true }

known_2b_sold_out:

{ type: boolean, notnull: true, default: 0 }

relations:
Travel_Lodging_LocationsType:

{ local: type_id, foreign: id }

I'm assuming this is a misnamed error call ... I have found a few references to that same error in other threads but none that resolve it



 Comments   
Comment by Maurice Stephens [ 01/Dec/11 ]

I was able to find a way to override the ATTR_AUTO_ACCESSOR_OVERRIDE with a method in the appConfiguration.class.php file

based on this thread ... http://stackoverflow.com/questions/7266293/attr-auto-accessor-override

But it is still a difficult error to troubleshoot ... not clear on what the reserved keyword "data" had to do with it ... considering I wasn't even using it in the schema

Would be interested in finding some resources that go into detail on the implications of the command line context that symfony relies on





[DC-1042] submitted form accidentally - PLEASE DELETE Created: 30/Nov/11  Updated: 30/Nov/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Trivial
Reporter: Maurice Stephens Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

This was accidentally submitted before being complete ... This one can be deleted ... sorry



 Comments   
Comment by Maurice Stephens [ 30/Nov/11 ]

This was accidentally submitted before being complete ... This one can be deleted ... sorry





[DC-1041] Using ->limit() in conjunction with many-to-many with mysql generates wrong SQL Created: 30/Nov/11  Updated: 30/Nov/11

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Evgeniy Afonichev Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

mysql



 Description   

Using ->limit() in conjunction with many-to-many relationships with mysql leads to strange SQL generated. The condition id IS NULL is added in such case which is not correct at all.

Here's example schema

User:
  columns:
    username: { type: string(255) }
  relations:
    Operators:
      foreignAlias: Users
      class:        Operator
      refClass:     OperatorUser

Operator:
  columns:
    username: { type: string(255) }
    type:     { type: integer }


OperatorUser:
  columns:
    user_id:      { type: integer }
    operator_id:  { type: integer }
  relations:
    Operator:
      foreignAlias: OperatorUser
    User:
      foreignAlias: OperatorUser

And here's query which generates wrong SQL

Doctrine_Core::getTable('User')
  ->createQuery('User')
  ->leftJoin('User.Operators Operator')
  ->addWhere('Operator.type = ?', 1)
  ->limit(10)
  ->offset(0)
  ->execute()
;

Expected SQL generated:

SELECT u.id AS u__id, u.username AS u__username, o.id AS o__id, o.username AS o__username, o.type AS o__type
FROM user u
LEFT JOIN operator_user o2  ON (u.id = o2.user_id)
LEFT JOIN operator o        ON o.id = o2.operator_id
WHERE (o.type = '1')
LIMIT 10

Actual SQL generated:

SELECT u.id AS u__id, u.username AS u__username, o.id AS o__id, o.username AS o__username, o.type AS o__type
FROM user u
LEFT JOIN operator_user o2  ON (u.id = o2.user_id)
LEFT JOIN operator o        ON o.id = o2.operator_id
WHERE
  u.id IS NULL # is not expected
  AND (o.type = '1')
# there's no LIMIT clause

Seems like here's code which causes the bug https://github.com/doctrine/doctrine1/blob/master/lib/Doctrine/Query.php#L1307






[DC-934] One-to-one relationship with cascading deletion and softdelete creates empty records Created: 21/Nov/10  Updated: 29/Nov/11

Status: Open
Project: Doctrine 1
Component/s: Record
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Rich Sage Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Ubuntu 10.10, PHP 5.3.3


Attachments: File testcase.php    

 Description   

When using softdelete behaviour with cascading deletion on a one-to-one relationship, Doctrine will create a 'child' record if it doesn't exist already, during the cascading deletion. Eg:

  • Models Foo, Bar, both SoftDelete
  • Foo hasOne Bar
  • $myFoo->delete()

Result is:

  • $myFoo->deleted_at is set correctly as expected
  • New Bar record is created & saved in the process (but is not set to deleted)

Is this expected behaviour? I've attached a test case script, tested against export from SVN of Doctrine 1.2.3 that demonstrates this.



 Comments   
Comment by marius [ 29/Nov/11 ]

I can confirm this issue on Ubuntu 11.10 PHP 5.3.6-13ubuntu3.2





[DC-1040] allow queries with table joins across different databases Created: 17/Nov/11  Updated: 17/Nov/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: 1.2.3

Type: Improvement Priority: Blocker
Reporter: Fabrice Agnello Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows XP SP3, Apache 2, PHP 5.3, MySQL 5.1.36, Symfony 1.4.8, Doctrine 1.2.3


Attachments: File Query.php    

 Description   

I'm currently working on a project which relies upon several databases declared in databases.yml in symfony 1.4.8.

I was facing an issue that has already been raised by other people, namely that you can't join tables which reference each other among different mysql databases.

I've dug a bit in the Doctrine_Query class and came to a solution that is acceptable for us, and allows now to make joins accross databases. Description follows :

first change is in the Doctrine_Core class, that gets stuffed with a new constant :
const ATTR_DATABASE_NAME = 0x1DB;

this constant allows us to add a new attribute to the databases.yml file as in :
gesdoc:
class: sfDoctrineDatabase
param:
dsn: mysql:host=127.0.0.1;dbname=gesdoc
username: root
password:
attributes:

  1. ************* NEW ATTRIBUTE BELOW ************
    database_name: gesdoc
    default_table_collate: utf8_general_ci
    default_table_charset: utf8

after that, a few changes have been done in the Doctrine_Query class which is attached to this issue for the sake of readability.

This may not be optimal, and probably need some regression testing, but it is currently working fine on our test server.

after this is done, I was able to issue queries like the following :
$x = DocumentTable::getInstance()->createQuery('d')
->distinct()
->leftJoin('d.Travail t')
->leftJoin('t.CdcIndInt ci')
->leftJoin('ci.CdcIndExt ce')
->leftJoin('ce.Cahierdescharge cdc')
->where('cdc.cdc_chro = ?', $cdc_chro)
->addWhere('d.id != ?', $document_id)
->execute();

where the referenced tables are in different databases. The necessary object binding has been done in every model class following the paradigm :

Doctrine_Manager::getInstance()->bindComponent('CdcIndInt ', 'gescdc');
abstract class BaseCdcIndInt extends sfDoctrineRecord
{
...
}

I don't know if this description is clear enough, so let me know if something is missing/wrong.






[DC-914] Doctrine_Pager ignores custom COUNT query Created: 02/Nov/10  Updated: 07/Nov/11

Status: Open
Project: Doctrine 1
Component/s: Pager
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Arnoldas Lukasevicius Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Zend Server CE



 Description   

I found some problem when I tried to define custom query for results counting. Defined custom COUNT query is totally ignored and executed default one. I will give you full description of problem bellow.

We have following source code:

 
$q_select = Doctrine_Query::create ()
->select ( 'DISTINCT p.product_name AS product_name' )
->from ( 'Product p' )
->where( 'p.product_name LIKE ?', '%motorola%');
				
$q_count = Doctrine_Query::create ()
->select ( 'COUNT (DISTINCT p.product_name) num_results' )
->from ( 'Product p' )
->where( 'p.product_name LIKE ?', '%motorola%');
												
$pager = new Doctrine_Pager( $q_select, 1, 25 );										
$pager->setCountQuery($q_count);

Let's check custom query before calling $pager->execute() method:

 
echo $pager->getCountQuery(); 

Output:

 
SELECT COUNT (DISTINCT p.product_name) num_results FROM Product p WHERE p.product_name LIKE ?

Looks like until now is everything is correct. Let's call $pager->execute() method:

 
$products = $pager->execute(); 

Let's check executed queries using Symfony SQL queries log panel:

SELECT COUNT(*) AS num_results FROM product p WHERE p.product_name LIKE '%motorola%'
7.27s, "doctrine" connection

SELECT DISTINCT p.product_name AS p__0 FROM product p WHERE (p.product_name LIKE '%motorola%') LIMIT 25
3.25s, "doctrine" connection

Executed COUNT query is not same we set using $pager->setCountQuery($q_count). Our defined custom COUNT query is totally ignored and executed default one:

INSTEAD OF THIS CUSTOM COUNT QUERY:

SELECT COUNT (DISTINCT p.product_name) num_results FROM Product p WHERE p.product_name LIKE '%motorola%'

EXECUTED DEFAULT COUNT QUERY:

SELECT COUNT(*) AS num_results FROM product p WHERE p.product_name LIKE '%motorola%'


 Comments   
Comment by Alex Cardoso [ 07/Nov/11 ]

I found a possible solution to the problem.

That occurs not because the Pager countQuery but in a method used inside the Query class.

When you set the Query or CountQuery for Pager and execute it, it calls a Query method called count(). This method by yourself call another Query class method named Query::getCountSqlQuery().

This method rather than simply execute the query that you passed earlier, simply create a new query.

Below is a possible solution to the problem:

Query.php (Doctrine Stable 1.2.4)


--- Query.php	2011-11-07 20:52:48.000000000 -0200
+++ Query.php	2011-11-07 20:51:58.000000000 -0200
@@ -2049,40 +2049,7 @@
         if (count($this->_queryComponents) == 1 && empty($having)) {
             $q .= $from . $where . $groupby . $having;
         } else {
-
-            // Subselect fields will contain only the pk of root entity
-            $ta = $this->_conn->quoteIdentifier($tableAlias);
-
-            $map = $this->getRootDeclaration();
-            $idColumnNames = $map['table']->getIdentifierColumnNames();
-
-            $pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames));
-
-            // We need to do some magic in select fields if the query contain anything in having clause
-            $selectFields = $pkFields;
-
-            if ( ! empty($having)) {
-                // For each field defined in select clause
-                foreach ($this->_sqlParts['select'] as $field) {
-                    // We only include aggregate expressions to count query
-                    // This is needed because HAVING clause will use field aliases
-                    if (strpos($field, '(') !== false) {
-                        $selectFields .= ', ' . $field;
-                    }
-                }
-                // Add having fields that got stripped out of select
-                preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER);
-                if (count($matches[0]) > 0) {
-                    $selectFields .= ', ' . implode(', ', array_unique($matches[0]));
-                }
-            }
-
-            // If we do not have a custom group by, apply the default one
-            if (empty($groupby)) {
-                $groupby = ' GROUP BY ' . $pkFields;
-            }
-
-            $q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') '
+            $q .= '( '.$this->getSqlQuery().' ) '
                 . $this->_conn->quoteIdentifier('dctrn_count_query');
         }
         return $q;




[DC-1039] Return value of function Doctrine_Tree_NestedSet::fetchRoot($id) Created: 31/Oct/11  Updated: 31/Oct/11

Status: Open
Project: Doctrine 1
Component/s: Documentation
Affects Version/s: None
Fix Version/s: None

Type: Documentation Priority: Trivial
Reporter: Dmitry Artanov Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

In api documentation about Doctrine_Tree_NestedSet::fetchRoot($id) said - it return void. But this is not true. This function return mixed - bool or model data.






[DC-992] I18n - Translated fields are not deleted when record in master table is deleted Created: 03/Apr/11  Updated: 28/Oct/11

Status: Open
Project: Doctrine 1
Component/s: Behaviors
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Thanasis Fotis Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows XP, xampp 1.7.3 (PHP 5.3.1)



 Description   

I have used I18n behavior for my application using the following:

public function setTableDefinition()
{
        $this->setTableName('products');

        $this->hasColumn('id', 'integer', 4, 
            array('fixed' => true, 
                  'primary' => true, 
                  'autoincrement' => true));

        $this->hasColumn('permalink', 'string', 255,
            array('notnull' => true));
        
        $this->hasColumn('title', 'string', 255, 
            array('notnull' => true));
            
        $this->hasColumn('teaser', 'string', 255, 
            array('notnull' => true));
            
        $this->hasColumn('content', 'clob', 32767);
}

public function setUp()
{   
        $this->actAs('I18n', array(
                'fields' => array('title', 'teaser', 'content')
            )
        );
}

Doctrine has created two tables db named products and products_translation.

Insert and update of the record is working fine but when i perform a deletion of a record, the record is deleted from the products table but the translations stored in products translation table are not deleted.



 Comments   
Comment by Justinas [ 28/Oct/11 ]

if you are not using transaction type tables like innoDB you need to set 'appLevelDelete' => TRUE option for I18n
it's not documented feature as i found out.

$this->actAs('I18n', array(
'fields' => array('title', 'teaser', 'content'),
'appLevelDelete' => TRUE,
)
);





[DC-727] ReOpen DC-46 - Unexpected behavior with whereIn() and empty array Created: 11/Jun/10  Updated: 12/Oct/11

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: David Jeanmonod Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 3
Labels: None
Environment:

PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22)
mysql Ver 14.14 Distrib 5.1.41, for apple-darwin9.5.0 (i386) using readline 5.1
Doctrine version 1.2.2 from SVN: http://doctrine.mirror.svn.symfony-project.com/tags/1.2.2/lib/Doctrine.php


Attachments: Text File DC-727_refactored.patch     Text File DC-727_with_duplicates.patch     File DC727TestCase.php     File DC727TestCase_more_specific.php    

 Description   

I reopen the DC-46 as it'seems not fix at all.
When I do a whereIn with empty array, the condition is just drop and I get no Exception.

Here is a simple test case:

require_once('doctrine/lib/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(Doctrine::ATTR_EXPORT, Doctrine::EXPORT_ALL);
$conn = Doctrine_Manager::connection('mysql://root:root@localhost/test_doctrine');
echo "Connection is set up\n";

class Record extends Doctrine_Record {
    public function setTableDefinition(){
        $this->setTableName('record');
    }
}

// Create the db
try {Doctrine::dropDatabases();}catch(Exception $e){} // Drop if exist :-)
Doctrine::createDatabases();Doctrine::createTablesFromArray(array('Record'));

// Test
echo Doctrine::getTable('Record')->createQuery()->select('id')->whereIn('id', array())->getSqlQuery() , "\n";
echo Doctrine::getTable('Record')->createQuery()->select('id')->whereIn('id', array())->fetchArray() , "\n";

// Result is:
// SELECT r.id AS r__id FROM record r
// Array


 Comments   
Comment by Guilliam X [ 16/Jun/10 ]

The problem is that the change for "new" behavior (throw exception instead of return unchanged query) was only done in _processWhereIn() but not cascaded to andWhereIn() and orWhereIn() (another example we should avoid code duplication).
The patch is simple, but it causes Doctrine_Ticket_1558_TestCase to fail. Indeed that (old) test expects the "old" behavior (return unchanged query, don't throw exception)... So the 2 fixes are incompatible, you'll have to choose :/

I still attach a new test case and 2 versions of a patch (the first one just applies changes of _processWhereIn also to the 2 other functions but adds more duplicate code, the second is a little refactored and seems better to me).

Regards

Comment by Guilliam X [ 16/Jun/10 ]

added a more specific test case (expects Doctrine_Query_Exception instead of simple Exception)

Comment by Jan Schütze [ 22/Nov/10 ]

Hi,

the issue is still present in 1.2.3. Are there any plans to apply it?

Kind regards,

Comment by Jim Persson [ 12/Oct/11 ]

I would like to add that this also applies to delete-queries which can cause serious data loss.
We had a case where a table of serialized data was completely emptied which caused a database cascade that deleted quite a lot of data.





[DC-875] One-to-many relationship returns Doctrine_Record instead of Doctrine_Collection Created: 30/Sep/10  Updated: 14/Sep/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Patrik Åkerstrand Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

WAMP:
Windows 7 - 64bit
Apache 2.2
PHP 5.3.1
MySQL 5.1.41



 Description   

I've run into a bit of a snag in my application where a relationship defined as a one-to-many relationship returns a model object (instance of Doctrine_Record) instead of a Doctrine_Collection when I try to access it as $model->RelatedComponent[] = $child1. This, of course, yields an exception like so:

Doctrine_Exception: Add is not supported for AuditLogProperty
#0 path\library\Doctrine\Access.php(131): Doctrine_Access->add(Object(AuditLogProperty))
#1 path\application\models\Article.php(58): Doctrine_Access->offsetSet(NULL, Object(AuditLogProperty))
#2 path\library\Doctrine\Record.php(354): Article->postInsert(Object(Doctrine_Event))
#3 path\library\Doctrine\Connection\UnitOfWork.php(576): Doctrine_Record->invokeSaveHooks('post', 'insert', Object(Doctrine_Event))
#4 path\library\Doctrine\Connection\UnitOfWork.php(81): Doctrine_Connection_UnitOfWork->insert(Object(Article))
#5 path\library\Doctrine\Record.php(1718): Doctrine_Connection_UnitOfWork->saveGraph(Object(Article))
#6 path\application\modules\my-page\controllers\ArticleController.php(26): Doctrine_Record->save()
#7 path\library\Zend\Controller\Action.php(513): MyPage_ArticleController->createAction()
#8 path\library\Zend\Controller\Dispatcher\Standard.php(289): Zend_Controller_Action->dispatch('createAction')
#9 path\library\Zend\Controller\Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#10 path\library\Zend\Application\Bootstrap\Bootstrap.php(77): Zend_Controller_Front->dispatch()
#11 path\library\Zend\Application.php(358): Zend_Application_Bootstrap_Bootstrap->run()
#12 path\public\index.php(11): Zend_Application->run()
{{#13

{main}

}}

This is what my yaml-schema looks like (excerpt):

schema.yml
AuditLogEntry:
  tableName: audit_log_entries
  actAs:
    Timestampable:
      updated: {disabled: true}
  columns:
    user_id: {type: integer(8), unsigned: true, primary: true}
    id: {type: integer(8), unsigned: true, primary: true, autoincrement: true}
    type: {type: string(255), notnull: true}
    mode: {type: string(16)}
    article_id: {type: integer(8), unsigned: true}
    comment_id: {type: integer(8), unsigned: true}
    question_id: {type: integer(8), unsigned: true}
    answer_id: {type: integer(8), unsigned: true}
    message_id: {type: integer(8), unsigned: true}
  indexes:
#   Must index autoincrementing id-column since it's a compound primary key and 
#   the auto-incrementing column is not the first column and we use InnoDB.
    id: {fields: [id]}
    type: {fields: [type, mode]}
  relations:
    User:
      local: user_id
      foreign: user_id
      foreignAlias: AuditLogs
      type: one
      onDelete: CASCADE
      onUpdate: CASCADE
AuditLogProperty:
  tableName: audit_log_properties
  columns:
    auditlog_id: {type: integer(8), unsigned: true, primary: true}
    prop_id: {type: integer(2), unsigned: true, primary: true, default: 1}
    name: {type: string(255), notnull: true}
    value: {type: string(1024)}
  relations:
    AuditLogEntry:
      local: auditlog_id
      foreign: id
      type: one
      foreignType: many
      foreignAlias: Properties
      onDelete: CASCADE
      onUpdate: CASCADE

Now, if we look at the generated class-files, it looks fine:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
/**
 * @property integer $user_id
 * @property integer $id
 * @property string $type
 * @property string $mode
 * @property integer $article_id
 * @property integer $comment_id
 * @property integer $question_id
 * @property integer $answer_id
 * @property integer $message_id
 * @property integer $news_comment_id
 * @property User $User
 * @property Doctrine_Collection $Properties
 * @property Doctrine_Collection $Notifications
 */
abstract class BaseAuditLogEntry extends Doctrine_Record

/**
 * @property integer $auditlog_id
 * @property integer $prop_id
 * @property string $name
 * @property string $value
 * @property AuditLogEntry $AuditLogEntry
 */
abstract class BaseAuditLogProperty extends Doctrine_Record

However, when I later try to add properties I get the exception posted in the beginning of the question:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
$auditLog = new AuditLogEntry();
$prop1 = new AuditLogProperty();
$prop1->name = 'title';
$prop1->value = $this->Content->title;
$prop2 = new AuditLogProperty();
$prop2->name = 'length';
$prop2->value = count($this->Content->plainText);
$auditLog->Properties[] = $prop1;
$auditLog->Properties[] = $prop2;
$auditLog->save();

If I do the following:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
var_dump(get_class($auditLog->Properties));

I get that Properties is of type AuditLogProperty, instead of Doctrine_Collection.

I use version 1.2.3 of Doctrine.



 Comments   
Comment by Trevor Wencl [ 14/Sep/11 ]

I am having the same issue and it is killing my application. Using your example, when I call:

var_dump(get_class($auditLog->Properties));

... and there are no AuditLogProperty records, I would expect either an empty Doctrine_Collection or null, but instead I get a new instance of AuditLogProperty with null values for the properties.





[DC-929] createIndexSql and dropIndexSql don't use the same logic to get the index name Created: 16/Nov/10  Updated: 07/Sep/11

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Lea Haensenberger Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Postgresql 8.4, Symfony 1.4, Doctrine 1.2



 Description   

In the class Doctrine_Export the functions for creating and dropping indexes do not use the same logic to get the name of the index to be created or dropped.
When creating an index $this->conn->quoteIdentifier() is called on the index name.
When dropping an index $this->conn->quoteIdentifier($this->conn->formatter->getIndexName()) is called on the name, which by default adds '_idx' to the index name. Hence, when an index should be dropped in a migration an index with that name is not found because it was created without the '_idx'.



 Comments   
Comment by Lukas Kahwe [ 16/Nov/10 ]

looks to me like this is a bug in index creation. then again fixing the bug will lead to potential BC issues. that being said, anyone affected could "simply" set the index format to empty. also "fixing" the names to the proper format does not require shuffeling around data. so imho the right fix would be to apply the drop naming logic in the create logic.

what surprises me is that the main reason for appending _idx by default was that many RDBMS will otherwise break because they do not separate identifiers between constraints and indexes etc and therefore people run into collisions without the postfix.

Comment by John Kary [ 07/Sep/11 ]

Related/Duplicate of DC-830 and DC-867.





[DC-915] The PHP code is invalid in the "Create Table" example; there are missing commas in the array definition. Created: 02/Nov/10  Updated: 07/Sep/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Trivial
Reporter: Matt Alexander Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: PNG File 2010-11-02_123641.png    

 Description   

http://www.doctrine-project.org/projects/orm/1.2/docs/manual/migrations/en#writing-migration-classes:available-operations:create-table

The PHP code is invalid in the "Create Table" example; there are missing commas in the array definition.



 Comments   
Comment by John Kary [ 07/Sep/11 ]

Submitted pull request with fixes:
https://github.com/doctrine/doctrine1-documentation/pull/1





[DC-867] Doctrine::ATTR_IDXNAME_FORMAT and Doctrine::ATTR_FKNAME_FORMAT are inconsistently applied during migrations Created: 15/Sep/10  Updated: 07/Sep/11

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Ryan Lepidi Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

postgres 8.4



 Description   

Given the following code:

    public function up()
    {
        $idx = array(
            'fields' => array('profile_id')
        );

        $this->addIndex('schedules', 'ix_schedules_profile_id', $idx);
    }
    public function down()
    {
        $this->removeIndex('schedules', 'ix_schedules_profile_id');
    }

The "up" function will try to create "ix_schedules_profile_id", but the "down" function will try to remove "ix_schedules_profile_id_idx". The same problem exists with foreign keys. The add/remove functions should both use the formatter, or neither should.



 Comments   
Comment by John Kary [ 07/Sep/11 ]

Appears to be duplicate of DC-830





[DC-1033] [PATCH] Use multibyte version of strtolower Created: 28/Aug/11  Updated: 28/Aug/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: Jonas Flodén Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.3.7, Symfony 1.4.13


Attachments: Text File 0001-Use-multibyte-version-of-strtolower.patch    

 Description   

While trying to develop a new Symfony frontend to an existing database - whcih unfortunately contains non-ascii character names - I ran into a lot of problems where non-ascii characters had been mangled.
After installing XDebug and digging into the issue I found that the use of strtolower on the column names was the issue, since it's not safe to use on UTF-8 strings.
I replaced all calls to strtolower with mb_strtolower and UTF-8 encoding which solved my issue. I don't know if that is the correct way of doing it or if there is a better way.
I saw one other use of mb_strtolower in doctrine and it was guarded with an if function exists... Also it might be an issue in other files as well...
I provide my patch file incase it is of any use.



 Comments   
Comment by Jonas Flodén [ 28/Aug/11 ]

Here is a Git pull request with the same patch:
https://github.com/doctrine/doctrine1/pull/39





[DC-1019] **REMOVED SPAM** Created: 14/Jul/11  Updated: 23/Aug/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Documentation Priority: Trivial
Reporter: betty akamissnigger Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

*REMOVED SPAM*



 Description   

*REMOVED SPAM*



 Comments   
Comment by Christian Roy [ 23/Aug/11 ]

This issue was filled with spam text so I removed it.





[DC-1030] [PATCH] doctrine 1.2.4 ADD/DROP CONSTRAINT UNIQUE Created: 19/Aug/11  Updated: 19/Aug/11

Status: Open
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: MichalKJP Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File symfony_0010_doctrine_fix_unique_add_drop.patch    

 Description   

Hi,

Adding/dropping UNIQUE CONSTRAINT doesn't work on PostgreSQL.

I'm attaching patch for this problem.

Best regards,
Michal






[DC-1013] [PATCH] Doctrine ignores unique option for integers (PostgreSQL) Created: 29/Jun/11  Updated: 18/Aug/11

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Eugene Leonovich Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File integer_unique.patch    

 Description   

This issue is exactly the same as DC-252, but refers to PostgreSQL



 Comments   
Comment by MichalKJP [ 18/Aug/11 ]

Your patch fixed the problem for me. Thanks!





[DC-1025] Doctrine is unable to handle table names with spaces Created: 02/Aug/11  Updated: 02/Aug/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.1, 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Blocker
Reporter: Daniel Borg Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP Version 5.2.14
Apache 2
MySQL
Windows Xp


Attachments: File doctrineTest.php     File tbl.php     File tbl_1.php    

 Description   

When trying to query a table which contains spaces I get the following exception

I have attached an simple example to reproduce

C:\Documents and Settings\daniel\Dokumenter\NetBeansProjects\test>php doctrineTest.php

Fatal error: Uncaught exception 'Doctrine_Query_Exception' with message 'Unknown table alias with' in C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php:856
Stack trace:
#0 C:\Doctrine-1.2.3\Doctrine\Query.php(1022): Doctrine_Query_Abstract->getComponentAlias('with')
#1 C:\Doctrine-1.2.3\Doctrine\Query.php(1239): Doctrine_Query->_buildSqlFromPart()
#2 C:\Doctrine-1.2.3\Doctrine\Query.php(1133): Doctrine_Query->buildSqlQuery(true)
#3 C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php(958): Doctrine_Query->getSqlQuery(Array)
#4 C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php(1026): Doctrine_Query_Abstract->_execute(Array)
#5 C:\Documents and Settings\daniel\Dokumenter\NetBeansProjects\test\doctrineTest.php(18): Doctrine_Query_Abstract->execute()
#6

{main}

thrown in C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php on line 856






[DC-509] Oracle don't close cursor Created: 18/Feb/10  Updated: 28/Jul/11

Status: Reopened
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: oxman Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

PHP 5.3.1



 Description   

When you doing a big loop of insertion you have a "too many open cursor".
The problem is in Doctrine_Connection class
At line 1005 you should replace :
$stmt = $this->prepare($query);
by
$stmt = $this->dbh->prepare($query);

and at line 1041 you should replace :
$stmt = $this->prepare($query);
by
$stmt = $this->dbh->prepare($query);

After this correction, you never have the problem "too many open cursor"

Thanks to Ota to point that on google groups.
http://groups.google.com/group/doctrine-user/browse_thread/thread/fe6cd03c8fb18b64/728ec1b4e42b1f0b?lnk=gst&q=doctrine_oracle_adapter#728ec1b4e42b1f0b



 Comments   
Comment by Jonathan H. Wage [ 02/Mar/10 ]

Hmm. This change is invalid because it then doesn't return the proper statement object. What is the real issue we get the too many cursors open error?

Comment by oxman [ 04/Mar/10 ]

Why ?
The both return Doctrine_Adapter_Statement_Interface

Comment by Jonathan H. Wage [ 04/Mar/10 ]

The change makes it so they return PDOStatement, and we need it to return the Doctrine statement wrapper, right?

Comment by oxman [ 04/Mar/10 ]

It seems not.

At line 1005 in Doctrine/Connection.php :
$stmt = $this->dbh->prepare($query);
var_dump(get_class($stmt));
die;

I see :
string(33) "Doctrine_Adapter_Statement_Oracle"

And with :
$stmt = $this->prepare($query);
var_dump(get_class($stmt));
die;

I see :
string(29) "Doctrine_Connection_Statement"

The both implements Doctrine_Adapter_Statement_Interface

Comment by vincent [ 29/Apr/10 ]

I have this problem in Symfony 1.4.3 when I use comand:
symfony doctrine:data-load

I have 3000 - 4000 lines in my fixtures and max open cursor at 300 on my database oracle.

This problem can an issue???

Comment by Jonathan H. Wage [ 08/Jun/10 ]

I see, well the change still is not right because it bypasses all the logic in Doctrine_Connection::prepare() which is for sure required and can't just be removed. We need to determine the real issue here in order to properly patch it.

Comment by Peter Wooster [ 29/Jun/10 ]

I'm encountering the same ORA-1000 problem running the symfony doctrine:build-schema command. We are still using PDO, but I have asked in the users group if that's the best choice. The problem is that the listTableColumns and listTableRelations methods both leave a cursor open. They both call Connection::fetchAssoc, so they should be reading all the records.

I narrowed it down a little:

This works properly when no parameters are provided:

$sql = "SELECT * FROM all_tab_columns tc WHERE tc.table_name = 'DEAL'";
$result = $connection->fetchAssoc($sql, array());

This doesn't release the cursor when a named parameter is provided

$sql = "SELECT * FROM all_tab_columns tc WHERE tc.table_name = :tn";
$result = $connection->fetchAssoc($sql, array(':tn' => 'DEAL')); // doesn't release cursor

This doesn't release the cursor when a positional parameter is provided

$sql = "SELECT * FROM all_tab_columns tc WHERE tc.table_name = ?";
$result = $connection->fetchAssoc($sql, array('DEAL')); // doesn't release cursor

This works properly when the PDO connection is used directly

$sql = "SELECT * FROM all_tab_columns tc WHERE tc.table_name = :tn";
$dbh = $connection->getDbh();
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':tn' => 'DEAL'));
$result = $stmt->fetchAll();

Comment by Clément Herreman [ 28/Jul/11 ]

As I went through this bug, I looked for a fix. I found one here https://github.com/derflocki/doctrine1/commit/47b926a523f9f6e3b88042ef2939af0646285ea2

Basically it consist of freeing cursors that aren't used by a SELECT query, thus preventing Oracle from throwing an exception on batch insert/delete.





[DC-1024] i am executing Created: 22/Jul/11  Updated: 26/Jul/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: cherukuri Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

$query = new Doctrine_Query();
$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,c.country_id,c.country_name')
//$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,ea.Country')
->from('Entities e')
->leftJoin('e.EntityAddresses ea ON ea.entity_id = e.entity_id AND ea.address_type ="M"')
->leftJoin('ea.Country c ON ea.country = c.country_id')
->leftJoin('e.ActiveFactories s')
->where('e.status=1');
if(!empty($alpha))

{ $query->andWhere("e.entity_name like '".$alpha."%'"); }

$query->andWhere("s.company_id=".$parentId)
->andWhere("e.entity_type=2")
->andWhere('s.status=1')
->groupBy('e.entity_id');






[DC-1023] i am executing doctrine type query i am geting error please gave me reply my query i am typed in descrition field Created: 24/Jul/11  Updated: 26/Jul/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: cherukuri Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 0
Labels: None


 Description   

$query = new Doctrine_Query();
$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,c.country_id,c.country_name')
//$query->select('e.entity_name,e.entity_id,s.id,s.parent_id,e.ffc_entity_id,ea.Country')
->from('Entities e')
->leftJoin('e.EntityAddresses ea ON ea.entity_id = e.entity_id AND ea.address_type ="M"')
->leftJoin('ea.Country c ON ea.country = c.country_id')
->leftJoin('e.ActiveFactories s')
->where('e.status=1');
if(!empty($alpha))
{
$query->andWhere("e.entity_name like '".$alpha."%'");
}
$query->andWhere("s.company_id=".$parentId)
->andWhere("e.entity_type=2")
->andWhere('s.status=1')
->groupBy('e.entity_id');






[DC-735] Imported objects not converted to objects and parsed as string when a setter method exists Created: 14/Jun/10  Updated: 22/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Kevin Dew Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Mac OS X 10.6



 Description   

If you set a setter method for a model which is for a relation the data import no longer works. This seems to be because in the _processRow method it checks if a method exists and then passes the default value rather than checking whether a relation exists first and passing the imported object.

This effectively means you can't overload a setter method and still use the data import.



 Comments   
Comment by ryan [ 22/Jul/11 ]

added testcase here
https://github.com/rahx/doctrine1/commit/ba5628abaa5b3d60638d833d90b1cf439504d560





[DC-743] Incompatibilty between fixture import and accessors extends Created: 16/Jun/10  Updated: 22/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Data Fixtures, Import/Export
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Brice Favre Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

Window, PHP5, Symfony



 Description   

Hello,

I had a problem when i try to import data with an extended accessors when i try to insert a content with a relation. I discovered this problem in symfony.

For example, here is my table :

 
News:
  tableName: ne_news
  columns:
    id:           { type: integer(4), primary: true, autoincrement: true }
    author_id:    { type: integer(4), notnull: true }
    name:         { type: string(255) }
    description:  { type: text }
  relations:
    author: { class: sfGuardUser, onDelete: NULL, local: author_id, foreign: id, foreignAlias: sfGuardUser }

And the fixture :

 
SfGuardUser:
  sadmin:
    username:       admin
    password:       admin
    is_super_admin: true
  author1:
    username: myname
    
News:
  News1:
    name: Test 1
    description: Description of news 1
    author: author1

I import it with symfony doctrine:data-load and it works.

If i add a news.class.php and extends the autogenerated class it fails.

 
    public function setAuthor($v)
    {
        //__log('extending setter');
        return $this->_set('author', $v);
    }

WhenDoctrine_Data_Import finds the setAuthor function, it wont transform author1 in object so $v will be a string, not an sfGuardUser object.

What do you think? Is a common behavior, how can i extends my accessor?



 Comments   
Comment by ryan [ 22/Jul/11 ]

this is the same issue as DC-735





[DC-1017] Floats persisted in the database are retrieve as strings. Created: 12/Jul/11  Updated: 12/Jul/11

Status: Open
Project: Doctrine 1
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor
Reporter: Grégoire Paris Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Ubuntu 64 bits, php 5.3



 Description   

Someone complained about symfony padding 0's after floats http://stackoverflow.com/questions/6650786/remove-extra-decimal-place-in-float-datatype-on-symfony/6663829 , I think it's a doctrine problem, since the doctrine:dql task seems to have the same problem:

>> doctrine executing dql query
DQL: FROM UcVideoAspect
found 1 results
-
id: '1'
video_id: null
pixel_ratio: '12.50'
width: null
height: null

Here, pixel ratio is defined as a float in the schema.yml file
Getting the property from a transient object returns a float, while getting it from the db returns a string.






issue with multiple connection handling (DC-740)

[DC-618] [PATCH] Local key relations without modifed fields but with modified relations are not saved Created: 06/Apr/10  Updated: 10/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Connection
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Sub-task Priority: Major
Reporter: Bernhard Schussek Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None

Attachments: File DC618TestCase.php     GIF File directadmin-logo.gif     Text File ticket_dc618.patch    

 Description   

Assume the following test setup:

[Email] * — 1 [Author] 1 — * [Book]

Assume further that you have a new Email, Author and Book object. Email and book have modified fields, author does not, except for the foreign key relation.

Now, when you save the Email object, the related Author is not saved because isModified($deep = false) returns false since no local field is modified. The solution is to pass the parameter $deep = true to isModified().

Patch and test case are attached. No existing test is broken by this fix.

PS: This patch fixes the correlated bug that objects with I18N behaviour are not saved if only their Translation objects are modified, but not their own fields.






[DC-797] Records containing a one-to-one relation are hydrated as dirty/modified Created: 26/Jul/10  Updated: 06/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Record, Relations
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Dominic Scheirlinck Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File Record.php.diff     File test.php    

 Description   

Attached is a self-contained 80 line test. In the test, Foo has an one to one relation to Bar. There is a null value in the foreign key column (at least one Foo without a Bar). And the relation is being used via this DQL:

Doctrine_Query::create()->from('Foo f')->leftJoin('f.Bar b')->execute();

At around line 254 of Doctrine_Hydrator_Graph/Graph.php, the hydrator sets the value of the relation column to Doctrine_Null if there is no related record:

$prev[$parent][$relationAlias] = $this->getNullPointer();

This causes Doctrine_Record to check if the value of the foreign key field was updated, which it does by calling Doctrine_Record::_isValueModified(). However, that method considers an update from null to Doctrine_Null as a modification. So, the record (and eventually the entire Collection returned) is marked as Doctrine_Record::STATE_DIRTY, even though it contains no modifications. This occurs during hydration, so the caller never sees the record as being clean.

The workaround I'm using is to subclass Doctrine_Record, and return false from _isValueModified() when moving from null to Doctrine_Null. But I think this could also be fixed in the hydrator.



 Comments   
Comment by Dominic Scheirlinck [ 15/Sep/10 ]

Patch is here: http://github.com/doctrine/doctrine1/pull/7

Comment by Dominic Scheirlinck [ 17/Oct/10 ]

New pull request, done on a topic branch this time (and rebased to be much nicer)

http://github.com/doctrine/doctrine1/pull/8

Comment by Derek Price [ 06/Jul/11 ]

Record.php.diff contains basically the patch Dominic attached but also makes sure that the internal property value is set regardless of whether the record is marked as dirty or not. Some code will break when the internal property value is left <unset> instead of Doctrine_Null.





[DC-644] _getCacheKeys() exhausts memory Created: 22/Apr/10  Updated: 06/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Caching
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Amir W Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Doctrine is installed as a Symfony plugin. Using the latest Symfony from SVN.



 Description   

My scripts have excessive memory consumption and I've often saw in my logs:

PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 2097152 bytes) in /proj/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Cache/Apc.php on line 111

Looking into the code I've found which function to blame:

protected function _getCacheKeys()
{
$ci = apc_cache_info('user');
$keys = array();

foreach ($ci['cache_list'] as $entry)

Unknown macro: { $keys[] = $entry['info']; ######### THIS IS THE LINE }

return $keys;
}

My server extensively uses APC caching and it's normal to have many cache keys.
Obviously retrieving ALL of them is time and memory consuming.
As I'm not well versed with Doctrine's code, I didn't want to dive further in.

Is there another way to avoid this pitfall?



 Comments   
Comment by Amir W [ 26/Apr/10 ]

Is there any patch that could be provided meanwhile? This is quite a problem on a live website.

Comment by Amir W [ 10/May/10 ]

Is this not a critical issue for Doctrine's cache? It's been up for 2 weeks with not even a comment...

Comment by Jonathan H. Wage [ 10/May/10 ]

Hi, what are you calling that is invoking _getCacheKeys()? The only methods that call it are the deleteBy*() methods. It is expected that these methods have to get the entire list of cache keys from the driver in order to perform the delete by operation. These cache clearing operations should probably be done in the CLI environment where the memory limits are higher. If you want to avoid _getCacheKeys() being invoked, then you must not use the deleteBy*() methods.

Comment by Amir W [ 10/May/10 ]

Thank you for commenting. Yes, I am using deleteByRegex() since I need to expire some result cache entries upon an update operation. What other choice do I have if I wish to keep using the result cache offered by Doctrine? Is there any other mechanism?

Can't _getCacheKeys() be optimized some way?

Comment by Jonathan H. Wage [ 10/May/10 ]

No, it is not able to be optimized anymore. It has to load all the keys into a php array in memory in order to loop over them to compare against the regex. You should probably not be doing cache clearing operations in the browser under apache. If you do, you'll need to raise your memory limit.

Comment by Amir W [ 10/May/10 ]

My code actually had a few of these calls and I've now removed use of the result cache with Doctrine. What you're writing means the result cache is not usable for dynamic websites. IMHO, it's a good practice to cache results and remove them once an update is made to the data (which naturally can happen due to an update from a user). However, if that by itself creates an overload on the server (and as you know even a temporary memory abuse leads to an overload), I cannot see how it can be useful.
Please tell me if you think there's a way the results cache can still be usable for a dynamic website.

Thanks

Comment by Jonathan H. Wage [ 10/May/10 ]

This is the only way to allow more complex delete functionality. How you use it, is not up to us. We intended that cache clearing is done from the command line or in an environment where the memory limit is high enough to be able to load all those keys. It may not be able to be used by everyone, if it is not working for how you are using it then you will need to think of another solution I suppose.

Comment by Amir W [ 10/May/10 ]

Thank you for your response and I'll think of another solution for my application.

I did dive into the code and there's a relevant optimization that could be made.

_getCacheKeys() is actually creating another array for all the cache keys which needlessly increases the memory used.
If the deleteBy*() method would be implemented at the driver level (such as with Apc.php) and not at the general level (Driver.php as it is now) this array would not have to be created. It won't be such a code bloat and would surely lessen memory use.

There could be a way around the problem which also implements another feature I miss with the results cache. By allowing some sort of cache tagging to mark the items that may need to be deleted we could easily delete relevant entries. I'll describe the interface here.

Instead of
$q = $q->useResultCache(true, 86400);

There should be
$q = $q->useTagResultCache('SomeTag', true, 86400);
which does the same PLUS update a cached variable (such as 'Doctrine_Result_Cache_Tag_SomeTag') which references the result cache keys of 'SomeTag'.

We can then easily implement deletion of relevant result cache entries with

deleteByTag('SomeTag')

which would read 'Doctrine_Result_Cache_Tag_SomeTag' to figure out which entries should be removed from the cache.

I'm pretty sure my usage scenario is not marginal but let me know what you think.

Comment by Jonathan H. Wage [ 10/May/10 ]

This is already possible if I understand what you describe.

$q->useResultCache(true, 3600, 'key_to_store_cache_under');

Now you can do:

$cacheDriver->delete('key_to_store_cache_under');

Also what you describe useTagResultCache() and keeping up with our own list of cache keys is the way it used to be and was changed to this after worse performance problems were discovered with that approach.

Comment by Amir W [ 10/May/10 ]

Perhaps I've been misunderstood so I'll try explain from the start.

In my system a few queries do relate to the same pieces of information. That information can be updated by a user and thus I would need to remove anywhere between 0 and 50 related result cache variables. I cannot easily name each and every one of my queries thus giving a specific key name doesn't help. So what I did was to prefix the name of each of the queries to indicate that I'll know how to remove them. I may have thousands of results cached and would need to clear just a few. That's why I use the deleteBy*() which proves to be extremely inefficient as it retrieves ALL the keys in my cache driver and not only the Doctrine related ones.

I really don't know how it has been implemented before but what I suggest wouldn't hurt performance as tagging would be an optional addition managed with another variable. If you think that won't b useful to other Doctrine users, I'll simply implement it for my system.

Thanks

Comment by Jonathan H. Wage [ 10/May/10 ]

I think the best solution is the one you suggested earlier. That each cache driver should directly implement this functionality and bypass the creation of the array. What do you think? It is backwards compatible so that way we can commit it in 1.2.

Comment by Amir W [ 10/May/10 ]

Bypassing the array is a required optimization which is easy to implement but it's not really a solution to the problem I'm facing and I believe is common enough (Zend_Cache for example implements tagging) and need to be offered. As it'll be 2 new functions that will implement tagging only when specifically requested, it'll also be backward compatible. The only thing I'm not sure about is if an implementation of some locking mechanism would be needed for the cached variable which would hold the list of cache keys for a specific tag.

Comment by Jonathan H. Wage [ 10/May/10 ]

Let me know what you come up with and we'll have a look at including it in the next 1.2.x release.

Comment by Amir W [ 16/May/10 ]

Bypassing the extra array is still not good enough and IMHO the whole idea of deleteBy() should NOT be used if many such requests could be made, as is my case.

What I've done now is what I mentioned before with a patch that is quite ugly.

In Doctrine/Query/Abstract.php right after the line

$cacheDriver->save($hash, $cached, $this->getResultCacheLifeSpan());

I've added

                if (!empty($GLOBALS['rcache_users_in_query'])) {
                	MyCache::keepRelatedCacheKey($GLOBALS['rcache_users_in_query'], $hash);
                }

Which saves another cache key which holds the hash tags that would have to be deleted on an update.
My global variable is actually an array as a Doctrine query result may be associated with more than one user and possibly other parameters.
Before calling the $q->execute(), I simply update this variable.

When a user on my system does the update, I then delete all relevant Doctrine keys with something like

		if (is_null($cacheDriver)) $cacheDriver = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE);
		
		foreach($arKeys as $key) {
			$cacheDriver->delete($key);			
		}

and then delete my other cache key.

This solution works well for me. Sorry I cannot make a nice Doctrine patch for it as I'm not well versed with your code. I still believe it should be supported by Doctrine with an optional extra parameter for $q->useResultCache()

Thanks

Comment by David Abdemoulaie [ 08/Jun/10 ]

Hi Amir,

Zend_Cache does not implement tagging for either APC or Memcached backends, see the documentation. It also likely never will, all requests for this functionality have been closed with Wont Fix.

I don't think the deleteBy methods should have ever been implemented. When initially implemented they cached a "doctrine_cache_keys" variable to store the keys known to Doctrine. This however led to a crippling bug that would crash my production servers after a few hours. Not even a friendly "out of memory" limit, but a slowdown and eventual crash. Please see DDC-460 for details. Note that I don't use the magic delete methods, just simple saves with timeouts and this was affecting me.

I fixed the solution as you've seen using the _getCacheKeys() method. I don't believe this functionality should have ever been added to Doctrine to begin with, but this is what we have to work with. It should be the responsibility of the cache store to handle tagging and such, not poorly hacked on with application code.

As it stands, the current implementation doesn't affect people who aren't even using this functionality, as it should be. As Jon suggested, you shouldn't be using this in the context of a page request. Use a CLI script or work on another solution. Your idea of tracking your keys in application code is a good idea, but it doesn't belong in Doctrine imo.

Comment by Amir W [ 10/Jun/10 ]

Thanks David for your comment.

I agree with you that my implementation should not belong in Doctrine and that tagging should have been a part of the cache backends.

Continuing with the same logic you've presented, deleteBy...() functionality **should be removed** from Doctrine if it causes the system to crash as it does so in an obnoxious way so that it would take too long for most developers to notice this is where the problem lies. It has certainly taken too much of my time and efforts and I'd rather save the pain from others.

Comment by Carsten Henkelmann [ 06/Jul/11 ]

We had the exact same problem. We used a "deleteAll()" of a ApcCache object and ran into the "allowed memory size exhausted" pitfall. We helped ourselves with a new class that extends ApcCache and uses the simpler apc_clear_cache function.

 
namespace Foo\Cache;

class ApcCache extends \Doctrine\Common\Cache\ApcCache
{
    /**
     * Delete all cache entries. Memory saving version...
     *
     * @return bool
     */
    public function deleteAll()
    {
        return apc_clear_cache('user');
    }
}
 
use Foo\Cache\ApcCache as Apc;
...
$this->_apc = new Apc();
$this->_apc->deleteAll();

This doesn't return the ids of the deleted entries like the original function but we don't need that. So this works fine for us.





[DC-1015] bindComponent not called before inherited classes base definitions Created: 04/Jul/11  Updated: 04/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Inheritance, Schema Files
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Adrian Nowicki Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony 1.4



 Description   

If I define a base model:

Entity:
connection: other
columns:
name: {}
size: {}

and inherited model:

Box:
inheritance:
extends: Entity
type: column_aggregation

Then file with base definition of Box does not contain bindComponent sentence to bind Box model with connection specified for Entity model.






[DC-1014] Geographical behaviour generates wrong INSERT statement in PostgreSQL if latitude/logitude not specified Created: 01/Jul/11  Updated: 01/Jul/11

Status: Open
Project: Doctrine 1
Component/s: Geographical
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Lorenzo Nicora Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Symphony 1.4, PostgreSQL 8.4.8



 Description   

Added "Geographical" behaviour to an entity:

 
ZipCode:
  actAs: [Geographical]
  columns:
    code: string
    [...]

Using the standard Symfony-generated admin manager, when trying to insert a new record without specifying both latitude and longitude, Doctrine generates a wrong INSERT statement for PostgreSQL, including latitude and longitude as '' (empty string)

 
Doctrine_Connection->exec('INSERT INTO zip_code (hidden, code,  country_id, latitude, longitude) VALUES (?, ?, ?, ?, ?)', array('false', '20133', '1', '', ''))

This cause this error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type double precision: ""

Workaround

explicitly specifying float type for latitude and longitude...

 
  actAs: 
    Geographical:
      latitude: {type: float}
      longitude: {type: float}

...still generate the column correctly as double precision in the database, but will not cause any error on inserting records.






[DC-1011] wierd behaviour with setTableName - table name doesn't get set Created: 28/Jun/11  Updated: 28/Jun/11

Status: Reopened
Project: Doctrine 1
Component/s: Record
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Justinas Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux 2.6.35-28-generic #50-Ubuntu SMP Fri Mar 18 19:00:26 UTC 2011 i686 GNU/Linux
PHP 5.3.3-1ubuntu9.5


Attachments: File attribute_set.php    

 Description   

if i create class called Attribute_set that extends Doctrine_Record and setTableName in setUpTableDefinintion like in documentation setting up models section, the table name appears not to be set
getTableName returns "doctrine_record_abstract"

any joins or relations fail.

if i set it in the setUp function the setTableName appear working and returns "attribute_sets" table name. This only happens with this particular class, and relations have no effect.

I attached class example i'm expiriencing problems with, that should help reproducte this issue



 Comments   
Comment by Justinas [ 28/Jun/11 ]

fixed misstype and it appears that it was not the problem, i get the same:

Base table or view not found: 1146 Table 'db.doctrine_record_abstract' doesn't exist

maybe attribute_set is somekind reserved word in doctrine library ?

Comment by Justinas [ 28/Jun/11 ]

the problem appears to come from Doctrine Formatter





[DC-1012] Doctrine_core specified twice in documentation Defining Models -> Join Table Associations Created: 28/Jun/11  Updated: 28/Jun/11

Status: Open
Project: Doctrine 1
Component/s: Documentation
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Documentation Priority: Minor
Reporter: Justinas Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

$manager->setAttribute(Doctrine_Core::Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);

should be:

$manager->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);

http://www.doctrine-project.org/projects/orm/1.2/docs/manual/defining-models/en#relationships:join-table-associations






[DC-1010] When putting a subquery in the where clause which includes a join and a limit the limit subquery algorithm mistakenly modifies the subquery Created: 21/Jun/11  Updated: 21/Jun/11

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: will ferrer Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

XP Xamp



 Description   

I have fixed this in my own version of doctrine but unfortunately I am to far diverged from the trunk to offer a patch.

here is a test case:

public function testSubqueryInWhereWithJoinAndLimit()
    {
        $q = new Doctrine_Query();
        $q->select('u.id');
        $q->from('User u');
        $q->where('u.id NOT IN (SELECT a.id FROM User u2 LEFT JOIN u2.Album a LIMIT 1)');
        $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id FROM entity e WHERE (e.id NOT IN (SELECT a.id AS a__id FROM entity e2 LEFT JOIN album a ON e2.id = a.user_id WHERE (e2.type = 0) LIMIT 1) AND (e.type = 0))');
    }

To fix the issue I changed this line in Doctrine_Query as follows:

if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) {

=

if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery && !$this->isSubquery()) {

Hope that helps.

Sincerely

Will Ferrer






[DC-1009] save() also updates fields which should not be Created: 08/Jun/11  Updated: 08/Jun/11

Status: Open
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Yan Urquiza Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows server 2003 PHP 5.2.17 / XP PRO 32bits XAMPP PHP 5.3.5
MSSQL / MYSQL
Symfony 1.4.6


Attachments: PNG File after_with_execute.PNG     PNG File after_with_save.PNG     PNG File before.PNG     File retrieveByExamBatchStatus.php     File schema.yml    

 Description   

When I want to do a simple update like this :

$batches = ExamResultsBatchTable::getInstance()->retrieveByExamBatchStatus(ExamResultsBatch::valid_status_code);
foreach($batches as $batch)
{
$batch->setExamBatchStatusId($batchStatusId);
$batch->setStatusDate(date('Y-m-d'));
$batch->save();
}
Only exam_batch_status_id and status_date should be updated (see screenshot before), but columns exam_batch_status_id ,status_date AND exam_subject_id are updated,with the same value (23) (screenshot after_with_save).

If I run this:
$toto = Doctrine_Query::create()
->update('ExamResultsBatch erb')
->set('erb.exam_batch_status_id', 23)
->set('erb.status_date', date('Y-m-d'))
>where('erb.id = ?' , $batch>getId())
->execute();
Everything is correctly done.

here is the simpliest case.

The same problems are signaled on other tables in the database, but different tables can be impacted by one save() (the execute() query still works fine).

Example : 2 foreign tables will be updated , even if the save() action should only concern the main table, and one field (which is not a foreign key).
The corresponding foreign key fields in the 2 foreign tables, will be updated with the value given (here 23).

Because save() is used in a lot of different places in our app, I need to find a solution to fix save(), or if not possible to override it to run a execute()like query.

Thanks for your help.
Don't hesitate to ask if you want more details.

Yan






[DC-329] Problem saving Self Referencing (Nest Relations) Created: 05/Dec/09  Updated: 03/Jun/11

Status: Open
Project: Doctrine 1
Component/s: Relations
Affects Version/s: 1.2.0
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Jaime Suez Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 14
Labels: None
Environment:

Mac OSX 10.5, Symfony 1.4 and MAMP


Attachments: Zip Archive h2aEqualable.zip     PNG File saving process.png     File schema.yml     File testEqualNestRelationsTest.php     File testNestedEqualRelationWithObjectsTest.php    

 Description   

There is a problem when you save Many to Many Self Referencing (Nest Relations).

I used the same example that it's used on Doctrine 1.2 Self Referencing (Nest Relations) Documentation:

My Schema:

User:
columns:
name:

Unknown macro: { type}

relations:
Parents:
class: User
local: child_id
foreign: parent_id
refClass: UserReference
foreignAlias: Children

UserReference:
columns:
parent_id:
type: integer
primary: true
child_id:
type: integer
primary: true

Fixtures:

User:
james:
name: James
alexander:
name: Alexander
david:
name: David

The problem happens with the Children. The first time I assigned children and saved the User, there is no problem; but when I saved the User again (without any change on him) the values in the UserReference? table changes: the "parent_id" takes the value of the "child_id".

I test it with Sf 1.4 and with Sf 1.3 stable versions, and I've got the same error.

If it not clear to understand what I'm saying, I put a "very ilustrative" image about the form and how change the values of the UserReference? table. Please see it, because it would be very usefull for understanding (explains better than my terrible English)

Thanks for all your work!

P. D.

I forgot to to say that watching the stack trace I think that the problem is in:

symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Connection/UnitOfWork.php

In the line 429:

public function saveAssociations(Doctrine_Record $record)

I would like to help more, but I couldn't figure out how this function works.



 Comments   
Comment by Jaime Suez [ 07/Dec/09 ]

This picture explains the error that it's done when you do an insert and then you save it again.

Comment by Jonathan H. Wage [ 07/Dec/09 ]

Can you provide a failing Doctrine test case? This may be a problem with Symfony and not Doctrine.

Comment by Jaime Suez [ 08/Dec/09 ]

First I published this bug on Symfony, because I thought that was a problem with Symfony, but you set it as invalid because it's belong to Doctrine.

This is the ticket on symfony:
http://trac.symfony-project.org/ticket/7690

I could do the Doctrine test case, but in one more mounth, because tomorrow I go out for vacations.
When I come back I'll do them.

Comment by psylosss [ 20/Dec/09 ]

Yes, I have got the same problem. During hours of debugging and exploring Doctrine's code, I found that problem localized in Hydrator component. I cannot digg deeper, so I ask you to fix it very much

Comment by Filippo De Santis [ 26/Dec/09 ]

Hi,
I had this problem in the 1.0 version of doctrine as well.
Using symfony, I upgraded to symfony 1.3 and doctrine 1.2 and I've found the same problem.

Attached to this comment you can find the files containing the schema I used (it is the same as that describe on this ticket but with a different class naming), and 2 unit tests. One using the symfony form and one using directly the doctrine objects. They report the bug discussed on this ticket and show another bug saving objects that already have one ore more relations.

As fixtures I used a fixtures.yml file containing:

Issue:
<?php for ($i = 1; $i <= 30; $i++): ?>
Issue_<?php echo $i; ?>:
title: "new issue <?php echo $i ?>"
<?php endfor; ?>

The following are the tests results:

– testEqualNestRelationsTest.php (using the forms) –

> First form for first issue: creation of the relation "issue 1 -> issue 2"
ok 1 - the edit form for issue 1 is valid
ok 2 - form1 saved
ok 3 - issue 1 is related with another issue
ok 4 - issue 1 is really related with issue 2

> Second form for first issue: saving the relation between "issue 1" and "issue 2" from "issue 2"'s form
ok 5 - the edit form for issue 2 is valid
ok 6 - form2 saved
not ok 7 - issue 2 is related with another issue ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 57)
  2. got: 0
  3. expected: 1
    not ok 8 - issue 2 is really related with issue 1
  4. Failed test (./test/unit/testEqualNestRelationsTest.php at line 58)
  5. got: NULL
  6. expected: 1

ok 9 - issue 1 is related with another issue
not ok 10 - issue 1 is really related with issue 2 ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 63)
  2. got: '1'
  3. expected: 2
    > Checking the relation table IssueReference ...
    ok 11 - There is only one relation saved on IssueReference
    ok 12 - 1 is the issue1 field of the relation
    not ok 13 - 2 is the issue2 field of the relation ******** this is the problem reported on this ticket ********
  4. Failed test (./test/unit/testEqualNestRelationsTest.php at line 71)
  5. got: '1'
  6. expected: '2'

> multi selection proof
ok 14 - the edit form for issue 1 is valid
ok 15 - form1 saved
ok 16 - the edit form for issue 2 is valid

                • this is the other bug I've found ********
                  not ok 17 - form2 exception catched : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 1
  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 114)

– testNestedEqualRelationWithObjectsTest.php (test using the "doctrine" objects ) –

> Saving relation directly from the objects and not using the forms...
ok 1 - issue1 saved
> checking issue1 relations
ok 2 - issue 1 is related with another issue
ok 3 - issue 1 is really related with issue 2

> checking "reverse" relation on issue2
ok 4 - issue 2 is related with another issue
ok 5 - issue 2 is really related with issue 1

> adding a relation issue2->issue1 directly
ok 6 - issue2 saved

> checking issue2 relations
not ok 7 - issue 2 is related with another issue ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 56)
  2. got: 0
  3. expected: 1
    not ok 8 - issue 2 is really related with issue 1
  4. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 57)
  5. got: NULL
  6. expected: 1

> checking issue1 relations
ok 9 - issue 1 is related with another issue
not ok 10 - issue 1 is really related with issue 2 ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 63)
  2. got: '1'
  3. expected: 2

> Checking the relation table IssueReference ...
ok 11 - There is only one relation saved on IssueReference
ok 12 - 1 is the issue1 field of the relation
not ok 13 - 2 is the issue2 field of the relation

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 71)
  2. got: '1'
  3. expected: '2'

> object multi adding relation proof
ok 14 - issue1 saved

                • this is the other bug I've found ********
                  not ok 15 - issue2 exception catched : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 1
  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 112)
Comment by Jaime Suez [ 13/Jan/10 ]

With the test provided by Filippo De Santis is any other thing needed??

I still on vacations untill 3 of febrary, so then I could do any other thing needed.

Comment by Jaime Suez [ 01/Feb/10 ]

The necessary test have to be how are illustrated in this link???

http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

Comment by Alexander Sweis [ 09/Feb/10 ]

What has happen with this bug?? I also have the same problem...

Comment by Jonathan H. Wage [ 02/Mar/10 ]

Hi, yes. We still need a unit test case like described here: http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

So we can run it with all the other tests and reproduce the issue in Doctrine by itself. Not in Symfony.

Thanks, Jon

Comment by psylosss [ 02/Mar/10 ]

Jon, here is the test for this bug: http://gist.github.com/319856

Please, fix it.. my work has been stopped cause of it

Comment by Jaime Suez [ 15/Mar/10 ]

Yes... please fix it... I'm also stuck in my work since a lot of time that the bug it's open.

Thanks

Comment by Nil Null [ 15/Mar/10 ]

I'm affected with this bug as well, fortunately, I found a way to get over it, it's ugly and innefficient, but at least my work isn't stopped due to this bug. I'll try to explain what I did commenting here later. Anyway, I really need this bug fixed too before I can start betatesting my app.
Thanks!

P.D: I'm using Doctrine 1.2.1.

Comment by Jonathan H. Wage [ 15/Mar/10 ]

I am trying to understand the issue but it just doesn't make much sense to me yet. The test case is wrong because you are dealing with instances of objects that have previously loaded references, then you try and re-fetch the same object instance. If you do $user1->free(true); then re-fetch the object the test passes as expected. So, I don't really have a proper failing test case still that actually exposes the problem. I'll keep playing around see if I can understand. let me know if anyone else has more information or a patch to test.

Thanks, Jon

Comment by Filippo De Santis [ 16/Mar/10 ]

Hi Jonathan,
This is the "translated" version of my unit test for symfony in "doctrine unit test"

http://github.com/ideato/phpcollab3/blob/phpcollabsf13/test/doctrine_unit_test/DC329TestCase.php

The first test is to show the error "SQLSTATE[23000]: Integrity constraint violation: 19 columns issue1, issue2 are not unique".
The second one is to show the fact that the relation are saved with wrong data.

Sorry for the late translation.

Filippo

Comment by Hendri Kurniawan [ 16/Mar/10 ]

Hi Jonathan,

It seems that the problem is caused by Doctrine_Collection::add() method line 456 (I could be totally wrong).

if (isset($this->referenceField)) {
    $value = $this->reference->get($this->relation->getLocalFieldName());
    if ($value !== null) {
        $record->set($this->referenceField, $value, false);
    } else {
        $record->set($this->referenceField, $this->reference, false);
    }
...

What is trying to do is to set the reference field value to the reference value that it's linked to.

This only happens when you try to fetch record from the "children".

Consider the following:

Employees:
  tableName: employees
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(100)
  relations:
    managing:
      class: Employees
      type: many
      local: manager_id
      foreign: employee_id
      foreignAlias: managedBy
      refClass: EmployeeManager

EmployeeManager:
...

Code:

// ----- The following will not give you any issues
  $manager = Doctrine::getTable('Issue')->findOneBy('id', '1'); // This is a manager
  foreach ($manager->managing as $employee) {
    ....
  }

  // This will not save anything
  $manager->save();
// -----

// ----- The following will
  $employee = Doctrine::getTable('Issue')->findOneBy('id', '2'); // This is an employee
  foreach ($employee->managedBy as $manager) {
    ...
  }

  // This will save the wrong data to the "EmployeeManager" table
  // because the code from Doctrine_Collection is overwriting "EmployeeManager" records
  // When they were being added to the collection by the Hydrator.
  $employee->save();
// -----

Debug backtrace when this happens:

string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1432"
string(103) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Collection.php @ line 461"
string(99) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Access.php @ line 131"
string(107) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Hydrator/Graph.php @ line 229"
string(101) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Hydrator.php @ line 137"
string(108) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Query/Abstract.php @ line 1036"
string(105) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Relation/Nest.php @ line 84"
string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1362"
string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1333"

Comment by Pierrot Evrard [ 19/Mar/10 ]

Hi all,

For people who are looking for a workaround, I've found one that work for me.

Get the doctrine extension h2aEqualable (h2aEqualable.zip), register it as a doctrine extension (see http://www.doctrine-project.org/documentation/manual/1_2/0_11/extensions) and make your refClass of every equal nest relation acting as h2aEqualable.

In your PHP script :
{{
Doctrine::setExtensionsPath( 'path/to/unzip/place' );
Doctrine_Manager::getInstance()->registerExtension( 'h2aEqualable' );
}}

In your YAML schema :
{{
MyEqualNestRelationRefClassModel:
actAs:
h2aEqualable:
fields: [id_1,id_2]
}}

As I've said before, it works for me, so let me know if it solve your issues too...

Comment by Pierre Guéguin [ 18/Jun/10 ]

I have the very same issue with non equal nest relations.
It is stopping my project

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '87-87' for key 'PRIMARY'

execute : UPDATE cop_job_stream_successor SET job_stream_destination_id = ?, updated_at = ? WHERE job_stream_source_id = ? AND job_stream_destination_id = ? - (87, 2010-06-18 18:55:32, 87, 94)

CopJobStream:
columns:
name:
type: string(255)
notnull: false
....
relations:
SuccessorJobStreams:
class: CopJobStream
local: job_stream_source_id
foreign: job_stream_destination_id
refClass: CopJobStreamSuccessor
foreignAlias: PredecessorJobStreams
onDelete: CASCADE
onUpdate: CASCADE

CopJobStreamSuccessor:
columns:
job_stream_source_id:
type: integer
primary: true
job_stream_destination_id:
type: integer
primary: true
relations:
CopJobStream:
local: job_stream_source_id
foreignAlias: CopJobStreamSuccessors
onDelete: CASCADE
onUpdate: CASCADE

Comment by Pierre Guéguin [ 18/Jun/10 ]

It works anyway with above h2aEqualable extension

Comment by Daniel Reiche [ 26/Jan/11 ]

after stumbling into the same pit as everyone, i created a fresh report as DC-958. Later I found out that it has been reported before, so please mark DC-958 as duplicate of this. (or at least related, as I was using a Non-Equal Nested Set) also DC-952 refers to the same problem, but also with Non-Equal nestet sets.

My Case: Non-Equal-Nested-Set. Problems occur on saving Objects for 2nd or more time. Doctrine deletes all Child-Relations of the Object to be saved and updates Relations of the Childs to other Objects (other parents of the children objects) with references to the child itself!

the proposed h2aEqualable extension does prevent the wrong update statements but not the initial delete of the child-relations.

What exactly is missing on this bug to be fixed? It is now a year old, and clearly preventing people from using Self-Referencing relations with doctrine.

How can we help? More sample data, schema definitions, test cases?

Comment by Francesco Levorato [ 15/Feb/11 ]

Here is a better and simpler test case for the equal relation: https://gist.github.com/827414

There is clearly a memory problem here. I'll leave it up to Jonathan to decide whether it's a scenario which can be avoided in Doctrine itself or must be handled by Symfony (http://trac.symfony-project.org/ticket/9398).

In the Symfony context calls to refresh() might not be an option when modifying an object (aka saving a form).

Comment by Yitzchak Schaffer [ 17/Feb/11 ]

h2aEqualable seems to work for me.

Comment by Pavel Campr [ 02/Jun/11 ]

h2aEqualable works only partly for me (same as Daniel Reiche wrote).

I tried to identify the problem.

My usecase was:
1) I have an Article record in $article
2) I called $article->RelatedArticles->getPrimaryKeys() , where RelatedArticles is a name of my self reference
3) $article->save();

The problem originates from step 2), during hydratation process for related articles, which are added to a collection of related articles, in Collection->add() method (line 465) here:

if ($value !== null)

{ $record->set($this->referenceField, $value, false); }

else {

but, $this->referenceField contains wrong name of reference field. Self referenced model (Article) has two relations to the same class (one from "owning" side, second from "referencing" side). $this->referenceField in the collection is somewhere filled with the wrong relation name (not the"referencing" one, but the "owning" one).

When I save the $article, all referenced records are saved too and this is the problem, why the Doctrine tries to save corrupted data:

In my example, I have this data:

in Doctrine_Collection->add on line 457: $record) is a RelatedArticle (
article1 = string(1) "4"
article2 = string(1) "9"
)
in Doctrine_Collection->add on line 458: $this->referenceField) = string(19) "article1"
in Doctrine_Collection->add on line 459: $value) = string(1) "9"

BUT expected data is:

in Doctrine_Collection->add on line 458: $this->referenceField) = string(19) "article2"

This wrong behavior modified my RelatedArticle into this: RelatedArticle (
article1 = string(1) "9"
article2 = string(1) "9"
)

I have no idea how to fix it, but maybe someone can, I hope

(
my schema is:

Article
relations:
RelatedArticles:
class: Article
local: article1
foreign: article2
refClass: RelatedArticle
)

Maybe, when "refClassRelationAlia