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

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

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

symfony 1.4.5, postgresql 8.4, debian lenny, nginx


Attachments: PNG File doctrine.png    

 Description   

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

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

sequence "Category_id_seq" does not exist

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

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

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



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

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

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

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

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

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

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

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





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

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

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

RHEL 6.0, mysql 5.1.52


Attachments: Text File migration.patch    

 Description   

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

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

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






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

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

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

windows



 Description   

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

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

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

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

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

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

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

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

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

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

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

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

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

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






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

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

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

apacha2, linux, Symfony 1.4



 Description   

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

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

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

We found the following solution

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

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

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

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

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






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

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

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

PHP 5.2, Symfony 1.4, Diem 5.1, Doctrine 1.2.2



 Description   

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

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

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

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

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



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

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

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

Comment by Daniele Dore [ 19/Sep/11 ]

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





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

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

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


 Description   

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






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

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

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


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

Throws:

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

Solution:

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

References:

Patch will be supplied soon ...



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

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

I guess we need more TestCases for the SubQuery stuff.

Comment by Enrico Stahn [ 02/Sep/10 ]

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





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

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

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

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

 Description   

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

Example:

 
ModelFoo:
  model_id as id
  username
  password

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

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



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

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

Comment by Enrico Stahn [ 18/Aug/10 ]

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





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

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

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

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



 Description   

When i execute this code:

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

Doctrine executes :

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

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

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

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

The problem is in Query.php line 1417 :

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

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

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

An other problem is probably located at line 1409

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

and 1497

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

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






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

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

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

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



 Description   

When i execute this code:

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

Doctrine executes :

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

The problem is in function _createLimitSubquery in Doctrine_Connection_Oracle :

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

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

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





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

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

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

Attachments: Text File DC-1032.patch    

 Description   

$record instanceof Doctrine_Record;
$collection instanceof Doctrine_Collection;

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

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

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

See attached patch.






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

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

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

windows ,wamp,php



 Description   

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






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

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

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


 Description   

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

After adding SQLT_INT everything is ok






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

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

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

LAMP



 Description   

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

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

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

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

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

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

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






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

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

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

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


Attachments: File DC747TestCase.php    

 Description   

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

Example:

Authority:
columns:
a_id:

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

name:

{ type: string }

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

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

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

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



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

Here is the test updated with the current ticket number.

Comment by Enrico Stahn [ 17/Jun/10 ]

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

Comment by Enrico Stahn [ 17/Jun/10 ]

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

  • remove autoincrement
  • add sequence name manually

Example:

Authority:
columns:
a_id:

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

name:

{ type: string }




[DC-1050] Doctrine_Relation_ForeignKey ignores ATTR_COLL_KEY attribute Created: 06/Mar/12  Updated: 17/Apr/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    

 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





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

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

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

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


Attachments: Zip Archive Doctrine_Timestampable_Alias.zip    

 Description   

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

 
<?php

abstract class Content_Article extends Doctrine_Record
{

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

}

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

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

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

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

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

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






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

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

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

All



 Description   

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

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

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

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

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

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

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



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

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





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

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

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


 Description   

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

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






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

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

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


 Description   

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

patch and test case @ github






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

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

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


 Description   

Hi Jon,

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

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

public function isValidated()

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

}

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



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

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

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

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

Comment by Enrico Stahn [ 02/Sep/10 ]

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





[DC-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-741] Sort of Migration Class Problem With More Than 9 Classes Created: 16/Jun/10  Updated: 17/Apr/14

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

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

Ubuntu 10.04, PHP 5.3.2, Doctrine 1.2.2


Attachments: Text File DC-741.patch    

 Description   

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

php doctrine-cli.php migrate 10

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

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

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



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

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

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

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

Can you help me with how to reproduce the error?





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

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

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

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


Attachments: Text File Doctrine-DC-1000.patch    

 Description   

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

By example, when you track the having clause interpretation:

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

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

I just fix it using:

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

instead of:

return $this->_parseAliases($func);

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

See patch attached...

Loops






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

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

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

OS X 10.6.6 with PHP 5.3.3, Windows with PHP 5.3.1


Attachments: File models.yml     Zip Archive test.zip    

 Description   

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

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

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

Applying the query:

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

and then producing output though

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

produces the expected:

Results (1): 1
alpha

Doing a similarly query to a new variable:

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

and printing with

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

produces the expected:

Results (2): 1
aleph

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

Results (1): 1
aleph

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

If, the second query was altered to

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

then all three output results are as expected.

test.zip contains corresponding test files.






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

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

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

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


