[DC-675] Doctrine_Connection_Mssql charset problem Created: 10/May/10  Updated: 23/Jul/14  Resolved: 08/Jun/10

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

Type: Bug Priority: Major
Reporter: Steve Müller Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None


 Description   

Recently I got problems with converting UTF-8 data to iso ISO-8859-1 while trying to insert/update a Microsoft SQL Server database.
I wrote a task that exports data from an UTF-8 MySQL database to a latin1 Microsoft SQL Server database. When converting the data from UTF-8 to ISO-8859-1 the insert/update fails:

SQLSTATE[HY000]: General error: trying to execute an empty query

As i tracked the error down I realized, that the exception only occurs if I try to insert/update data with special characters like "ü", "ö", "ä", "ß" etc.
The error's origin seems to lie in the Doctrine_Connection_Mssql class, more precisely in the replaceBoundParamsWithInlineValuesInQuery() method.
Debugging this method shows that after replacing a bound param with data containing a special character (see above), the replace action for the next bound param replaces the whole query string with an empty string. Therefore the parent class's method exec() throws an exception as it tries to execute an empty query.

Example:

Task snippet:
// $src is UTF-8 data (MySQL DB)
// $dest ist latin1 data (MSSQL DB)

$dest->setZip($src->getZip());
$dest->setCity(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $src->getCity());
$dest->setStreet(iconv("UTF-8", "ISO-8859-1//TRANSLIT", $src->getStreet());
$dest->save();

RESULTING DQL: UPDATE table SET zip = ?, city = ?, street = ? WHERE id = ?;

Params:
array(
'22307',
'München',
'Dummystreet 18'
'1'
)

After replaceBoundParamsWithInlineValuesInQuery() replaces param 'München', the query string is replaced by an empty string in the following iteration.

The root of the Problem seems to lie in the regex modifier 'u' which treats the pattern as UTF-8 in the param replacements. Removing this modifier solves the problem for me. What purpose has this modifier?






[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-98] Generated base class file names get erroneously prefixed Created: 10/Oct/09  Updated: 17/Jul/14  Resolved: 13/Oct/09

Status: Resolved
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.0-ALPHA2
Fix Version/s: 1.2.0-ALPHA3

Type: Bug Priority: Major
Reporter: Pim Rupert Assignee: Jonathan H. Wage
Resolution: Cannot Reproduce Votes: 0
Labels: None
Environment:

Mac OS X 10.6.1 / PHP 5.3.0


Attachments: File Builder.php     File Builder.php    
Issue Links:
Duplicate
is duplicated by DC-1065 http://www.doctrine-project.org/jira/... Open

 Description   

You can set the boolean option 'classPrefixFiles' to false when generating models to prevent the full class name becoming your file name. However, you this option has no effect on generated base classes. So even if you have set 'classPrefixFiles' to false, the generated files with base classes still contain the base class prefix name in their file name.

I suggest having a 'baseClassPrefixFiles' options OR following the 'classPrefixFiles' option for base class file names as well.

This is how the generated file names ended up in my models folder (with 'baseClassPrefix' = 'Base_'; 'classPrefixFiles' = false; 'baseClassesDirectory' = 'Base' and 'baseClassPrefixFiles' = false):

./Base/Base_Monkey.php
./Monkey.php

Should be:

./Base/Monkey.php
./Monkey.php



 Comments   
Comment by Jonathan H. Wage [ 13/Oct/09 ]

This seems to work for me when I test it.

Comment by Kyle Spraggs [ 05/Jan/10 ]

baseClassPrefixFiles does absolutely nothing on v1.2.1. I have patched Doctrine_Import_Builder to provide this functionality.

– ADD around line 132
/**

  • Whether to use the base class prefix for the filenames too
  • @var boolean
    **/
    protected $_baseClassPrefixFiles = true;

– MODIFY around line 1004

  • $baseClass['className'] = $this->_baseClassPrefix . $baseClass['className'];

+ if ($this->_baseClassPrefixFiles)

{ + $baseClass['className'] = $this->_baseClassPrefix . $baseClass['className']; +}
Comment by Kyle Spraggs [ 05/Jan/10 ]

Seems I was a little to hasty. I'm attaching the properly patched file for review.

Comment by Kyle Spraggs [ 05/Jan/10 ]

Adds the option baseClassPrefixFiles (default true) to specify whether or not the base class should include the prefix in the filename.

Comment by BizLogic [ 17/Jul/14 ]

I can confirm that this is still an issue in 1.2.4 – Doctrine does not respect the $this->_baseClassPrefixFiles because this variable does not exist in ./Doctrine/Import/Builder.php. Additionally some logic is missing for determine whether to use the prefix or not.

I have attached the patched file.





[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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-848] Validator Timestamp does not validate "YYYY-MM-DD hh:mm:ss"-Timestamps Created: 31/Aug/10  Updated: 17/Apr/14  Resolved: 01/Sep/10

Status: Resolved
Project: Doctrine 1
Component/s: Validators
Affects Version/s: 1.2.2, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Steffen Zeidler Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None

Attachments: File DC848TestCase.php     Text File Timestamp.patch    

 Comments   
Comment by Steffen Zeidler [ 31/Aug/10 ]

patch & test

Comment by Steffen Zeidler [ 31/Aug/10 ]

patch

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

Thanks for the issue and patches!

Fixed here http://github.com/doctrine/doctrine1/commit/680b4ba489d15a4c7fba73ec6a832ca142877b7b





[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-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-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-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-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-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-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-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-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-744] PHP Deprecated: Function spliti() is deprecated Created: 16/Jun/10  Updated: 17/Apr/14  Resolved: 31/Aug/10

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

Type: Bug Priority: Minor
Reporter: Jean-Philippe Blais Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None
Environment:

From Symfony 1.4 on Windows with PHP 5.3.2 using MSSQL (thru ODBC)



 Description   

spliti is deprecated with php 5.3.0+ and this function is used in Connection/Mssql.php lines 171 and 190
Original line:
$aux2 = spliti(' as ', $field_array);

Probably replacing with:
preg_split('/ as /i', $field_array);

Original PHP message :
PHP Deprecated: Function spliti() is deprecated in ....\lib\vendor\symfony\lib\plugins\sfDoctrinePlugin\lib\vendor\doctrine\Doctrine\Connection\Mssql.php on line 190



 Comments   
Comment by Javier Nogueira [ 12/Aug/10 ]

This bug is also present in doctrine 1.2.2, the version used by the symfony framework 1.4.X

Changing:
$aux2 = spliti(' as ', $field_array);
By:
$aux2 = preg_split('/ as /i', $field_array);

As reported by Jean-Philippe Blais solves the deprecation message problems.

Comment by Enrico Stahn [ 25/Aug/10 ]

Should be fixed with DC-828

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

Comment by Daniel O'Connor [ 31/Aug/10 ]

Causing http://pear.php.net/bugs/bug.php?id=17835 at the moment.

Who can we bribe to get the preg_split() change in? We're stomping out all of these bugs in PEAR (http://ollehost.dk/media/pear-bugs/) and this would just make life a little less painful

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

Sorry for the delay, it is fixed here http://trac.doctrine-project.org/changeset/7690





[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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-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-713] [pgsql] importer does not fetch varchar max length Created: 02/Jun/10  Updated: 17/Apr/14  Resolved: 25/Aug/10

Status: Resolved
Project: Doctrine 1
Component/s: Import/Export
Affects Version/s: 1.2.2
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Francesco Montefoschi Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None
Environment:

PostgreSql


Attachments: PNG File pgsql.png    

 Description   

The importer doe not look for the max length of string columns.

For example, the task generate-models-db is generating definitions like
$this->hasColumn('code', 'string', null, array(/**/));

instead of
$this->hasColumn('code', 'string', 10, array(/**/));



 Comments   
Comment by Francesco Montefoschi [ 02/Jun/10 ]

I created a patch on GitHub: http://github.com/fmntf/doctrine1/tree/DC-713.

Reading from `information_schema` we can also get the string length.
I tried to `generate-models-db` with original 1.2.2 code and patched code: it seems there are no regressions.

Comment by Francesco Montefoschi [ 17/Jun/10 ]

I don't know what happened, but the `listTableColumns` query is

SELECT fields, t.typtype AS typtype FROM information_schema.columns WHERE ..

and the t relation is not specified. By the way, commenting out the typtype, the string length is no more detected.
I think there is something wrong around line 170 - the "type" column should contain "varchar", not "character varying".

Comment by Francesco Montefoschi [ 17/Jun/10 ]

I attached the query output, commenting the typtype column.

Comment by Ricardo Simoes [ 05/Aug/10 ]

My workaround for `listTableColumns` query:
Doctrine/Import/Pgsql.php ln 101-102:

'listTableColumns' => "SELECT
ordinal_position as attnum,
column_name as field,
udt_name as type,
data_type as complete_type,
--t.typtype AS typtype,
(SELECT t.typtype FROM pg_type t WHERE t.typname = udt_name) 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 = %s
ORDER BY ordinal_position", FROM pg_type t WHERE t.typname = udt_name) AS typtype,

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

Why was this re-opened? Your comment is not clear to me. Can you provide a test case or a proper patch so we can see the changes.

Comment by Francesco Montefoschi [ 24/Aug/10 ]

Sorry if the comment was not clear.

I proposed you a patch, I tested it before sending it back to you.
You applied something else to Doctrine source code that is not working. Try to copy and paste the query in http://svn.doctrine-project.org/tags/1.2.3/lib/Doctrine/Import/Pgsql.php (listTableColumns) to pgadmin and execute it. The postgres server will refuse to execute that query.
The error is due to a call to a "t" relation, which is not declared in the FROM (the query is something like: "SELECT a.field, ..., t.field FROM a").

The error is:
-----------------------------------------------------
ERROR: missing FROM-clause entry for table "t"
LINE 6: ... t.typtype ...
^
-----------------------------------------------------

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

It had looked like this patch: http://github.com/fmntf/doctrine1/commit/5a1123f78974fef7203500b082df754e1c69cbf6

was already applied. I did not apply any patch today. I am confused now, which patch is the right one?

Comment by Francesco Montefoschi [ 25/Aug/10 ]

The patch was not applied correctly.

In 1.2.3 importer the query has 8 direct fields in SELECT + 1 field as subquery
My patch has 7 direct fields + 1 as subquery.

Compare also the subquery. Mine is one line shorter.

Read the two queries line by line. They are different, and the one in 1.2.3 cannot be executed

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

Can you generate a patch and paste it in a code block?

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

Hopefully this fixes it for good.

http://trac.doctrine-project.org/changeset/7689

Comment by Francesco Montefoschi [ 27/Aug/10 ]

It seems to be fine!

Comment by Miha Vrhovnik [ 13/Sep/10 ]

Ok.. this is complete mess, somebody with permissions should reopen it.
This one works for Francesco as he is running with notices disabled.
if ttype is removed or commented out , then you get a notices that ttype key doesn't exist.
and it seems that ttype is required for enums to work.

in one of the comments Ricardo suggested replacing ...
t.typtype AS typtype with
(SELECT t.typtype FROM pg_type t WHERE t.typname = udt_name) AS typtype,

adding this get's rid of notices, but i don't know what happens for other things mentioned within comments of if this is a correct fix... The one who provided support for enums should take a look

I think Francesco should run import with notices enabled and then add the upper sub-query to get rid f them.. then it should also test if the rest of the import still works correctly.

Comment by Francesco Montefoschi [ 13/Sep/10 ]

My apologies, I developed the patch on a non development machine, so I used the default PHP configuration.





[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-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-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-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-645] Query with a leftJoin() + where(NOT IN) + limit() generate wrong SQL alias in the NOT IN part Created: 23/Apr/10  Updated: 17/Apr/14  Resolved: 02/Sep/10

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

Type: Bug Priority: Critical
Reporter: David Jeanmonod Assignee: Guilherme Blanco
Resolution: Fixed Votes: 1
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: File NotIn_LeftJoin_Limit_TestCase.php    

 Description   

I have a simple case with 3 Classes. Contact, Phone and Email. A Contact can many many phones, but only one email.

When doing this simple query:
$query = Doctrine_Query::create()->from('Contact c');
$query->leftJoin('c.Phones p ON c.id = p.contact_id');
$query->where('c.id NOT IN (SELECT Email.contact_id FROM Email)');
$query->execute();
Every thing went fine.

But when adding a limit() condition like:
$query->limit(20);
$query->execute();

The SQL generated query is not valid. There is a problem with the alias used in the NOT IN subquery. This query is generated like this:
WHERE c2.id NOT IN (SELECT e2.contact_id AS e2__contact_id FROM email e)
There is a mix between alias e2 and e

I have been trying to debug, but I didn't understand what was going wrong. The problem seems to happend in the class Doctrine_Query between line 1486 and 1554, but this part is obscur to me.

I attach to this ticket a valid TestCase

Thanks for support



 Comments   
Comment by David Jeanmonod [ 23/Apr/10 ]

TEXT VERSION OF THE TEST CASE

<?php

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:@localhost/test_doctrine');
echo "Connection is set up\n";

class Contact extends Doctrine_Record {
public function setTableDefinition()

{ $this->setTableName('contact'); $this->hasColumn('name', 'string', 300, array('type' => 'string', 'length' => 300)); }

public function setUp()

{ $this->hasMany('Phone as Phones', array('local' => 'id', 'foreign' => 'contact_id')); $this->hasOne('Email as Email', array('local' => 'id', 'foreign' => 'contact_id')); }

}
class Phone extends Doctrine_Record {
public function setTableDefinition()

{ $this->setTableName('phone'); $this->hasColumn('contact_id', 'integer', null, array('type' => 'integer')); }

public function setUp()

{ $this->hasOne('Contact', array('local' => 'contact_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); }

}
class Email extends Doctrine_Record {
public function setTableDefinition()

{ $this->setTableName('email'); $this->hasColumn('contact_id', 'integer', null, array('type' => 'integer')); }

public function setUp()

{ $this->hasOne('Contact', array('local' => 'contact_id', 'foreign' => 'id')); }

}
echo "Classes Contact, Phone and Email are defines\n";

try

{Doctrine::dropDatabases();}

catch(Exception $e){} // Drop if exist
Doctrine::createDatabases();
Doctrine::createTablesFromArray(array('Contact', 'Phone', 'Email'));
echo "Databases tables are create\n";

$query = Doctrine_Query::create()->from('Contact c');
$query->leftJoin('c.Phones p ON c.id = p.contact_id');
$query->where('c.id NOT IN (SELECT Email.contact_id FROM Email)');
$query->limit(20);
try

{ $query->execute(); echo "TEST: Doctrine LEFTJOIN + NOT IN + LIMIT is OK\n"; }

catch (Exception $e)

{ echo "TEST: Doctrine LEFTJOIN + NOTIN + LIMIT is NOT working\n Alias in the NOT IN part are wrong, we get e2 and e\n\nDetail of the error:\n ", $e->getMessage(), "\n"; }
Comment by will ferrer [ 30/Jun/10 ]

Hi David

I had a problem with subqueries in the which I worked around by including real sql in the subquery with a prefix of SQL:.

My bug occurred trying to run this code:

$q = Doctrine_Query::create(); 
$q->from('Customer Customer'); 
$q->addWhere(' Customer.id in (SELECT Customer.id as customer_id FROM Customer Customer)'); 
$q->addSelect('Customer.id'); 
$q->addSelect('Customer.id as customer_id');
$q->limit(20);

However this code works fine for me now (though make sure you have the latest svn build of doctrine because there were some patches that helped this work):

$q = Doctrine_Query::create(); 
$q->from('Customer Customer'); 
$q->addWhere(' Customer.id in (SQL:SELECT p.id AS p__0 FROM product_customers p)'); 
$q->addSelect('Customer.id'); 
$q->addSelect('Customer.id as customer_id');

Notice the use of SQL: in the subquery.

Here is the bug:

http://www.doctrine-project.org/jira/browse/DC-692

Also worth noting that I am getting that sql by building another query and then running the getSqlQuery method to return the sql I am then using in the other query.

Hope that helps.

Will Ferrer





[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-421] Doctrine_Table::createQuery() can use wrong connection Created: 12/Jan/10  Updated: 17/Apr/14  Resolved: 07/Dec/10

Status: Resolved
Project: Doctrine 1
Component/s: Connection, Query
Affects Version/s: 1.2.0, 1.2.1
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Eugene Janusov Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 0
Labels: None

Attachments: Text File DC-421.patch     File DC421TestCase.php    

 Description   

r6799 introduced 3 changes to the Doctrine_Table: in findByDql(), getQueryObject(), and createQuery() methods.
The first two are pretty obvious, but the last one is a mistake in my opinion:

--- lib/Doctrine/Table.php	(revision 6798)
+++ lib/Doctrine/Table.php	(revision 6799)
@@ -1033,7 +1033,7 @@
 
         $class = $this->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS);
 
-        return Doctrine_Query::create($this->_conn, $class)
+        return Doctrine_Query::create(null, $class)
             ->from($this->getComponentName() . $alias);
     }

An instance of Doctrine_Table always has a reference to a particular Doctrine_Connection, so why createQuery() method, intended to "create a query on this table" should use different (i.e. default one) connection instead of already specified one?



 Comments   
Comment by Eugene Janusov [ 20/Jan/10 ]

Attached test case.

Comment by Eugene Janusov [ 20/Jan/10 ]

While preparing the test case, I looked more closely to the sources. It turns out that if you do something like this:

Doctrine::getTable('ComponentName')->createQuery()->execute()

then eventually the preferred connection will be used.

But createQuery() method creates a new Doctrine_Query and doesn't pass a connection, thus Doctrine_Query_Abstract's constructor tries to get a default connection, which is unacceptable if you'd like to work without a default connection.

A possible solution that I see is to not set $this>_conn inside Doctrine_Query as long as it will not be really required.-

Comment by Eugene Janusov [ 20/Jan/10 ]

I found another solution. As I said above, the problem is really relevant only if you don't use a default connection. But in this case you must bind all your components to a particular connection(s). So, we can just check for hasConnectionForComponent() inside Doctrine_Table::createQuery().

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

Can you provide the fix you found as a patch so I can clearly see it and test it? Thanks, Jon

Comment by Paul Kamer [ 17/Jul/10 ]

Jonathan, I can confirm that this patch solves this issue.
It also fixes this ticked in Symfony 1.X: http://trac.symfony-project.org/ticket/7689

Comment by Jochen Bayer [ 07/Aug/10 ]

DC-421.patch works for me too.

Comment by Jonathan H. Wage [ 07/Dec/10 ]

I've reverted that one change and everything seems better now: https://github.com/doctrine/doctrine1/commit/b4dc8e66a89a7e17cd195c489b18005e19ca9ea5





[DC-754] When using a dot inside a string doctrine throws an exception because it believes what comes before the dot is a class name Created: 20/Jun/10  Updated: 17/Apr/14  Resolved: 01/Sep/10

Status: Resolved
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: Fixed Votes: 0
Labels: None
Environment:

XP Xamp


Attachments: Text File 2010-06-21_Doctrine_1.2_SVN.patch     Text File DC_754_fix.patch    

 Description   

Hi Jon

I ran into and patched another bug in Doctrine 1.2.2 (The menu in jija shows 1.2.3 as released but I am not seeing it in SVN or on the web site so I can't test the bug in that version).

When you include a dot in a string in your select statement the function getExpressionOwner in Doctrine_Query fires and considers that the text appearing before the dot in the string is the name of a class. There for it attempts to extract a short alias out of it.

I made a test case to illustrate this:

public function testQuoteEncapedDots()
    {
        $q = new Doctrine_Query();
        $q->select("'testing.dots.inquotes' as string, u.name")->from('User u');

        $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, 'testing.dots.inquotes' AS e__0 FROM entity e WHERE (e.type = 0)");
    }

It throws the following exception.

Unexpected Doctrine_Query_Exception thrown in [Doctrine_Query_ShortAliases_TestC
ase] with message [Couldn't get short alias for testing] in C:\htdocs\php_librar
y\Doctrine_1.2_SVN\lib\Doctrine\Query\Abstract.php on line 679

Trace
-------------
#0 C:\htdocs\php_library\Doctrine_1.2_SVN\lib\Doctrine\Query.php(641): Doctrine_
Query_Abstract->getSqlTableAlias('testing')
#1 C:\htdocs\php_library\Doctrine_1.2_SVN\lib\Doctrine\Query\Select.php(37): Doc
trine_Query->parseSelect(''testing.dots.i...')
#2 C:\htdocs\php_library\Doctrine_1.2_SVN\lib\Doctrine\Query\Abstract.php(2083):
 Doctrine_Query_Select->parse(''testing.dots.i...')
#3 C:\htdocs\php_library\Doctrine_1.2_SVN\lib\Doctrine\Query.php(1168): Doctrine
_Query_Abstract->_processDqlQueryPart('select', Array)
#4 C:\htdocs\php_library\Doctrine_1.2_SVN\lib\Doctrine\Query.php(1134): Doctrine
_Query->buildSqlQuery(true)
#5 C:\htdocs\php_library\Doctrine_1.2_SVN\tests\Query\ShortAliasesTestCase.php(3
0): Doctrine_Query->getSqlQuery()
#6 C:\htdocs\php_library\Doctrine_1.2_SVN\tests\DoctrineTest\UnitTestCase.php(15
8): Doctrine_Query_ShortAliases_TestCase->testQuoteEncapedDots()
#7 C:\htdocs\php_library\Doctrine_1.2_SVN\tests\DoctrineTest\GroupTest.php(75):
UnitTestCase->run()
#8 C:\htdocs\php_library\Doctrine_1.2_SVN\tests\DoctrineTest.php(183): GroupTest
->run(Object(DoctrineTest_Reporter_Cli), Array)
#9 C:\htdocs\php_library\Doctrine_1.2_SVN\tests\run.php(320): DoctrineTest->run(
)
#10 {main}

I patched the bug by doing a preg_replace where all quote encaped strings are removed before looking for the short alias. The getExpressionOwner function now reads as follows in my code:

public function getExpressionOwner($expr)
    {
        if (strtoupper(substr(trim($expr, '( '), 0, 6)) !== 'SELECT') {
			$expr = preg_replace('/([\\]*[\'\"])[^\1]*\1/', '', $expr);
            preg_match_all("/[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*[\.[a-z0-9]+]*/i", $expr, $matches);

            $match = current($matches);

            if (isset($match[0])) {
                $terms = explode('.', $match[0]);

                return $terms[0];
            }
        }
        return $this->getRootAlias();

    }

I am including the patch with this post but I think my version of the code base is starting diverge as I also have a few other things added to mine (as discussed in: DC-701)

Hope you are well.

Will Ferrer



 Comments   
Comment by will ferrer [ 21/Jun/10 ]

Improved patch to have a more rigorous test case, refined the regex added, and put in a comment referencing this bug.

Comment by Pablo Mateos [ 29/Jun/10 ]

Hi, we're having an issue which is related to this post and I'd like to share it with you so maybe it's posible to solve both.

The situation appears when you need to look for some data that includes a "." inside a string SQL comparison with LIKE operator, here you have an example:

$this->pager = new sfDoctrinePager('Recurso', sfConfig::get('app_res_pag'));
$this->pager->getQuery()
->select('r.*,
c.alias as cliente_alias,
c.nombre as cliente_nombre,
o.alias as origen_alias,
o.nombre as origen_nombre,
GROUP_CONCAT(DISTINCT CONCAT_WS(",", cat.id, e.nombre) ORDER BY cat.id ASC) as elemento_nombre,
cv.hash as cv_hash')
->from('Recurso r')
->innerJoin('r.Cliente c')
->innerJoin('r.Origen o')
->leftJoin('r.RecursoCategoriaItem rci')
->leftJoin('rci.CategoriaItem ci')
->leftJoin('ci.Categoria cat')
->leftJoin('ci.Elemento e')
->leftJoin('ci.Nivel n')
->leftJoin('r.RecursoCv rcv')
->leftJoin('rcv.Cv cv')
->leftJoin('cv.Idioma i')
->leftJoin('r.RecursoComentario rc')
->leftJoin('rc.Comentario comm')
->where('r.apellido LIKE "%.net%" OR r.nombre LIKE "%.net%" OR r.numero_doc LIKE "%.net%" OR r.mail LIKE "%.net%" OR o.nombre LIKE "%.net%" OR cat.nombre LIKE "%.net%" OR e.nombre LIKE "%.net%" OR n.nombre LIKE "%.net%" OR c.nombre LIKE "%.net%" OR c.alias LIKE "%.net%" OR r.contenido LIKE "%.net%"')
->groupBy('r.id')
>orderBy('r.' . $orderBy . ' ' . $this>order);
$this->pager->setPage($page);
$this->pager->init();

Look at the "WHERE" line, there is a LIKE ".net".

So when we execute this code, Doctrine tries to parse the "." in the ".net" like an SQL alias and of course it fails:

ERROR:

500 | Internal Server Error | Doctrine_Exception
Couldn't find class "%

Do you know some other why to solve this situation ?. In case you need further information about this, just ask me.

Thank you in advance.

Pablo Mateos.

Comment by will ferrer [ 29/Jun/10 ]

Hi Pablo

I think I found a work around for you – I tested this bug out to see if I could recreate and patch it and found that my own system didn't generate the bug. Turns out the difference is my code encapes the strings that go in the query with single quotes and this seems to solve the problem.

Try the same query you posted above but replace the "%.net%" with '%.net%'.

I think that should solve it.

Hope that helps.

Will

Comment by Pablo Mateos [ 30/Jun/10 ]

Hi Will, I tried what you said and it worked !!!!!! . It's great to have so easy solutions for debugging, isn't ?.

So, anyway do you think this issue should be considered as a bug ?.

I really appreciate your help.

Pablo.

Comment by will ferrer [ 30/Jun/10 ]

Hi Pablo

I am glad that worked .

I do think this is still a bug – I there are some problems with double quotes in dql in general I believe. Then again there may be something in the docs about this being a restriction that I overlooked (not sure).

But since its solvable with using single quotes I would recommend putting it as a low priority bug – which may mean it won't actually get fixed any time soon. Whether it gets fixed or not though its good to have these kinds of bugs in the system so that there is a record of everything that needs fixing and so other users can find work arounds to there problems by looking through the archive.

Hope you are well.

Will

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 smash company [ 18/Nov/10 ]

I'm curious if this could be the same issue that causes doctrine:build-schema to give either the 'Missing class name' or 'Couldn't find class Content ' error? I am going a little crazy trying to figure out why doctrine:build-schema doesn't work for me. Details here:

http://www.symfonyexperts.com/question/show/id/156

Comment by will ferrer [ 18/Nov/10 ]

Hi Smash

I did a quick glance at your issue. I have never encountered this error my self and I don't think it is related to my issue.

When I have a bug like that the first place I start looking is where the exception is being thrown.

For you its in the Doctrine_Import_Builder class on either line 949 or 995

You could start by putting some debugging to see what the $definition var is. That may offer some insights. Then if that doesn't clarify whats wrong with your schema you could start back tracking out of the method to see where else things could be screwing up .

Hope that helps at least alil bit.

Will Ferrer





[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-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-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-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-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-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-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-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-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-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-1064] EntityManager::clear doesn't working with inserting Created: 16/Apr/14  Updated: 16/Apr/14  Resolved: 16/Apr/14

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

Type: Bug Priority: Major
Reporter: Adrian Ch Assignee: Jonathan H. Wage
Resolution: Invalid Votes: 0
Labels: None


 Description   

It looks like EntityManager's clear() method doesn't remove objects that was persisted during script execution.

Bellows are two functions. First one insert 10.000 records and use clear after each flush that should remove objects from memory, but instead of that memory usage growths in each iteration. There isn't any other reference for this objects.

I've checked how it works for reading and with clearing it works perfectly - script uses only constant memory.

 
    private function testInserting($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        for ($i = 1; $i <= 10000; ++$i) {

            $item = new $entityClass();
            $item->setName($i);
            $item->setPresentation($i);
            $em->persist($item);

            if ($i % $batchSize == 0) {
                $em->flush();
                $em->clear();

                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }
        }
    }
    
    
private function testReading($em, $entityClass, $batchSize, $startMemoryUsage)
    {
        $q = $em->createQuery("select i from $entityClass i");
        $iterableResult = $q->iterate();

        $i = 0;
        while (($row = $iterableResult->next()) !== false) {
            $em->clear();
            if ($i % $batchSize == 0) {
                $currentMemoryUsage = memory_get_usage();
                printf("%d:\n\t%.2f MB (%.2f MB)\n", $i, $currentMemoryUsage /1024 / 1024, ($currentMemoryUsage - $startMemoryUsage) / 1024 / 1024);
            }

            $i++;
        }
    }
    

My results:

1) Reading without clearing ($em->clear(); removed)

0:
22.89 MB (2.63 MB)
1000:
33.41 MB (13.15 MB)
2000:
44.04 MB (23.78 MB)
3000:
53.50 MB (33.24 MB)
4000:
65.13 MB (44.86 MB)
5000:
74.81 MB (54.55 MB)
6000:
84.27 MB (64.01 MB)
7000:
97.96 MB (77.69 MB)
8000:
107.40 MB (87.14 MB)
9000:
117.17 MB (96.91 MB)
10000:
126.61 MB (106.35 MB)

2) Reading with using clear

0:
22.89 MB (2.63 MB)
1000:
26.25 MB (5.99 MB)
2000:
24.74 MB (4.48 MB)
3000:
26.72 MB (6.46 MB)
4000:
24.79 MB (4.52 MB)
5000:
26.76 MB (6.50 MB)
6000:
24.81 MB (4.55 MB)
7000:
26.77 MB (6.51 MB)
8000:
24.83 MB (4.57 MB)
9000:
26.81 MB (6.54 MB)
10000:
24.86 MB (4.60 MB)

3) Inserting without clearing

1000:
29.50 MB (9.24 MB)
2000:
37.76 MB (17.50 MB)
3000:
45.12 MB (24.86 MB)
4000:
54.34 MB (34.07 MB)
5000:
61.79 MB (41.53 MB)
6000:
69.09 MB (48.82 MB)
7000:
76.40 MB (56.13 MB)
8000:
83.75 MB (63.48 MB)
9000:
95.64 MB (75.37 MB)
10000:
102.98 MB (82.71 MB)

4) Inserting with using clear