Attachments: File Doctrine_Locking_Manager_Pessimistic.diff    

 Description   

When using pessimistic locking as described in:

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

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

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

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

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



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

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

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

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





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

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

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

WAMP stack - PHP 5.3



 Description   

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

Example:

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

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

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

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

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


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

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

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

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

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

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

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

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

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

C

Comment by Adam Benson [ 19/Nov/10 ]

Updated affected versions

Comment by Adam Benson [ 19/Nov/10 ]

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

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

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





[DC-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-389] query cache doesn't cache _isLimitSubqueryUsed Created: 26/Dec/09  Updated: 17/Apr/14

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

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

Postgres db, php5.2, linux



 Description   

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

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

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


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

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

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





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

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

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


 Description   

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

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

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

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

{{
Kitten:
Kitten1:
Basket: Basket1

Basket:
Basket1:
FluffiestKitten: Kitten1
}}

Will result in either fluffiest_kitten_id or basket_id being set to 0

See also ticket DC-555






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

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

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


 Description   

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

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

I suspect it only affects queries without explicitly listed fields.

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



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

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

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





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

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

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

Windows 7 x86_64, PHP 5.3



 Description   

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

The test case files are as follows:

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

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






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

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

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

Attachments: Text File doctrine_toarray-deep_fix.patch    

 Description   

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

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






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

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

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


 Description   

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

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

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

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

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

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





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

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

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

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


Attachments: Text File DC-1029.patch    

 Description   

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

Why ? Just because of this line :

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

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

The bug is very simple to reproduce :

1. Get a classic I18n fixtures like :

Article:
Translation:
en:
title: Lorem Ipsum

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

class My_Doctrine_Template_I18n extends Doctrine_Template_I18n {}

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

Thanks



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

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

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

Thanks

Comment by Pierrot Evrard [ 18/Aug/11 ]

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

What do you think about that ?

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





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

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

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


 Description   

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

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






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

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

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


 Description   

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

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

A mention of the feature

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

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



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

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





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

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

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

doctrine, symfony, linux, hpux


Attachments: File closeCursor.diff    

 Description   

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

Doctrine2 should also be affected by this bug.

Change:
public function closeCursor()

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

To:
public function closeCursor()

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




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

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

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

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


Attachments: Text File fix_boolean_default_mysql_column_migration.patch    

 Description   

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

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

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

{main}

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

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

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






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

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

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

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


Attachments: File schema.yml     File test.yml    

 Description   

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

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

Artist
-Album
-Song
-Comments

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

thus, the UnitOfWork - builtFlushTree should generate

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

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

which in turn generates:

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

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

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



 Comments   
Comment by Ochoo [ 10/Sep/10 ]

found a tiny BUG, submitting the fix.

EDIT: scratch the rest from here.

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

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

Comment by Ochoo [ 10/Sep/10 ]

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

Comment by Ochoo [ 10/Sep/10 ]

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

Comment by atali daoud [ 29/Nov/10 ]

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

Comment by Ochoo [ 01/Dec/10 ]

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





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

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

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

PHP 5.2.11 (with Suhosin-Patch 0.9.7)
PHP 5.3.6


Attachments: File DC373TestCase.php    

 Description   

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

First, I defined the following schema.yml::

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

Next, I prepared the following fixture file::

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

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

And I write the following code::

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

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

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


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

Good Morning,

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

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

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

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

Thanks to let me know as soon as possible.

Arnaud

Comment by Joe Siponen [ 27/May/11 ]

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

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

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

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

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

Maybe do it like this perhaps:

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

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

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

      $this->buildRelation();

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

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

Failing test case attached

Comment by Kousuke Ebihara [ 08/Jun/12 ]

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

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

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

Comment by Kousuke Ebihara [ 11/Sep/12 ]

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

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





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

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

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


 Description   

Hi,

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

Here is an example:

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

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

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

Can you help me please?

With kind regards
Stephan






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

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

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

Attachments: File doctrine_bug_diff.diff    

 Description   

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

The fix (diff):

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

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

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



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

The diff output as .diff





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

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

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

karmic, php 5.2.10, apache2


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

 Description   

When writing a query such as

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

you are unable to then

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

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

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



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

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

Comment by alex pilon [ 06/May/11 ]

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





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

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

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


 Description   

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

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





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

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

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

PHP 5.2, 5.3


Attachments: File Query.pendingjoin.diff    

 Description   

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

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

Example

For instance, the following query exhibits this problem:

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

This query emits the following SQL:

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

which returns also a deleted row.