1000:
27.90 MB (7.63 MB)
2000:
34.64 MB (14.37 MB)
3000:
40.43 MB (20.17 MB)
4000:
48.20 MB (27.93 MB)
5000:
54.12 MB (33.85 MB)
6000:
59.89 MB (39.63 MB)
7000:
65.67 MB (45.40 MB)
8000:
71.43 MB (51.16 MB)
9000:
81.51 MB (61.25 MB)
10000:
87.29 MB (67.02 MB)






[DC-933] Results from Doctrine_Query::execute inconsistent with results from Doctrine_Query::getSqlQuery() Created: 19/Nov/10  Updated: 15/Apr/14  Resolved: 28/Feb/11

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

Type: Bug Priority: Critical
Reporter: Roger Webb Assignee: Guilherme Blanco
Resolution: Invalid Votes: 0
Labels: None
Environment:

Redhat Linux, Apache, PHP 5,



 Description   

The DQL Query:

$query = Doctrine_Query::create()
->select("
b.borrowers_date as borrowers_date,
b.borrower_id as borrower_id,
borrower_contact.first_name as borrower_first_name,
borrower_contact.last_name as borrower_last_name,
lo_contact.first_name as lo_first_name,
lo_contact.last_name as lo_last_name,
realtor_contact.first_name as realtor_first_name,
realtor_contact.last_name as realtor_last_name,
lo_company_contact.first_name as lender,
b.current_status as current_status
")
->from("Borrowers b")
>innerJoin("b.UserBorrowerAssigned ubass WITH ubass.user_id = " . $this>user_id)
->innerJoin("b.ContactInfo borrower_contact")
->innerJoin("b.LoBorrowerAssigned lobass")
->innerJoin("lobass.LoanOfficers lo")
->innerJoin("lo.ContactInfo lo_contact")
->innerJoin("lo.Companies lo_company")
->innerJoin("lo_company.ContactInfo lo_company_contact")
->leftJoin("b.RealtorBorrowerAssigned realbass")
->leftJoin("realbass.Realtors realtor")
->leftJoin("realtor.ContactInfo realtor_contact");
...
$query->where("b.current_status != 'finialized'")
->andWhere("b.current_status != 'ignored'")
->andWhere("b.current_status != 'dead'");

$query->execute Returns only 1 row

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

$query->getSqlQuery() returns:

SELECT b.borrowers_date AS b_0, b.borrower_id AS b1, c.first_name AS c2, c.last_name AS c3, c2.first_name AS c24, c2.last_name AS c25, c5.first_name AS c56, c5.last_name AS c57, c4.first_name AS c48, b.current_status AS b_9 FROM borrowers b INNER JOIN user_borrower_assigned u ON b.borrower_id = u.borrower_id AND (u.user_id = 129) INNER JOIN contact_info c ON b.contact_info_id = c.contact_info_id INNER JOIN lo_borrower_assigned l ON b.borrower_id = l.borrower_id INNER JOIN loan_officers l2 ON l.loan_officer_id = l2.loan_officer_id INNER JOIN contact_info c2 ON l2.contact_info_id = c2.contact_info_id INNER JOIN companies c3 ON l2.company_id = c3.company_id INNER JOIN contact_info c4 ON c3.contact_info_id = c4.contact_info_id INNER JOIN realtor_borrower_assigned r ON b.borrower_id = r.borrower_id INNER JOIN realtors r2 ON r.realtor_id = r2.realtor_id INNER JOIN contact_info c5 ON r2.contact_info_id = c5.contact_info_id WHERE (b.current_status != 'finialized' AND b.current_status != 'ignored' AND b.current_status != 'dead')

Running this query in PhpMyAdmin returns 1,095 rows.

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

Results Inconsistent



 Comments   
Comment by Roger Webb [ 19/Nov/10 ]

I have stripped the query down to this:

->select("
b.borrowers_date as borrowers_date,
b.borrower_id as borrower_id,
borrower_contact.first_name as borrower_first_name,
borrower_contact.last_name as borrower_last_name,
b.current_status as current_status
")
->from("Borrowers b")
->innerJoin("b.ContactInfo borrower_contact")
->innerJoin("b.UserBorrowerAssigned ubass");

$query->where("b.current_status != 'finialized'")
->andWhere("b.current_status != 'ignored'")
->andWhere("b.current_status != 'dead'")
>andWhere("ubass.user_id = ?", $this>user_id);

Results are still consistent with but report above.

Classes:

class Borrowers extends BaseBorrowers
{

function setUp()

{ parent::setUp(); $this->hasOne('ContactInfo', array('local' => 'contact_info_id', 'foreign' => 'contact_info_id')); $this->hasOne('LoBorrowerAssigned', array('local' => 'borrower_id', 'foreign' => 'borrower_id')); $this->hasOne('RealtorBorrowerAssigned', array('local' => 'borrower_id', 'foreign' => 'borrower_id')); $this->hasOne('UserBorrowerAssigned', array('local' => 'borrower_id', 'foreign' => 'borrower_id')); $this->unshiftFilter(new Doctrine_Record_Filter_Compound(array('ContactInfo'))); }

}

class UserBorrowerAssigned extends BaseUserBorrowerAssigned {

function setUp()

{ parent::setUp(); $this->hasOne("Borrowers", array("local" => "borrower_id", "foreign" => "borrower_id")); $this->hasOne("Users", array("local" => "user_id", "foreign" => "user_id")); }

}

class Users extends BaseUsers {

function setUp()

{ parent::setUp(); $this->hasOne("ContactInfo", array("local" => "contact_info_id", "foreign" => "contact_info_id")); $this->unshiftFilter(new Doctrine_Record_Filter_Compound(array('ContactInfo'))); }

}

The users class also contains the function that issues the query in question.

Comment by Roger Webb [ 28/Feb/11 ]

Non issue. Wasn't familiar with use of Doctrine.

Comment by Jacob Spizziri [ 15/Apr/14 ]

I know this is an old issue, but I'm experiencing a similar problem. What did you do to fix this?

Here is my QueryBuilder query:

$qb = $query = $this->repoLibrary->createQueryBuilder('l');

$query = $qb
->select('l')
->innerJoin('l.productVariant', 'v')
->innerJoin('v.product', 'p')
->innerJoin('p.taxons', 't', 'WITH', 't.id IN (:array)')
->where('l.user = :user')
->groupBy('l.id HAVING count(DISTINCT t.id) >= :count')
->setParameter('user', $user)
->setParameter('array', $s)
->setParameter('count', count($taxons))
->getQuery();

$query->getSql() executes perfectly in MySQL but
$query->getResult() doesn't return what I'm looking for.





[DC-8] Doctrine_Hydrator error while populate records if column contains double underscores Created: 15/Sep/09  Updated: 06/Mar/14  Resolved: 18/Sep/09

Status: Resolved
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.0.12, 1.1.4, 1.2.0-ALPHA1
Fix Version/s: 1.0.12, 1.1.4, 1.2.0-ALPHA1

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


 Description   

Moved from Trac (Ticket #2472) to JIRA.

I'm starting to use Doctrine for an project which already has an existing database schema. Some of the columns have double underscores as part of their names, e.g. "foo_bar__abc".

Model:

Foo:
  tableName: foo_table
  columns:
    foo_bar__abc:
      type: integer

Query:

$q = Doctrine_Query::create()->from('Foo b')->fetchOne();

Error:

Notice: Undefined index: b__foo_bar in Doctrine/Hydrator.php on line 309
Notice: Undefined index: in Doctrine/Hydrator.php on line 310
Fatal error: Call to a member function getFieldName() on a non-object in Doctrine/Hydrator.php on line 311

Issue #849 is from the same kind of error but I solved it in another way.

File: Hydrator.php

304 if ($this->_isIgnoredName($key)) continue;
305                
306 $e = explode('__', $key);
307 $last = strtolower(array_pop($e));

changed to

304 if ($this->_isIgnoredName($key)) continue;
305                
306 $e = explode('__', $key, 2);
307 $last = strtolower(array_pop($e));

This will fix the issue without the need to replace the seperator.



 Comments   
Comment by Jonathan H. Wage [ 18/Sep/09 ]

Your change breaks the test suite with fatal errors. I don't think this is something we can change at this point in 1.x

Comment by Frank Strife [ 26/Jan/10 ]

i have found a workaround for this little problem

 
				$count = substr_count($key, '__');
				
				$e = explode('__', $key);
                $last = strtolower(array_pop($e));
				if ($count > 1){
					$cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('', $e))];
				}
				else{
					$cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];
				}