Expected behavior

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

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

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

Full test case details:

init.sql

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

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

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

run.php

<?php

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

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

require "SoftDeleteTest.php";

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

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

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

SoftDeleteTest.php (copied from Doctrine manual)

<?php

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

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


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

Fixing quote formatting

Comment by Walter Hop [ 03/Dec/10 ]

Final formatting fixes.





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

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

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

All



 Description   

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






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

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

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

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


Attachments: Text File fix_google18n_and_similiar_import_problem.patch    

 Description   

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

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

{main}

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

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

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

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



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

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





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

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

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

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



 Description   

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

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

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

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

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

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



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

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





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

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

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

linux, apache2, php 5.3



 Description   

Ok, so the object relations go like this:

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

The testing code looks like following:

== CODE START ==

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

/* Filling $comp with data */

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

    $product = new Application_Model_Product();

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

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

        $param = new Application_Model_Parameter();

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

            $option = new Application_Model_Option();

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

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

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

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

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

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

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

$comp->save();

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

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

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

$comp->save();

== CODE END ==

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






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

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

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

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



 Description   

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

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

thnx.






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

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

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


 Description   

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

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






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

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

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

MySQL database, Lenny



 Description   

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

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

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

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

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

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

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






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

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

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


 Description   

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

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


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

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

Comment by Enrico Stahn [ 27/Aug/10 ]

see DC-841





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

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

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

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


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

 Description   

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

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

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

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

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

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

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

the following queries:

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

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

will output the following:

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

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

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

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



 Comments   
Comment by suhock [ 26/Apr/10 ]

attached a test case for this bug

Comment by suhock [ 26/Apr/10 ]

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

Comment by Dan Ordille [ 30/Aug/10 ]

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

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

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

Comment by suhock [ 21/Sep/10 ]

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

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

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

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

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





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

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

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

Symfony 1.4.11 , Ubuntu 11, PHP 5.3



 Description   

I had to define this function:

public function deactivate($segment_id)

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

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

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






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

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

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

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



 Description   

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

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

therefore generating a syntax error.

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

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

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

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

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

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





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

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

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


 Description   

Example:

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

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



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

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

Comment by Enrico Stahn [ 27/Aug/10 ]

Patch added to github (see above)

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

Comment by Enrico Stahn [ 02/Sep/10 ]

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





[DC-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-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-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-1049] error with Timestamp data Validation Created: 26/Feb/12  Updated: 17/Apr/14

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

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

Linux


Attachments: File Timestamp.php    

 Description   

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

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

{ return true; }

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

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

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

{ return false; }

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

return true;
}






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

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

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

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



 Description   

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

To reproduce:

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

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

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

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

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



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

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





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

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

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


 Description   

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

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

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

The proper SQL to be generated should be:

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


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

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





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

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

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

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



 Description   

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

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

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

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

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

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

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

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






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

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

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

ubuntu, apache, symfony version 1.4.4


Attachments: Text File DC-756.partial.patch    

 Description   

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

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

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



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

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

$maxDaysDetailsToProcess=3;

as the fourth line in the code.

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

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

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

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

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





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

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

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

XP Xamp


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

 Description   

Hi All

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

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

It produces this correct DQL:

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

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

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

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

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

SELECT DISTINCT p3.id FROM product_customers p3 LIMIT 20

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

Here is my sample schema in case its helpful.

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

Thanks much.

Will Ferrer

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



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

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

Comment by will ferrer [ 08/Jun/10 ]

Hi Jon

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

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

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

Does Doctrine 2 fix this problem?

Thanks for the help.

Will Ferrer

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

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

Comment by will ferrer [ 08/Jun/10 ]

Hi Jon

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

Thanks again for your help.

Will Ferrer

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

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

Comment by will ferrer [ 10/Jun/10 ]

Hi Jon

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

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

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

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

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

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

and

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

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

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

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

Hope you are well.

Will Ferrer

Comment by will ferrer [ 10/Jun/10 ]

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

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

Thanks for the issue and patches.

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

Comment by will ferrer [ 01/Sep/10 ]

individual patch for this issue with out other features included

Comment by will ferrer [ 01/Nov/10 ]

adding test cases for these features

Comment by will ferrer [ 01/Nov/10 ]

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





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

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

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

Revision: 104


Attachments: Text File replaceBoundParamsWithInlineValuesInQuery.patch    

 Description   

Hello,

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

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

Kind regards
Peter



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

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

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

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

Kind regards,
Peter





[DC-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.





Generated at Fri Apr 18 00:29:55 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.