but to call use $example->id not $example->__id

Comment by Jaroslav Hejral [ 05/Mar/10 ]

This bug occures again in the 1.2.1 version.

file: Doctrine/Hydrator/Graph.php

282: if ($this->_isIgnoredName($key))

{ 283: continue; 284: }

285:
286: $e = explode('__', $key); // here is missing the third argument with value 2
287: $last = strtolower(array_pop($e));

Comment by Edu [ 06/Mar/14 ]

Solution:

In file: Doctrine/Hydrator/Graph.php

Change this:

$e = explode('__', $key);
$last = strtolower(array_pop($e));
$cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];

For this:

$e = explode('__', $key);
if(count($e)>2){
	$aux = array($e[0]);
	unset($e[0]);
	$ls_builder = '';
	foreach($e as $value)
        {
		$ls_builder .= '__'.$value;
	}
	array_push($aux,$ls_builder);
	$e = $aux;
}
$last = strtolower(array_pop($e));
$cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];




[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-646] DELETE and INNER JOIN Created: 23/Apr/10  Updated: 03/Jun/13  Resolved: 08/Jun/10

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

Type: Bug Priority: Major
Reporter: jerome Assignee: Jonathan H. Wage
Resolution: Won't Fix Votes: 0
Labels: None
Environment:

WIndows 7
Wamp (PHP Version 5.3.0 mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $ )



 Description   

I made a DQL delete query.

$q = Doctrine_Query::create()
->delete()
->from('termRelationship tr')
->innerJoin('tr.termTaxonomy tt')
->innerJoin('tr.Post p')
->where('p.id = ?', '1')
->andWhere('tt.taxonomy = ?','category');

//GENERATED SQL OF THE DQL
DELETE FROM term_relationship INNER JOIN term_taxonomy t2 ON t.term_taxonomy_id = t2.id INNER JOIN post p ON t.object_id = p.id WHERE (id = '1' AND taxonomy = 'category')

But this query is incorrect

The query must be( alias are not present beetween DELETE and FROM and for the FROM table)

DELETE tr FROM term_relationship tr INNER JOIN term_taxonomy t2 ON tr.term_taxonomy_id = t2.id INNER JOIN post p ON tr.object_id = p.id WHERE (p.id = '1' AND t2.taxonomy = 'category')

With this request all is good in pphmyadmin.



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

Joins are not supported on update and delete queries because it is not supported on all dbms. It won't be implemented in Doctrine 1 or Doctrine 2. You can however get the same affect by using subqueries.

Comment by James Bench [ 03/Jun/13 ]

You can't delete from a table when it's in a subquery in MySQL (I'm using Doctrine 2).

DELETE FROM tblA a WHERE a.id NOT IN(SELECT a2.id FROM tblA a2 JOIN a2.tblB b WHERE b.value = :value)




[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-377] Cannot delete a taggable record (Taggable Extension) Created: 22/Dec/09  Updated: 10/Aug/12  Resolved: 15/Mar/10

Status: Closed
Project: Doctrine 1
Component/s: Extensions
Affects Version/s: 1.2.0, 1.2.1
Fix Version/s: 1.2.2

Type: Bug Priority: Major
Reporter: Fabien Pennequin Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 1
Labels: None
Environment:

PHP 5.3.1, Mac OS X (10.6), MySQL 5.0.86, Symfony 1.4.1


Attachments: Text File TaggableConstraintError.patch    

 Description   

With Taggable extension, when I try to delete a record using Taggable, I get this exception :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`sf_sandbox/article_taggable_tag`, CONSTRAINT `article_taggable_tag_id_article_id` FOREIGN KEY (`id`) REFERENCES `article` (`id`))

If I check the sql queries generated by Doctrine, there are not "onDelete CASCADE" for one of relation added by Taggable extension.

I have write some test cases for reproduce this bug (checking if relation has a property onDelete setted to CASCADE) but I can't reproduce the thrown exception in test case because sqlite omits queries with constraint. Also, I found how to fix this bug.

The fix and test cases are available in the file attached to this ticket.



 Comments   
Comment by Jason [ 20/Apr/10 ]

Hi Jon-

Where can I find this fix?

http://svn.doctrine-project.org/extensions/Taggable/branches/1.2-1.0 (the link referenced from the docs at http://www.doctrine-project.org/extension/Taggable) doesn't have this fix.

Comment by Jason [ 20/Apr/10 ]

Sorry, it appears the patch attached above is in SVN, however this is still broken.

With Doctrine 1.2.2 sandbox configured to work with MySQL 5.x database on 5.2.10, using the following schema

{{
BlogPost:
actAs: [Taggable]
columns:
title:
type: string(255)
notnull: true
description:
type: string(255)
notnull: true
}}

the CASCADE in the constraints for the table being applied the Taggable behavior are still not being applied (see first constraint below)

{{
CREATE TABLE `blog_post_taggable_tag` (
`id` bigint(20) NOT NULL DEFAULT '0',
`tag_id` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`,`tag_id`),
KEY `blog_post_taggable_tag_tag_id_taggable_tag_id` (`tag_id`),
CONSTRAINT `blog_post_taggable_tag_id_blog_post_id` FOREIGN KEY (`id`) REFERENCES `blog_post` (`id`),
CONSTRAINT `blog_post_taggable_tag_tag_id_taggable_tag_id` FOREIGN KEY (`tag_id`) REFERENCES `taggable_tag` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
}}

Comment by Malcolm Hall [ 10/Aug/12 ]

I use Doctrine v1.2.4 and created a fix for this problem, change the _options array initialization in Taggable.php to this:

protected $_options = array(
'builderOptions' => array(),
'tagField' => null,
'cascadeDelete' => true
);

This works because parent::buildRelation() calls the buildLocalRelation() method in Generator.php which looks for the cascadeDelete and if true then it adds the necessary CASCADE params, as you can see below:

public function buildLocalRelation($alias = null)
{
...
if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && ! $this->_options['appLevelDelete'])

{ $options['onDelete'] = 'CASCADE'; $options['onUpdate'] = 'CASCADE'; }

...

Now both parts of the taggable relation get the cascade on delete feature. So if you delete a tag OR you delete a post, the row in the taggable_tag table gets deleted too.





[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-160] Search doesn't use the Search Analyzer to escape the query Created: 30/Oct/09  Updated: 13/Jul/12  Resolved: 02/Nov/09

Status: Resolved
Project: Doctrine 1
Component/s: Searchable
Affects Version/s: 1.0.12, 1.1.4, 1.2.0-ALPHA1, 1.2.0-ALPHA2, 1.2.0-ALPHA3
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Markus Lanthaler Assignee: Jonathan H. Wage
Resolution: Can't Fix Votes: 0
Labels: None


 Description   

When you use the Doctrine_Search_Analyzer_Standard all special characters like "ü" are removed or converted to e.g. "ue". So far so good.. The problem arises when a user performs a search.
Since Doctrine is using the plain query with the special char "ü" instead of converting it also there no results are returned.

Using the UTF8 analyzer is no option because often the normalization is a desired feature. It allows for example a user to formulate the query either as "Muenchen" or "München" and he still receives a relevant result.



 Comments   
Comment by Jonathan H. Wage [ 30/Oct/09 ]

The only option I can see is to do this in Doctrine_Search_Query::query()

$text = Doctrine_Inflector::unaccent($text);

I am not sure about doing this though. What do you think?

Comment by Markus Lanthaler [ 30/Oct/09 ]

I don't think that that's a good idea since it breaks the UTF8 analyzer. I would refactor the analyzers to include a method like normalize(). Those methods could then be called in the analyzers analyze() method.

Doctrine_Search_Analyzer_Standard::normalize($text, $encoding = $null) would look as follows:

public function normalize($text, $encoding = null) 
{ 
  $text = preg_replace('/[\'`�"]/', '', $text); 
  $text = Doctrine_Inflector::unaccent($text); 
  $text = preg_replace('/[^A-Za-z0-9]/', ' ', $text); 
  $text = str_replace('  ', ' ', $text); 

  return strtolower(trim($text));
}

Doctrine_Search_Analyzer_Utf8::normalize($text, $encoding = $null) would look as follows:

public function normalize($text, $encoding = null) 
{ 
  if (is_null($encoding)) { 
    $encoding = isset($this->_options['encoding']) ? $this->_options['encoding']:'utf-8'; 
  } 

  // check that $text encoding is utf-8, if not convert it 
  if (strcasecmp($encoding, 'utf-8') != 0 && strcasecmp($encoding, 'utf8') != 0) { 
    $text = iconv($encoding, 'UTF-8', $text); 
  } 

  $text = preg_replace('/[^\p{L}\p{N}]+/u', ' ', $text); 
  $text = str_replace('  ', ' ', $text); 

  return mb_strtolower(trim($text), 'UTF-8');
}

This would then also allow to remove some code duplication in the analyze() method. It could be changed to the following code in Doctrine_Search_Analyzer_Standard and could be completely removed in Doctrine_Search_Analyzer_Utf8:

public function analyze($text, $encoding = null)
{
  $text = $this->normalize($text, $encoding);

  $terms = explode(' ', $text);

  $ret = array();
  if ( ! empty($terms)) {
      foreach ($terms as $i => $term) {
          if (empty($term)) {
              continue;
          }

          if (in_array($lower, self::$_stopwords)) {
              continue;
          }

          $ret[$i] = $lower;
      }
  }
  return $ret;
}

Finally the normalize() method is called in Doctrine_Search_Query::query(). Unfortunately I have no idea how to call it there!?
What do you think?

Comment by Jonathan H. Wage [ 02/Nov/09 ]

At first this seems like a good solution but I realized it will break things even more. We allow wildcards and certain keywords in the query string. *, OR, AND, etc. If we were to run the normalize() method on the query text it would break all that functionality.

Comment by Markus Lanthaler [ 02/Nov/09 ]

Well.. that's nowhere documented.. the only thing I found was

Doctrine_Search provides a query language similar to Apache Lucene. The Doctrine_Search_Query converts human readable, easy-to-construct search queries to their complex DQL equivalents which are then converted to SQL like normal.

So I would rather break those special things than to have the search missing existing items. But maybe there's a better place to call that normalize() - perhaps where the query is analyzed and converted to a DQL statement. It should be possible there to run normalize on every search term.

Comment by Jonathan H. Wage [ 02/Nov/09 ]

That's what this means:

Doctrine_Search provides a query language similar to Apache Lucene

You can do things like

$query->query('some text* OR some more test*');

If we normalized each term/word it will still remove those wildcards. That is what query language similar to Apache lucene means.

Comment by João Veríssimo [ 13/Jul/12 ]

What do you think about this solution?
class ErpSearchAnalizer extends Doctrine_Search_Analyzer_Standard {
public function analyze($text, $encoding = null) {
$text = preg_replace('/[\'`�"]/', '', $text);
$text = Doctrine_Inflector::unaccent($text);
// for * search
//$text = preg_replace('/[^A-Za-z0-9]/', ' ', $text);
$text = str_replace(' ', ' ', $text);
$terms = explode(' ', $text);

$ret = array();
if (!empty($terms)) {
foreach ($terms as $i => $term) {
if (empty($term))

{ continue; }
if($term == 'OR'){ $ret[$i] = $term; continue; }
$lower = strtolower(trim($term));

if (in_array($lower, parent::$_stopwords)) { continue; }

$ret[$i] = $lower;
}
}
return $ret;
}
}
to make a search like this
$analize = new ErpSearchAnalizer();
$val_user = $analizar->analyze($val_user);
$tempresult = $table->search(implode(" ", $val_user));

will it work?





[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-702] Migration commands always want to drop all database tables Created: 25/May/10  Updated: 07/May/12  Resolved: 08/Jun/10

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

Type: Bug Priority: Major
Reporter: Benjamin Arthur Lupton Assignee: Jonathan H. Wage
Resolution: Cannot Reproduce Votes: 0
Labels: None
Environment:

Zend Server 5.0.1 for OSX, PHP 5.3.2, MySQL 5.1.43



 Description   

I'm trying to get migrations going, such that I install the database, make a change to the schema.yml (something simple such as a column length change), and then have a migration generated and performed.

No matter what I try, doctrine just generates an initial add all the database tables, then after that if I try any further migration generation, they all try to drop all the database tables. I am not having much luck.

$ rm ../application/data/migrations/*

$ php ./doctrine build-all-reload
build-all-reload - Are you sure you wish to drop your databases? (y/n)
y
build-all-reload - Successfully dropped database for connection named '0'
build-all-reload - Generated models successfully from YAML schema
build-all-reload - Successfully created database for connection named '0'
build-all-reload - Created tables successfully
build-all-reload - Data was successfully loaded

$ ls ../application/data/migrations

$ php ./doctrine generate-migrations-db
generate-migrations-db - Generated migration classes successfully from database

$ ls ../application/data/migrations
1274778030_addbal_file.php 1274778038_addbal_roleanduser.php 1274778046_addburn_fileandproject.php 1274778054_addinvoicedatabackup.php 1274778062_addburnprojectindex.php
1274778031_addbal_invoice.php 1274778039_addbal_user.php 1274778047_addburn_imageandproject.php 1274778055_addusergroup.php 1274778063_addideaindex.php
1274778032_addbal_invoiceitem.php 1274778040_addbrief.php 1274778048_addburn_project.php 1274778056_addusergroupanduserfor.php 1274778064_addusergroupindex.php
1274778033_addbal_message.php 1274778041_addbriefandfile.php 1274778049_addburn_recommendation.php 1274778057_addbalfileindex.php 1274778065_addfks.php
1274778034_addbal_permission.php 1274778042_addbriefanduserfor.php 1274778050_addburn_state.php 1274778058_addbalusertaggabletag.php
1274778035_addbal_permissionandrole.php 1274778043_addbrieftype.php 1274778051_addburn_suburb.php 1274778059_addtaggabletag.php
1274778036_addbal_permissionanduser.php 1274778044_addburn_company.php 1274778052_addidea.php 1274778060_addbriefindex.php
1274778037_addbal_role.php 1274778045_addburn_department.php 1274778053_addideaandimage.php 1274778061_addburncompanyindex.php

$ ... make a change to the schema.yml file in my text editor and save, in this case change a column length from 250 to 200 ...

$ php ./doctrine generate-migrations-diff
generate-migrations-diff - Generated migration classes successfully from difference

$ ls ../application/data/migrations
1274778030_addbal_file.php 1274778038_addbal_roleanduser.php 1274778046_addburn_fileandproject.php 1274778054_addinvoicedatabackup.php 1274778062_addburnprojectindex.php
1274778031_addbal_invoice.php 1274778039_addbal_user.php 1274778047_addburn_imageandproject.php 1274778055_addusergroup.php 1274778063_addideaindex.php
1274778032_addbal_invoiceitem.php 1274778040_addbrief.php 1274778048_addburn_project.php 1274778056_addusergroupanduserfor.php 1274778064_addusergroupindex.php
1274778033_addbal_message.php 1274778041_addbriefandfile.php 1274778049_addburn_recommendation.php 1274778057_addbalfileindex.php 1274778065_addfks.php
1274778034_addbal_permission.php 1274778042_addbriefanduserfor.php 1274778050_addburn_state.php 1274778058_addbalusertaggabletag.php 1274778089_version37.php
1274778035_addbal_permissionandrole.php 1274778043_addbrieftype.php 1274778051_addburn_suburb.php 1274778059_addtaggabletag.php
1274778036_addbal_permissionanduser.php 1274778044_addburn_company.php 1274778052_addidea.php 1274778060_addbriefindex.php
1274778037_addbal_role.php 1274778045_addburn_department.php 1274778053_addideaandimage.php 1274778061_addburncompanyindex.php

$ cat ../application/data/migrations/1274778089_version37.php
<?php
/**

  • This class has been auto-generated by the Doctrine ORM Framework
    */
    class Version37 extends Doctrine_Migration_Base
    {
    public function up() { $this->dropTable('bal__file'); $this->dropTable('bal__invoice'); $this->dropTable('bal__invoice_item'); $this->dropTable('bal__message'); $this->dropTable('bal__permission'); $this->dropTable('bal__permission_and_role'); $this->dropTable('bal__permission_and_user'); $this->dropTable('bal__role'); $this->dropTable('bal__role_and_user'); $this->dropTable('bal__user'); $this->dropTable('brief'); $this->dropTable('brief_and_file'); $this->dropTable('brief_and_user_for'); $this->dropTable('brief_type'); $this->dropTable('burn__company'); $this->dropTable('burn__department'); $this->dropTable('burn__file_and_project'); $this->dropTable('burn__image_and_project'); $this->dropTable('burn__project'); $this->dropTable('burn__recommendation'); $this->dropTable('burn__state'); $this->dropTable('burn__suburb'); $this->dropTable('idea'); $this->dropTable('idea_and_image'); $this->dropTable('invoice_data_backup'); $this->dropTable('user_group'); $this->dropTable('user_group_and_user_for'); $this->dropTable('bal_file_index'); $this->dropTable('bal_user_taggable_tag'); $this->dropTable('taggable_tag'); $this->dropTable('brief_index'); $this->dropTable('burn_company_index'); $this->dropTable('burn_project_index'); $this->dropTable('burn_user_taggable_tag'); $this->dropTable('burn_user_index'); $this->dropTable('buyer_taggable_tag'); $this->dropTable('buyer_index'); $this->dropTable('company_index'); $this->dropTable('file_index'); $this->dropTable('idea_index'); $this->dropTable('project_index'); $this->dropTable('seller_taggable_tag'); $this->dropTable('seller_index'); $this->dropTable('user_taggable_tag'); $this->dropTable('user_index'); $this->dropTable('user_group_index'); }

public function down()
{
$this->createTable('bal__file', array(
'id' =>
array(
....



 Comments   
Comment by Benjamin Arthur Lupton [ 25/May/10 ]

Clarity over tables and database.

Comment by Benjamin Arthur Lupton [ 25/May/10 ]

forgot to add the part about me changing the yaml file inbetween

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

Hi, I cannot reproduce the issue unfortunately

Comment by SkaveRat [ 26/Nov/10 ]

I have the exact same problem.

Looking at the paths, is seems OP uses the same ZendCasts.com setup for ZendFramework/Doctrine. I think the problem lies somewhere in there. Anyone got an idea?

Comment by SkaveRat [ 26/Nov/10 ]

Okay, found the problem, And I really hope there will be a fix soon, because it one of the biggest features of doctrine:

To get autoloading in ZendFramework correct, Doctrine has to prefix all models with "Model_" (see http://www.zendcasts.com/deep-integration-between-zend-and-doctrine-1-2/2010/01/ for more information)
The problem is, that the Diff-generating script searches for i.e. the class "User" instead of "Model_User", thinks that it doesnt exist, and wants to recreate it from scratch

Comment by Thomas Ingham [ 07/May/12 ]

We're having this same issue in 1.2.3 right now. Has anyone found a workaround? It seems likely that given the age of the last comment - I'm out of luck but yolo.





[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-363] Multiple connections and i18n Created: 16/Dec/09  Updated: 28/Mar/12  Resolved: 08/Jun/10

Status: Resolved
Project: Doctrine 1
Component/s: Connection, I18n
Affects Version/s: 1.0.14, 1.2.2, 1.2.3
Fix Version/s: 1.2.3

Type: Bug Priority: Blocker
Reporter: Xav. Assignee: Jonathan H. Wage
Resolution: Fixed Votes: 1
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 Colin Darie [ 04/Feb/10 ]

I'm experiencing the same issue with 4 connections. The I18n behavior is almost unusable for models whose connection is not the last one defined. I searched for an acceptable solution but I haven't found one (IMHO the setting to the right connection before each query is not acceptable in large projects). I tried to do like in Search behavior, but it didn't work, I doesn't know enough doctrine internals to understand why.

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

Can you test this in Doctrine 1.2? I believe it is fixed.

Comment by Georg [ 17/Feb/11 ]

I am using the latest symfony 1.4 which is doctrine 1.2.3 afaik, and this bug still exists.
Try

actAs:
I18n:
fields: [name]
generateFiles: true
generatePath: /project/lib/model/doctrine/i18n

and the resulting model base class is not bound to the correct connection.

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). The issue states that this has been fixed but I looked at the latest code and the problem still seems to be very much the same.

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 James Bell [ 23/Aug/11 ]

I'm also experiencing this issue, using the stable version of Symfony 1.4.13. If I define multiple database connections, the i18n Translation relations fail with this call: Doctrine_Relation_Parser->getRelation('Translation', )

'Unknown relation alias Translation'

dev:
mysql1:
class: sfDoctrineDatabase
param:
dsn: 'mysql:host=localhost;dbname=microscooters'
username: microuser_uk
password: sailing

mysql2:
class: sfDoctrineDatabase
param:
dsn: 'mysql:host=localhost;dbname=microscooters_ie'
username: microuser_ie
password: windy

postgresql:
class: sfDoctrineDatabase
param:
dsn: 'pgsql:host=localhost;dbname=mses6'
username: postgres
password: postgres

In this case, the primary connection is the postgresql one, and that is where the i18n behaviour is defined:

Category:
actAs:
Timestampable: ~
Auditable: ~
NestedSet: ~
I18n:
fields: [picture_id, sort_type, name, handle, subheading, breadcrumb, description, enabled, meta_title, meta_keywords, meta_description]
i18nField: culture
length: 5
actAs:
Timestampable: ~
Auditable: ~
...

I tried to implement the suggest above (ie adding a static hash of the database handle to the Doctrine_Record_Generator class file, which does clear out the connections. However, I then have difficulty with Doctrine recognizing CategoryTranslation as a class:

"( ! ) Fatal error: Class 'CategoryTranslation' not found in /sitename/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Table.php on line 545"

Is there anything else I can to do test/fix this?

Comment by Joe Siponen [ 23/Aug/11 ]

This is a duplicate of http://www.doctrine-project.org/jira/browse/DC-373. I've also added a failing test case to that issue that should reproduce the issue as described here.

Comment by Andy.L [ 28/Mar/12 ]

still exists in 1.2.4





[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-582] DataDict entry missing for datetime type for MySQL causes migrations to fail due to sql error Created: 18/Mar/10  Updated: 10/Jan/12  Resolved: 29/Mar/10

Status: Resolved
Project: Doctrine 1
Component/s: Migrations
Affects Version/s: 1.2.0, 1.2.1
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Rich Birch Assignee: Jonathan H. Wage
Resolution: Invalid Votes: 0
Labels: None
Environment:

LAMP



 Description   

I discovered this whilst trying out migrations via symfony. I added a datetime field to my schema.yml and generated the migrations, but upon running the migration I got the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '()' at line 1. Failing Query: "ALTER TABLE order_item ADD purchased_at datetime()"

The following code causes the failure in the actual migration:

$this->addColumn('order_item', 'purchased_at', 'datetime', '', array());

because it generates the following sql:

ALTER TABLE order_item ADD purchased_at datetime()

The diff from my patched version which fixes the issue is as follows:

Index: Doctrine/DataDict/Mysql.php
===================================================================
— Doctrine/DataDict/Mysql.php (revision 7415)
+++ Doctrine/DataDict/Mysql.php (working copy)
@@ -227,6 +227,7 @@
return 'DATE';
case 'time':
return 'TIME';
+ case 'datetime':
case 'timestamp':
return 'DATETIME';
case 'float':

It's against the following repository file:

http://doctrine.mirror.svn.symfony-project.com/branches/1.2/lib/Doctrine/DataDict/Mysql.php

I hope this is useful and gets committed



 Comments   
Comment by Rich Birch [ 22/Mar/10 ]

I've just discovered that the same issue exists for fields of type 'text':

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') NOT NULL, session_time DATETIME NOT NULL, INDEX session_id_index_idx (session_' at line 1. Failing Query: "CREATE TABLE session (id BIGINT AUTO_INCREMENT, session_id VARCHAR(64) NOT NULL, session_data text() NOT NULL, session_time DATETIME NOT NULL, INDEX session_id_index_idx (session_id), PRIMARY KEY(id)) ENGINE = INNODB"

from the following schema:

Session:
columns:
session_id:

{ type: string(64), notnull: true }

session_data:

{ type: text, notnull: true }

session_time:

{ type: timestamp, notnull: true }

indexes:
session_id_index:
fields: [ session_id ]
unique: true

I guess there may be other field entries missing too. Is there a comprehensive list of doctrine field types somewhere?

Comment by Rich Birch [ 22/Mar/10 ]

Ok, I might have been being dumb here. I've just checked the doctrine documentation for defining the schema (http://www.doctrine-project.org/documentation/manual/1_2/en/defining-models) and there's no mention of a datetime or text field (I've just realised that I should have used string instead of text anyway), but datetime still works as a column type so shouldn't it be documented?

I guess either datetime should be fully removed or fully supported

Comment by Jonathan H. Wage [ 29/Mar/10 ]

You should be using the Doctrine portable types. So you would use date or timestamp I believe and Doctrine will convert it to the appropriate type for your dbms.

Comment by Anatolie Marinescu [ 10/Jan/12 ]

not correctly generated migration, in my case generated:

$this->addColumn('tree', 'published_at', 'datetime', '', array(
));

but if change the fourth parameters on null, all ok





[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-534] Couldn't hydrate. Found non-unique key mapping named 'lang' Created: 02/Mar/10  Updated: 28/Dec/11  Resolved: 15/Mar/10

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

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

PHP 5.2.9 Symfony 1.4



 Description   

For the following query

return $this->createQuery('a')
->innerJoin('a.Translation t WITH t.lang = ?', $lang)
->innerJoin('a.UserAttributes ua')
->innerJoin('ua.AttrOptions o WITH o.attribute_id = a.id')
->innerJoin('o.Translation ot WITH ot.lang = ?', $lang)
->addWhere('ua.user_id = ?', $userId)
->addWhere('a.tab = ?', $tab)
->addOrderBy('a.ord asc')
->execute();

Unknown macro: {/quote}

i get

Couldn't hydrate. Found non-unique key mapping named 'lang'.

{/quote}

error, so i cannot join more than one translation table in one query because it cause error.



 Comments   
Comment by Jonathan H. Wage [ 02/Mar/10 ]

Can you create a test case for this? You can find information about Doctrine unit testing here: http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

Comment by Mikhail Menshinskiy [ 28/Dec/11 ]

I have the same error.
How to solve this issue?





[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: