[DC-313] Ordering m2m relationship with column from related table (with orderBy option) Created: 02/Dec/09  Updated: 18/Feb/11

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

Type: Bug Priority: Blocker
Reporter: Maciej Hołyszko Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 3
Labels: None
Environment:

php 5.3/win, doctrine 1.2 svn, ATTR_QUOTE_IDENTIFIER = true, ATTR_USE_DQL_CALLBACKS = true


Attachments: File DC313TestCase.php    

 Description   

I find no way to define automatic orderBy in m2m relations with column not from reference table, but actual related table.

E.g. BlogPost <= m2m through BlogPostCategory => BlogCategory
I need BlogPost->Categories ordered by BlogCategory.name

class BlogPost extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('title', 'string', 128);
        $this->hasColumn('content', 'string');
    }
    
    public function setUp()
    {
        $this->hasMany('BlogCategory as BlogCategories', array('local' => 'id_blog_post', 'foreign' => 'id_blog_category', 'refClass' => 'BlogPostCategory', 'orderBy' => 'name'));        
    }
}

class BlogCategory extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('name', 'string', 128);
    }
    
    public function setUp()
    {
        $this->hasMany('BlogPost as BlogPosts', array('local' => 'id_blog_category', 'foreign' => 'id_blog_post', 'refClass' => 'BlogPostCategory'));
    }
}

class BlogPostCategory extends Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->hasColumn('id_blog_post', 'integer', null, array('primary' => true));
        $this->hasColumn('id_blog_category', 'integer', null, array('primary' => true));
    }
    
    public function setUp()
    {
        $this->hasOne('BlogPost', array('local' => 'id_blog_post', 'foreign' => 'id', 'onDelete' => 'CASCADE'));
        $this->hasOne('BlogCategory', array('local' => 'id_blog_category', 'foreign' => 'id', 'onDelete' => 'CASCADE'));
    }
}

The resulting query contains doubled 'name' column in ORDER BY clause, both from reference table and related table, e.g. ORDER BY t2.name, t3.name

I tried putting the following code in BlogCategory::setTableDefinition() instead of attribute in relation definition in BlogPost record:

$this->option('orderBy', 'name');

but the result was the same.

Maybe I'm doing something wrong? Is there a possibility to define an alias, where to get column name from - in orderBy attribute?

Thanks in advance.



 Comments   
Comment by Maciej Hołyszko [ 02/Dec/09 ]

Attached test case.

Comment by Maciej Hołyszko [ 08/Dec/09 ]

I find this issue as critical one now, because when I use e.g.

$this->option('orderBy', 'name');

in a model's definition (not ref class), then when other model is related m2m with it, a query loading both of them with relations will fail because of name column duplicated in ref table.

Comment by suhock [ 23/Apr/10 ]

I am having the same issue with an equivalent test case. For some reason, the 'orderBy' option on the target of the join (set by calling the option() function inside the setUp() method of the model class, not the ref class) is being applied to the relation table. After digging through the 1.2.2 tag a bit, I found altering line 1319 of Query.php as follows seems to fix the problem (at least against my test cases):

if (isset($map['relation'])) {
if (isset($map['relation']) && $map['relation']->getTable() === $map['table']) {

I'll do some more thorough testing and submit a patch if I find time.

Comment by Bart W [ 17/Feb/11 ]

I had this issue as well. suhock's solution fixed it for me. It would be nice if this was merged in to a bug fix release of Doctrine 1.x.

Comment by suhock [ 18/Feb/11 ]

I ended up creating a new ticket, DC-651, which addresses a more general problem with the orderBy feature. You should use the attached Ticket_DC651.patch instead, as I found the solution I provided here is not completely correct and does not pass all test cases.





[DC-627] Work on link-table and leftJoin Created: 13/Apr/10  Updated: 13/Apr/10

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

Type: Bug Priority: Blocker
Reporter: Thomas Tourlourat - Armetiz Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows Seven - WAMP 2.0i


Attachments: PNG File composition.png    

 Description   

Looking at the attachment to see the little schema.
Tree table : items, items_children and children.

The link-table items_children is here to create a many-to-many relationships between Items and Children.

So, after configure the YAML and generated Models.
We can do something like that :

$query = Doctrine_Query::create ()
->select ("items.title, children.title")
->from ("Item items")
->leftJoin ("item.children children");
$items = $query->execute ();

$items //An array of items
$items[0]->title //A string
$items[0]->children //An array of children

The SQL Output of the query is :

SELECT `i`.`id_item` AS `i_id_item`, `i`.`title` AS `ititle`, `c`.`id_child` AS `cid_child`, `c`.`title` AS `c_title` FROM `items` `i` LEFT JOIN `items_children` `i2` ON (`i`.`id_item` = `i2`.`id_item`) LEFT JOIN `children` `c` ON `i2`.`id_child` = `c`.`id_child`

All array are order by something, in this case it's a natural order which come from the items_children order into database.

Now, I want to apply a condition, or a filter on the items_children table.
If I translate my demand to SQL Query :

SELECT `i`.`id_item` AS `i_id_item`, `i`.`title` AS `ititle`, `c`.`id_child` AS `cid_child`, `c`.`title` AS `c_title` FROM `items` `i` LEFT JOIN `items_children` `i2` ON (`i`.`id_item` = `i2`.`id_item`) LEFT JOIN `children` `c` ON `i2`.`id_child` = `c`.`id_child` ORDER BY `c1`.`index`

Or something crazy :

SELECT `i`.`id_item` AS `i_id_item`, `i`.`title` AS `ititle`, `c`.`id_child` AS `cid_child`, `c`.`title` AS `c_title` FROM `items` `i` LEFT JOIN `items_children` `i2` ON (`i`.`id_item` = `i2`.`id_item`) LEFT JOIN `children` `c` ON `i2`.`id_child` = `c`.`id_child` WHERE `c1`.`index` > 2

But how can I do that with DQL ? Because I have no access to the Link-table.

Link-Table are use to create many-to-many, that could be OOP array. So we have to be allowed to add "index" to order the result. Also, we have to be allowed to add condition on this tables, like "datePromote" or simply "enabled".

The solution should be on the following DQL Query :

$query = Doctrine_Query::create ()
->select ("items.title, children.title")
->from ("Item items")
->leftJoin ("item.children children")
->leftJoin ("ItemsChildren link_table")
->orderBy ("link_table.index")
$items = $query->execute ();

But the SQL Output is :

SELECT `i`.`id_item` AS `i_id_item`, `i`.`title` AS `ititle`, `c`.`id_child` AS `cid_child`, `c`.`title` AS `c_title` FROM `items` `i` LEFT JOIN `items_children` `i2` ON (`i`.`id_item` = `i2`.`id_item`) LEFT JOIN `children` `c` ON `i2`.`id_child` = `c`.`id_child`, `items_children` `i3` ORDER BY `i3`.`index`

To conclude, it's a blocker problem. Because I can't use a standard DB schema.

Regards,
Armetiz.






[DC-665] Named parameters doesn't work on MSSQL anymore Created: 05/May/10  Updated: 22/Sep/10

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

Type: Bug Priority: Blocker
Reporter: Dennis Pettersson Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows Server 2003. PHP 5.2.12. MS SQL Server 2008



 Description   

After upgrading to Doctrine 1.2.2 queries with named arguments doesn't work anymore.
Whenever querying like
$query = Doctrine_Query::create();
$customer = $query->from('Customers')
->where("id = :id"
, array('id'=>$user['customer_id']))
->fetchOne(array(), Doctrine::HYDRATE_ARRAY);

I get the error
SQLSTATE[HY000]: General error: 10007 Incorrect syntax near ':'. [10007] (severity 5)

If changing the query to
$query = Doctrine_Query::create();
$customer = $query->from('Customers')
->where("id = ?"
, array($user['customer_id']))
->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
it works fine.
Testing with MySQL works fine, so it seems contained to MSSQL



 Comments   
Comment by Dennis Pettersson [ 06/May/10 ]

Should mention I upgraded from 1.1.6 to 1.2.2, so the problem might be present in earlier 1.2.x versions as well.





[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-770] Result Cache Created: 29/Jun/10  Updated: 29/Jun/10

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

Type: Bug Priority: Blocker
Reporter: Thomas Tourlourat - Armetiz Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Doctrine result cache isn't working properly.

Here a simple example, when I'm calling query->execute (); parentProgram is related to a video.
Into the Doctrine_Query_Abstract.php file

line 1014 : I have just add some code to output data.
[code]
if ($cached === false)

{ // cache miss $stmt = $this->_execute($params); $this->_hydrator->setQueryComponents($this->_queryComponents); $result = $this->_hydrator->hydrateResultSet($stmt, $this->_tableAliasMap); $oVideo = $result[0]; echo "not cached "; var_dump (count ($oVideo->parentProgram->getReferences ())); $cached = $this->getCachedForm($result); $cacheDriver->save($hash, $cached, $this->getResultCacheLifeSpan()); }

else

{ $result = $this->_constructQueryFromCache($cached); $oVideo = $result[0]; echo "cached "; var_dump (count ($oVideo->parentProgram->getReferences ())); exit (0); }

[/code]

The output of a query execution (the first with an empty APC cache) with "useResultCache" is :

  • not cached int(1)
  • cached int(0)

The problem is coming from the serialize php function that can't serialize protected properties..
getReferences is a getter to a protected property.. So data result can't work properly.

A solution could be use __sleep function, and a public property that contain all important protected data.






[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-839] Version classes not built for models using package attribute Created: 24/Aug/10  Updated: 08/Mar/11

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

Type: Bug Priority: Blocker
Reporter: Prasad Gupte Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

PHP 5.2.3 / Symfony 1.4.6



 Description   

For models using the 'package' attribute in the schema definition, the version classes do not get created. However, the version table gets created.

There is no problem during the build, but when loading fixtures, there is a fatal error: Class TaxCodeVersion not found

TaxCode:
package: Masters
tableName: Fin_Tax_Codes
actAs:
Activateable: ~
SoftDelete: ~

  1. Versionable:
  2. tableName: fin_tax_codes_version
    1. versionColumn: version
  3. className: %CLASS%Version
    1. auditLog: true
      Auditable: ~
      Timestampable: ~
      .......


 Comments   
Comment by hetsch [ 08/Mar/11 ]

Same here,

If i use this yaml file:

Page:
actAs:
NestedSet:
hasManyRoots: true
rootColumnName: root_id
Versionable:
versionColumn: version
className: %CLASS%Version
auditLog: true
Timestampable:
created:
name: created_at
type: timestamp
format: Y-m-d H
updated:
name: updated_at
type: timestamp
format: Y-m-d H
I18n:
fields: [name]
columns:
name: string(255)

PageVersion and PageTranslation Models don't get generated if i use 'build-models-yaml'. Have to create the Models manually then it works fine.





[DC-860]  0 down vote favorite In some circumstances Doctrine_Core::getTable('%Name%') returns Doctrine_Table instance instead of %Name%Table one. Created: 06/Sep/10  Updated: 06/Sep/10

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

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

WinXP, Apache, PHP 5.2.14



 Description   

In some circumstances Doctrine_Core::getTable('%Name%') returns Doctrine_Table instance instead of %Name%Table one.
So custom %Name%Table's methods become unavailable.

In order to give a demonstration of this improper behavior : here is a schema of small issue tracking system

User:
actAs: [Timestampable]
tableName: issue_user
columns:
user_id:

{ type: integer, primary: true, autoincrement: true }

user_name:

{ type: string(255) }

user_role:

{ type: enum, values: [worker, dispatcher, manager] }

managed_by:

{ type: integer }

password:

{ type: string(32) }

salt:

{ type: string(32) }

relations:
Manager:
foreignAlias: Workers
class: User
local: managed_by
foreign: user_id
type: one
foreignType: many

Issue:
actAs: [Timestampable]
columns:
issue_id:

{ type: integer, primary: true, autoincrement: true }

from_ceh:

{ type: string(255) }

from_name:

{ type: string(255) }

from_phone:

{ type: string(255) }

from_location:

{ type: string(255) }

comp_name:

{ type: string(255) }

comp_serial:

{ type: string(255) }

comp_os:

{ type: enum, values: [Win95, Win98, WinNT, WinME, Win2000, WinXP, Vista, Win7] }

issue_title:

{ type: string(255) }

comment:

{ type: string(255) }

owner_id:

{ type: integer }

is_executed:

{ type: bool }

relations:
Owner:
onDelete: CASCADE
foreignAlias: Issues
class: User
local: owner_id
foreign: user_id
type: one
foreignType: many

When I just call Doctrine_Core::getTable('User') it returns UserTable instance, but if I call it after such a query:

Doctrine_Query::create()
->select('u.user_id, ws.user_id, i.*')
->from('User u, u.Workers ws, ws.Issues i')
->where('u.user_id=', $manager_id)
->fetchArray();

calling Doctrine_Core::getTable('User') returns Doctrine_Table instance






[DC-918] Causing ORA-01791 when try to sort on relation field and use limit in query to Oracle DB Created: 06/Nov/10  Updated: 06/Nov/10

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

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

Windows 2003 Server, Oracle 10g, Symfony 1.4.8



 Description   

Schema in yml format
in Symfony it looks more simple, but i'm going to show relation in detail

PrType:
  columns:   
    name:                   { type: string(255), notnull: true }                          

PrTypeTranslation:
  columns:   
    id:                     { type: integer, notnull: true }
    name:                   { type: string(255), notnull: true }
    lang:                   { type: string(255), notnull: true }
  relations:
    PrType:                 { onDelete: CASCADE, local: id_id, foreign: id, foreignAlias: Translation }

When i try to execute this code:

   $q = Doctrine_Query::create()
            ->from('PrType tp')
            ->leftJoin('tp.Translation t WITH t.lang = ?', 'ru')
            ->orderBy('t.name')
            ->limit(10);

doctrine executes next statement:

SELECT "p"."id", "p2"."name" AS "p2__name", "p2"."lang" AS "p2__lang"
FROM "pr_type" "p"
LEFT JOIN "pr_type_translation" "p2" ON "p"."id" = "p2"."id" AND ("p2"."lang" = :oci_b_var_1)
WHERE "p"."id" IN (
              SELECT a."id" FROM ( 
                          SELECT DISTINCT "p3"."id"
                          FROM "pr_type" "p3"
                          INNER JOIN "pr_type_translation" "p4" ON "p3"."id" = "p4"."id" AND ("p4"."lang" = 'ru') 
                          ORDER BY "p4"."name" ) a 
                          WHERE ROWNUM <= 10) 
ORDER BY "p2"."name"

This sql code produces next error

ORA-01791: not a SELECTed expression

Error occures, because (from ORACODE)

There is an incorrect ORDER BY item. The query is a SELECT DISTINCT query with an ORDER BY clause. In this context, all ORDER BY items must be constants, SELECT list expressions, or expressions whose operands are constants or SELECT list expressions



 Comments   
Comment by Dmitriy [ 06/Nov/10 ]

Some very similar issue were reported and resolved here http://trac.doctrine-project.org/ticket/1038.

Comment by Dmitriy [ 06/Nov/10 ]

Reason of issue was founded. It appears because i'm using oci8 driver, and this drivername not be listed in if statement on line 1401 in Doctrine/Query.php:

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

I changed to:

LINE 1401: if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8' || $driverName == 'mssql' || $driverName == 'odbc') {

Sorry, but i don't know how to create patch diff file.





[DC-926] Doctrine ignored PORTABILITY_FIX_CASE and ATTR_FIELD_CASE settings when building query Created: 12/Nov/10  Updated: 12/Nov/10

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

Type: Bug Priority: Blocker
Reporter: Dziamid Zayankouski Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Tested on CentOS 5, Ubuntu 10.4, MYSQL and MSSQL databases



 Description   

Setting:
$conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_FIX_CASE)
$conn->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, CASE_UPPER)

I expect column names in built queries to be uppercase, but they remain to be lowercase.






[DC-952] Non-Equal Nest Relations Not Working - from "Children" side Created: 03/Jan/11  Updated: 24/Mar/11

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

Type: Bug Priority: Blocker
Reporter: Paweł Barański Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 4
Labels: None
Environment:

Ubuntu 10.04 + PHP 5.3.3 + Symfony 1.4.8


Attachments: File DC952TestCase.php    
Sub-Tasks:
Key
Summary
Type
Status
Assignee
DC-958 updating Models with Intra-Table Rela... Sub-task Open Jonathan H. Wage  

 Description   

I've copy & pasted example from http://www.doctrine-project.org/projects/orm/1.2/docs/manual/defining-models/1_0#relationships:join-table-associations:self-referencing-nest-relations:non-equal-nest-relations .
I've created User backend module using doctrine:generate-admin backend User task. On how to reproduce the error:

1. Add 3 User objects (A,B,C)
2. Open generated edit form for User A.
3. Set User B as Children from Children list and Save
4. Set User B and C as Chidren from Children list and Save

As a result you will see only C set as Children, and strange situation in database :

UserReference Table:

parent_id | child_id
pk_B | pk_B (!!!)
pk_A | pk_C



 Comments   
Comment by Paweł Barański [ 06/Jan/11 ]

Same ticket on symfony trac because I'm not sure whose fault is it

http://trac.symfony-project.org/ticket/9398

Also some new error path there

Comment by Daniel Reiche [ 24/Mar/11 ]

Test Case of Non-Equal Self-Referencing Relations, based on #DC-329.

Failure occures in line 75 of the test case file. This should not happen!
Only the parent object is modified in line 73 and saving should not interfere with the relations.





[DC-962] Broken logic when doctrine translates limit's into subqueries, with joins. (with patch) Created: 02/Feb/11  Updated: 02/Feb/11

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

Type: Bug Priority: Blocker
Reporter: Ben Davies Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

All


Attachments: Text File Query.php.patch     Text File Tests.patch    

 Description   

Problem exists when Doctrine formulates a subquery to perform a limit when a join in included.

The problem is that the where clause that doctrine creates for the subquery (the WHERE IN clause) is inserted as the first where clause.
This will break the parameter duplicate done at Doctrine_Query_Abstract:969, as the order of the parameters is now wrong.

Consider:

 
select * from table
join metadata WITH c = ?
where a = ? and b = ?
limit 1

with parameters be (1, 2, 3)

Doctrine will translate this to

 
select * from table
join metadata WITH c = ?
where table.id IN (
    select id from table
    join metadata WITH c = ?
    where a = ? and b = ?
    limit 1
)
and a = ? and b = ?

Doctrine will duplicate the params (Doctrine_Query_Abstract:969) to (1, 2, 3, 1, 2, 3), but now they are in the wrong order completely.
They should be (1,1,2,3,2,3).

The easy fix is to move the limit subquery to the LAST where clause, which would reuslt in a query like so:

 
select * from table
join metadata WITH c = ?
where a = ? and b = ?
and table.id IN (
    select id from table
    join metadata WITH c = ?
    where a = ? and b = ?
    limit 1
)

Attached is a patch to fix this issue, along with a patch that fixes all unit tests referring to the old query format.



 Comments   
Comment by Ben Davies [ 02/Feb/11 ]

upping to blocker since this breaks very basic queries





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

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

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

MySQL 5, PHP 5


Attachments: File BaseTerritoryCombined.php    

 Description   

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

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

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

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

A test query:

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

MY PROPOSED PATCH:

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

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

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

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



 Comments   
Comment by Mishal [ 18/Jul/13 ]

Bringing dead things back to life

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





[DC-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-1025] Doctrine is unable to handle table names with spaces Created: 02/Aug/11  Updated: 02/Aug/11

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

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

PHP Version 5.2.14
Apache 2
MySQL
Windows Xp


Attachments: File doctrineTest.php     File tbl.php     File tbl_1.php    

 Description   

When trying to query a table which contains spaces I get the following exception

I have attached an simple example to reproduce

C:\Documents and Settings\daniel\Dokumenter\NetBeansProjects\test>php doctrineTest.php

Fatal error: Uncaught exception 'Doctrine_Query_Exception' with message 'Unknown table alias with' in C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php:856
Stack trace:
#0 C:\Doctrine-1.2.3\Doctrine\Query.php(1022): Doctrine_Query_Abstract->getComponentAlias('with')
#1 C:\Doctrine-1.2.3\Doctrine\Query.php(1239): Doctrine_Query->_buildSqlFromPart()
#2 C:\Doctrine-1.2.3\Doctrine\Query.php(1133): Doctrine_Query->buildSqlQuery(true)
#3 C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php(958): Doctrine_Query->getSqlQuery(Array)
#4 C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php(1026): Doctrine_Query_Abstract->_execute(Array)
#5 C:\Documents and Settings\daniel\Dokumenter\NetBeansProjects\test\doctrineTest.php(18): Doctrine_Query_Abstract->execute()
#6

{main}

thrown in C:\Doctrine-1.2.3\Doctrine\Query\Abstract.php on line 856






[DC-1031] CLONE -Multiple connections and i18n (raised as unresolved - original ticket marked as resolved) Created: 23/Aug/11  Updated: 28/Mar/12

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

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

MySQL 5.1.37
PHP 5.2.11
symfony 1.2.11 DEV

symfony 1.4.13
PHP 5.3.6
Postgres 8.4.8



 Description   

I used to work with a single database named "doctrine". The query was working properly.

I then decided to use 2 databases so I got my schema like this:

connection: doctrine

Category:
actAs:
I18n:
actAs:
Sluggable:
fields: [name]
Timestampable: ~
fields: [name, description]
columns:
id: ~
name:
type: string(255)
notnull: true
description: string

User:
connection: second
columns:
id: ~
name:
type: string(255)
notnull: true

I did setup my connections in config/databases.yml this way:

all:
doctrine:
// ....
second:
// ....

build-model, build-forms, build-filters and cc got ran. But now, I got an exception saying the "Translation" relation doesn't exist. The Base Models include correctly the bindComponent line:

Doctrine_Manager::getInstance()->bindComponent('Category', 'doctrine');

For now, I managed to kind of fixing it with simply swapping the databases order in my config/databases.yml and it's now working again perfectly.

I forgot to mention that in the CategoryTable when i call $this->getConnection()->getName(), it outputs "second"



 Comments   
Comment by James Bell [ 23/Aug/11 ]

Original issue: DC-363 (http://www.doctrine-project.org/jira/browse/DC-363)

There are some additional comments in there that explain the issue as currently being seen in released versions of Doctrine 1.2. Can I help verify that this is the same ticket?

What is needed to help with debug (in addition to the extra information already provided)?

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

meet the same issue and it really blocked my project, seems no one will maintain 1.x. I'm considering whether to replace symfony 1.4 with 2.0.





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

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

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

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



 Description   

When i execute this code:

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

Doctrine executes :

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

The problem is in function _createLimitSubquery in Doctrine_Connection_Oracle :

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

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

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





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

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

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

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



 Description   

When i execute this code:

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

Doctrine executes :

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

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

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

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

The problem is in Query.php line 1417 :

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

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

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

An other problem is probably located at line 1409

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

and 1497

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

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






[DC-1040] allow queries with table joins across different databases Created: 17/Nov/11  Updated: 17/Nov/11

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

Type: Improvement Priority: Blocker
Reporter: Fabrice Agnello Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows XP SP3, Apache 2, PHP 5.3, MySQL 5.1.36, Symfony 1.4.8, Doctrine 1.2.3


Attachments: File Query.php    

 Description   

I'm currently working on a project which relies upon several databases declared in databases.yml in symfony 1.4.8.

I was facing an issue that has already been raised by other people, namely that you can't join tables which reference each other among different mysql databases.

I've dug a bit in the Doctrine_Query class and came to a solution that is acceptable for us, and allows now to make joins accross databases. Description follows :

first change is in the Doctrine_Core class, that gets stuffed with a new constant :
const ATTR_DATABASE_NAME = 0x1DB;

this constant allows us to add a new attribute to the databases.yml file as in :
gesdoc:
class: sfDoctrineDatabase
param:
dsn: mysql:host=127.0.0.1;dbname=gesdoc
username: root
password:
attributes:

  1. ************* NEW ATTRIBUTE BELOW ************
    database_name: gesdoc
    default_table_collate: utf8_general_ci
    default_table_charset: utf8

after that, a few changes have been done in the Doctrine_Query class which is attached to this issue for the sake of readability.

This may not be optimal, and probably need some regression testing, but it is currently working fine on our test server.

after this is done, I was able to issue queries like the following :
$x = DocumentTable::getInstance()->createQuery('d')
->distinct()
->leftJoin('d.Travail t')
->leftJoin('t.CdcIndInt ci')
->leftJoin('ci.CdcIndExt ce')
->leftJoin('ce.Cahierdescharge cdc')
->where('cdc.cdc_chro = ?', $cdc_chro)
->addWhere('d.id != ?', $document_id)
->execute();

where the referenced tables are in different databases. The necessary object binding has been done in every model class following the paradigm :

Doctrine_Manager::getInstance()->bindComponent('CdcIndInt ', 'gescdc');
abstract class BaseCdcIndInt extends sfDoctrineRecord
{
...
}

I don't know if this description is clear enough, so let me know if something is missing/wrong.






[DC-347] AddPendingJoinConditions doesn't work if alias equals model name Created: 09/Dec/09  Updated: 29/Jan/10

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

Type: Bug Priority: Critical
Reporter: Christian Jaentsch Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File AliasEqualsModelNameTestCase.php    

 Description   

If the alias in a from-query is equal to the model name, I get an exception when executing the query after adding a "pendingJoinCondition".

See attached testCase.



 Comments   
Comment by David Abdemoulaie [ 29/Jan/10 ]

I fail to see why you would use an alias that is equal to the model name.

Comment by Christian Jaentsch [ 29/Jan/10 ]

To clarify again: Using an alias equal to the model name is the same as not using an alias at all. The built sql is the same afterwards (and the addPendingJoinCondition behaviour is the same as well).

I would not use an alias equal to the model name myself, but sometimes this is used in Doctrine core, e.g. in Doctrine_Relation_ForeignKey around line 60. So to solve the problem either all the core queries, where no alias or an alias equal to the model name is used, have to be rewritten or the behaviour of a respective query has to be changed somehow so that applying an addPendingJoinCondition is possible even in the given case.





[DC-371] Lazy loading - doctrine makes extra queries into db Created: 19/Dec/09  Updated: 23/Dec/10

Status: Open
Project: Doctrine 1
Component/s: Behaviors, Documentation, Query, Record
Affects Version/s: 1.2.0-BETA3
Fix Version/s: None

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

Symfony 1.4, Doctrine Version: 1.2.0-BETA3



 Description   

Just downloaded symfony 1.4

First of all I have a query:

$q = \Doctrine_Query::create()
->select('u., ur.')
->from('UserDb u')
->leftJoin('u.RealUserDetailsDb ur')
->leftJoin('u.MockUserDetailsDb um')
->where('u.id = :user_id')
;
$user = $q->fetchOne(array(':user_id' => $uid));

After that I'm accessing the fields of this object:

$userArray = array(
'id' => $this->getUser()->getId(),
'real_user_details_id' => $this->getUser()->getRealUserDetailsId(),
'mock_user_details_id' => $this->getUser()->getMockUserDetailsId(),
'real_user_details' => array(),
'mock_user_details' => array()
);

This is the actual queries into DB:

NR1:
SELECT u.id AS u_id, u.user_real_id AS uuser_real_id, u.user_mock_id AS uuser_mock_id, u2.id AS u2id, u2.nickname AS u2nickname, u2.email AS u2_email FROM user u LEFT JOIN user_real u2 ON u.user_real_id = u2.id LEFT JOIN user_mock u3 ON u.user_mock_id = u3.id WHERE (u.id = :user_id)

NR2:
SELECT u.id AS u_id, u.user_real_id AS uuser_real_id, u.user_mock_id AS u_user_mock_id FROM user u WHERE (u.id = '1') LIMIT 1

As you can see there are TWO queries however there should be only one query. The problem is that u.user_real_id is NULL in database and when I do 'real_user_details_id' => $this->getUser()->getRealUserDetailsId() doctrine does not have enough intelligence to understand that these fields have been already requested in NR1. If I comment this field, everything works well.

SURPRISE!
And now a surprise... if I modify a little bit my first query: ">select('u.')" instead of , ">select('u., ur.*')" it WON'T make TWO queries. It will make ONLY ONE!

As you understand this a very critical bug and of course our system won't go to production with this bug.

P.S. Is it possible to turn off the lazy loading in doctrine?



 Comments   
Comment by Roman Drapeko [ 17/Jan/10 ]

Any comments? Will it be fixed??

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

Hi, I'd like to take a look but can you make a failing test case that I can run so that I can see if I can come up with a patch that fixes your case and doesn't break anything else.

Comment by Luke Winiarski [ 01/Jun/10 ]

Hi

I had similar problem but after several hours i did work it out

Try to make get method in your model for getting field which has NULL value in database

public function getUserRealId()

{ return $this->_get("user_real_id", false); }

by making second argument false u force doctrine not to lazy load value and extra sql query is not created

regards

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

Has anyone been able to reproduce this in a test case? I am not having much luck so far.

Comment by Gennady Feldman [ 23/Dec/10 ]

I've seen this a ton of times. Basically when it loads related records through the Hydrator using leftJoin() and gets NULLs back. BUT it doesn't save the fact that the related records are NULL. So when you actually do call to getRelated objects it sees that it doesn't have the value cached and runs the query again.

Let me know if I should show you the problem in the Doctrine code base.





[DC-489] Doctrine_Record seems to have a bug with default values when updating Created: 10/Feb/10  Updated: 20/Jan/11

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

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

PHP 5.2.11



 Description   

So lets see the table:

User:
tableName: users
columns:
id:
type: integer(1)
fixed: false
unsigned: true
primary: true
autoincrement: true
username:
type: string(32)
fixed: false
unsigned: false
primary: false
notnull: true
autoincrement: false
password:
type: string(48)
fixed: false
unsigned: false
primary: false
notnull: true
autoincrement: false
role:
type: enum
fixed: false
unsigned: false
values:

  • admin
  • support
    default: support <----- Unable to render embedded object: File (ROOT OF EVIL) not found.
    primary: false
    notnull: true
    autoincrement: false

So lets say we have a user with `role` = 'support' and want to set em
'admin' we wrote

$user = new App_Model_User();
$user->assignIdentifier(1);
$user->role = 'admin';
$user->save();
var_dump($user->toArray());

in debugger we see SQL query been made:

  1. [0.55 ms] UPDATE users SET role = ? WHERE id = ?
  • bindings: admin
  • 1

array(6)

{ ["id"]=> int(1) ["display_name"]=> string(13) "Administrator" ["username"]=> string(4) "root" ["password"]=> string(40) "45bb0f589525a2f0f2a48620bb59b1b8baef0c1d" ["role"]=> string(5) "admin" ["is_active"]=> bool(true) }

Superb! Works as it should! So lets now set role of this user back to
'support':

$user = new App_Model_User();
$user->assignIdentifier(1);
$user->role = 'support'; // This value defined as default in scheme,
thats why have problems
$user->save();
var_dump($user->toArray());

in debugger we didnot see any UPDATE queries! However object is been
changed, results just has not been flushed to database.

array(6)

{ ["id"]=> int(1) ["display_name"]=> string(13) "Administrator" ["username"]=> string(4) "root" ["password"]=> string(40) "45bb0f589525a2f0f2a48620bb59b1b8baef0c1d" ["role"]=> string(7) "support" ["is_active"]=> bool(true) }

I cant overcome this problem right now, unfortunatelly (well I can
just remove all default values from table definitions or use
Doctrine_Query for updating staff.. but I'd like to use models

However if I use Doctrine_Query of even

$user = Doctrine_Core::getTable('App_Model_User')->find(1);

instead of

$user = new App_Model_User();
$user->assignIdentifier(1);

updates works well...



 Comments   
Comment by Petr Peller [ 20/Jan/11 ]

I second this.

When you UPDATE row with save() method of Record after setting identifier by assignIdentifier() doctrine removes columns updates from SQL which are set to default values same as it would do with INSERT. Other columns are updated correctly. This is sure a bug.

You can workaround this by setting the value as NULL instead of the actual default value. (Which I wouldn't recommend).





[DC-515] HYDRATE_RECORD_HIERARCHY broken with many roots Created: 22/Feb/10  Updated: 09/Jun/10

Status: Reopened
Project: Doctrine 1
Component/s: Nested Set
Affects Version/s: 1.2.0
Fix Version/s: None

Type: Bug Priority: Critical
Reporter: Kamil Rojewski Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

DB schema:

Category:
actAs:
NestedSet:
hasManyRoots: true
rootColumnName: root_id
columns:
id:
type: integer(4)
primary: true
autoincrement: true
name:
type: string(64)
notnull: true
image: string(64)
indexes:
tree:
fields: [lft, rgt, root_id]

Sample data:

id: '1'
name: 'Przykładowa kategoria 1'
image: null
root_id: '1'
lft: '1'
rgt: '6'
level: '0'

  • id: '2'
    name: 'Przykładowa kategoria 2'
    image: null
    root_id: '2'
    lft: '1'
    rgt: '6'
    level: '0'
    -
    id: '3'
    name: 'Przykładowa podkategoria 1'
    image: null
    root_id: '2'
    lft: '2'
    rgt: '5'
    level: '1'
    -
    id: '4'
    name: 'Przykładowa podkategoria 2'
    image: null
    root_id: '2'
    lft: '3'
    rgt: '4'
    level: '2'
    -
    id: '5'
    name: teset1
    image: null
    root_id: '1'
    lft: '2'
    rgt: '5'
    level: '1'
    -
    id: '6'
    name: test2
    image: null
    root_id: '1'
    lft: '3'
    rgt: '4'
    level: '2'

When using HYDRATE_RECORD_HIERARCHY, the first top-level category is empty. Everything is assigned to the other one. Only single-root trees work properly.



 Comments   
Comment by Kamil Rojewski [ 17/Mar/10 ]

If you look at Doctrine_Collection::toHierarchy() you'll notice that there is NO reference to root_id, therefore it treats the entire collection as 1 tree (which is false). The bug is 100% repeatable. I've made a fast walkaround ba adding a multi-tree hydrator:

class MultiRootHydrator extends Doctrine_Hydrator_RecordDriver
{
  public function hydrateResultSet($stmt)
  {
    $result = parent::hydrateResultSet($stmt);

    $collection = array();
    foreach ($result as $item)
    {
      if (!isset($collection[$item->root_id]))
        $collection[$item->root_id] = new Doctrine_Collection($result->getTable());

      $collection[$item->root_id]->add($item);
    }

    $result = new Doctrine_Collection($result->getTable());
    foreach ($collection as $tree)
    {
      $tree = $tree->toHierarchy();
      $record = $tree->getFirst();

      $result->add($record, $record->root_id);
    }

    return $result;
  }
}

It should clarify the problem.

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

I think it was intended that you would only convert a single tree to a hierarchy. What would the structure of the returned data be like?

Comment by Kamil Rojewski [ 09/Jun/10 ]

A Doctrine_Collection with root nodes seems to work fine. It allows to traverse the tree for each root.





[DC-586] Doctrine outputs invalid SQL when using Limit and Order By conditions in MSSQL Created: 18/Mar/10  Updated: 18/Mar/10

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

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

Windows XP
Apache 2.2
PHP 5.3
Doctrine 1.2.1
Symfony 1.4



 Description   

I have a Doctrine model which connects to a MSSQL database. I was trying to run the following query:

$q = Doctrine_Query::create()
    ->select('*')
    ->from('Comment c')
    ->innerJoin('c.RecordType')
    ->innerJoin('c.Department')
    ->limit(10)
    ->orderBy('c.Counter');

The code failed with a SQL Syntax exception so I took a look at the generated query and found the following (SELECT fields shortened for readabilty):

SELECT * FROM (
	SELECT TOP 10 * FROM (
		SELECT TOP 10 [c].[counter] AS [c__counter], [c].[loanid] AS [c__loanid]... ... ...
		FROM comments c
			INNER JOIN [SystemTypes] [s] ON [c].[recordtype] = [s].[code] AND [s].[fieldname] = 'RecordType'
			INNER JOIN [SystemTypes] [s2] ON [c].[department] = [s2].[code] AND [s2].[fieldname] = 'Department'
		ORDER BY [c].[counter]
	) AS [inner_tbl]
	ORDER BY [inner_tbl].[counter] AS [c__counter] DESC
) AS [outer_tbl]
ORDER BY [outer_tbl].[counter] AS [c__counter] ASC

As you can see, the ORDER BY clauses on the inner_tbl and outer_tbl segments have AS clauses which do not belong there. If you fix the ORDER BY statements the query runs just fine.

So I decided to prod around the Mssql.php connection class and found the following:

140 public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false, $isSubQuery = false)
141 {
...
169                    $field_array = explode(',', $fields_string);
170                    $field_array = array_shift($field_array);
171                    $aux2 = preg_split('/ as /', $field_array);
172                    $aux2 = explode('.', end($aux2));
173
174                    $aliases[$i] = trim(end($aux2));
...
232 }

Line 171 seems to be in charge of setting up the orderBy aliases but it is looking for a lower case ' as ' string which doesn't exist in this SQL expression. Changing that to a case insensitive regular expression search seems to fix the problem:

171                    $aux2 = preg_split('/ as /i', $field_array);

Here is the resulting SQL with the change:

SELECT * FROM (
	SELECT TOP 10 * FROM (
		SELECT TOP 10 [c].[counter] AS [c__counter], [c].[loanid] AS [c__loanid]... ... ...
		FROM comments c
			INNER JOIN [SystemTypes] [s] ON [c].[recordtype] = [s].[code] AND [s].[fieldname] = 'RecordType'
			INNER JOIN [SystemTypes] [s2] ON [c].[department] = [s2].[code] AND [s2].[fieldname] = 'Department'
		ORDER BY [c].[counter]
	) AS [inner_tbl]
	ORDER BY [inner_tbl].[c__counter] DESC
) AS [outer_tbl]
ORDER BY [outer_tbl].[c__counter] ASC]

This seems to fix the problem but I don't know if it'll create a regression. It's a start though. Anyone have any thoughts on this?






[DC-644] _getCacheKeys() exhausts memory Created: 22/Apr/10  Updated: 06/Jul/11

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

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

Doctrine is installed as a Symfony plugin. Using the latest Symfony from SVN.



 Description   

My scripts have excessive memory consumption and I've often saw in my logs:

PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 2097152 bytes) in /proj/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Cache/Apc.php on line 111

Looking into the code I've found which function to blame:

protected function _getCacheKeys()
{
$ci = apc_cache_info('user');
$keys = array();

foreach ($ci['cache_list'] as $entry)

Unknown macro: { $keys[] = $entry['info']; ######### THIS IS THE LINE }

return $keys;
}

My server extensively uses APC caching and it's normal to have many cache keys.
Obviously retrieving ALL of them is time and memory consuming.
As I'm not well versed with Doctrine's code, I didn't want to dive further in.

Is there another way to avoid this pitfall?



 Comments   
Comment by Amir W [ 26/Apr/10 ]

Is there any patch that could be provided meanwhile? This is quite a problem on a live website.

Comment by Amir W [ 10/May/10 ]

Is this not a critical issue for Doctrine's cache? It's been up for 2 weeks with not even a comment...

Comment by Jonathan H. Wage [ 10/May/10 ]

Hi, what are you calling that is invoking _getCacheKeys()? The only methods that call it are the deleteBy*() methods. It is expected that these methods have to get the entire list of cache keys from the driver in order to perform the delete by operation. These cache clearing operations should probably be done in the CLI environment where the memory limits are higher. If you want to avoid _getCacheKeys() being invoked, then you must not use the deleteBy*() methods.

Comment by Amir W [ 10/May/10 ]

Thank you for commenting. Yes, I am using deleteByRegex() since I need to expire some result cache entries upon an update operation. What other choice do I have if I wish to keep using the result cache offered by Doctrine? Is there any other mechanism?

Can't _getCacheKeys() be optimized some way?

Comment by Jonathan H. Wage [ 10/May/10 ]

No, it is not able to be optimized anymore. It has to load all the keys into a php array in memory in order to loop over them to compare against the regex. You should probably not be doing cache clearing operations in the browser under apache. If you do, you'll need to raise your memory limit.

Comment by Amir W [ 10/May/10 ]

My code actually had a few of these calls and I've now removed use of the result cache with Doctrine. What you're writing means the result cache is not usable for dynamic websites. IMHO, it's a good practice to cache results and remove them once an update is made to the data (which naturally can happen due to an update from a user). However, if that by itself creates an overload on the server (and as you know even a temporary memory abuse leads to an overload), I cannot see how it can be useful.
Please tell me if you think there's a way the results cache can still be usable for a dynamic website.

Thanks

Comment by Jonathan H. Wage [ 10/May/10 ]

This is the only way to allow more complex delete functionality. How you use it, is not up to us. We intended that cache clearing is done from the command line or in an environment where the memory limit is high enough to be able to load all those keys. It may not be able to be used by everyone, if it is not working for how you are using it then you will need to think of another solution I suppose.

Comment by Amir W [ 10/May/10 ]

Thank you for your response and I'll think of another solution for my application.

I did dive into the code and there's a relevant optimization that could be made.

_getCacheKeys() is actually creating another array for all the cache keys which needlessly increases the memory used.
If the deleteBy*() method would be implemented at the driver level (such as with Apc.php) and not at the general level (Driver.php as it is now) this array would not have to be created. It won't be such a code bloat and would surely lessen memory use.

There could be a way around the problem which also implements another feature I miss with the results cache. By allowing some sort of cache tagging to mark the items that may need to be deleted we could easily delete relevant entries. I'll describe the interface here.

Instead of
$q = $q->useResultCache(true, 86400);

There should be
$q = $q->useTagResultCache('SomeTag', true, 86400);
which does the same PLUS update a cached variable (such as 'Doctrine_Result_Cache_Tag_SomeTag') which references the result cache keys of 'SomeTag'.

We can then easily implement deletion of relevant result cache entries with

deleteByTag('SomeTag')

which would read 'Doctrine_Result_Cache_Tag_SomeTag' to figure out which entries should be removed from the cache.

I'm pretty sure my usage scenario is not marginal but let me know what you think.

Comment by Jonathan H. Wage [ 10/May/10 ]

This is already possible if I understand what you describe.

$q->useResultCache(true, 3600, 'key_to_store_cache_under');

Now you can do:

$cacheDriver->delete('key_to_store_cache_under');

Also what you describe useTagResultCache() and keeping up with our own list of cache keys is the way it used to be and was changed to this after worse performance problems were discovered with that approach.

Comment by Amir W [ 10/May/10 ]

Perhaps I've been misunderstood so I'll try explain from the start.

In my system a few queries do relate to the same pieces of information. That information can be updated by a user and thus I would need to remove anywhere between 0 and 50 related result cache variables. I cannot easily name each and every one of my queries thus giving a specific key name doesn't help. So what I did was to prefix the name of each of the queries to indicate that I'll know how to remove them. I may have thousands of results cached and would need to clear just a few. That's why I use the deleteBy*() which proves to be extremely inefficient as it retrieves ALL the keys in my cache driver and not only the Doctrine related ones.

I really don't know how it has been implemented before but what I suggest wouldn't hurt performance as tagging would be an optional addition managed with another variable. If you think that won't b useful to other Doctrine users, I'll simply implement it for my system.

Thanks

Comment by Jonathan H. Wage [ 10/May/10 ]

I think the best solution is the one you suggested earlier. That each cache driver should directly implement this functionality and bypass the creation of the array. What do you think? It is backwards compatible so that way we can commit it in 1.2.

Comment by Amir W [ 10/May/10 ]

Bypassing the array is a required optimization which is easy to implement but it's not really a solution to the problem I'm facing and I believe is common enough (Zend_Cache for example implements tagging) and need to be offered. As it'll be 2 new functions that will implement tagging only when specifically requested, it'll also be backward compatible. The only thing I'm not sure about is if an implementation of some locking mechanism would be needed for the cached variable which would hold the list of cache keys for a specific tag.

Comment by Jonathan H. Wage [ 10/May/10 ]

Let me know what you come up with and we'll have a look at including it in the next 1.2.x release.

Comment by Amir W [ 16/May/10 ]

Bypassing the extra array is still not good enough and IMHO the whole idea of deleteBy() should NOT be used if many such requests could be made, as is my case.

What I've done now is what I mentioned before with a patch that is quite ugly.

In Doctrine/Query/Abstract.php right after the line

$cacheDriver->save($hash, $cached, $this->getResultCacheLifeSpan());

I've added

                if (!empty($GLOBALS['rcache_users_in_query'])) {
                	MyCache::keepRelatedCacheKey($GLOBALS['rcache_users_in_query'], $hash);
                }

Which saves another cache key which holds the hash tags that would have to be deleted on an update.
My global variable is actually an array as a Doctrine query result may be associated with more than one user and possibly other parameters.
Before calling the $q->execute(), I simply update this variable.

When a user on my system does the update, I then delete all relevant Doctrine keys with something like

		if (is_null($cacheDriver)) $cacheDriver = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE);
		
		foreach($arKeys as $key) {
			$cacheDriver->delete($key);			
		}

and then delete my other cache key.

This solution works well for me. Sorry I cannot make a nice Doctrine patch for it as I'm not well versed with your code. I still believe it should be supported by Doctrine with an optional extra parameter for $q->useResultCache()

Thanks

Comment by David Abdemoulaie [ 08/Jun/10 ]

Hi Amir,

Zend_Cache does not implement tagging for either APC or Memcached backends, see the documentation. It also likely never will, all requests for this functionality have been closed with Wont Fix.

I don't think the deleteBy methods should have ever been implemented. When initially implemented they cached a "doctrine_cache_keys" variable to store the keys known to Doctrine. This however led to a crippling bug that would crash my production servers after a few hours. Not even a friendly "out of memory" limit, but a slowdown and eventual crash. Please see DDC-460 for details. Note that I don't use the magic delete methods, just simple saves with timeouts and this was affecting me.

I fixed the solution as you've seen using the _getCacheKeys() method. I don't believe this functionality should have ever been added to Doctrine to begin with, but this is what we have to work with. It should be the responsibility of the cache store to handle tagging and such, not poorly hacked on with application code.

As it stands, the current implementation doesn't affect people who aren't even using this functionality, as it should be. As Jon suggested, you shouldn't be using this in the context of a page request. Use a CLI script or work on another solution. Your idea of tracking your keys in application code is a good idea, but it doesn't belong in Doctrine imo.

Comment by Amir W [ 10/Jun/10 ]

Thanks David for your comment.

I agree with you that my implementation should not belong in Doctrine and that tagging should have been a part of the cache backends.

Continuing with the same logic you've presented, deleteBy...() functionality **should be removed** from Doctrine if it causes the system to crash as it does so in an obnoxious way so that it would take too long for most developers to notice this is where the problem lies. It has certainly taken too much of my time and efforts and I'd rather save the pain from others.

Comment by Carsten Henkelmann [ 06/Jul/11 ]

We had the exact same problem. We used a "deleteAll()" of a ApcCache object and ran into the "allowed memory size exhausted" pitfall. We helped ourselves with a new class that extends ApcCache and uses the simpler apc_clear_cache function.

 
namespace Foo\Cache;

class ApcCache extends \Doctrine\Common\Cache\ApcCache
{
    /**
     * Delete all cache entries. Memory saving version...
     *
     * @return bool
     */
    public function deleteAll()
    {
        return apc_clear_cache('user');
    }
}
 
use Foo\Cache\ApcCache as Apc;
...
$this->_apc = new Apc();
$this->_apc->deleteAll();

This doesn't return the ids of the deleted entries like the original function but we don't need that. So this works fine for us.





[DC-659] Sluggable behavior does not check uniqueness on insert if a slug is manually set, causing SQL error/crash Created: 01/May/10  Updated: 05/Oct/10

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

Type: Improvement Priority: Critical
Reporter: Christian Seaman Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

symfony-1.3.4 and doctrine-1.2.2



 Description   

The Sluggable behavior has the following code:

Sluggable.php
    /**
     * Set the slug value automatically when a record is inserted
     *
     * @param Doctrine_Event $event
     * @return void
     */
    public function preInsert(Doctrine_Event $event)
    {
        $record = $event->getInvoker();
        $name = $record->getTable()->getFieldName($this->_options['name']);

        if ( ! $record->$name) {
            $record->$name = $this->buildSlugFromFields($record);
        }
    }

However, this can lead to problems...

If the user incorrectly assigns a duplicate slug to the record then there is no uniqueness checking in doctrine and you get an uncaught SQL error looking something like this:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'my-slug-en_GB' for key 'foo_i18n_sluggable_idx'

If this kind of "don't do a preInsert check if I manunally set the slug" behavior is a FEATURE then it would be best to have an option to allow it to be disabled. If it is a BUG then I would suggest that the preInsert method should be changed to:

Sluggable.php
    /**
     * Set the slug value automatically when a record is inserted
     *
     * @param Doctrine_Event $event
     * @return void
     */
    public function preInsert(Doctrine_Event $event)
    {
        $record = $event->getInvoker();
        $name = $record->getTable()->getFieldName($this->_options['name']);

        if ( ! $record->$name) {
            $record->$name = $this->buildSlugFromFields($record);
        } else { // Still check for slug uniqueness when you insert
            $record->$name = $this->buildSlugFromSlugField($record);
        }
    }

C



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

Can you provide your changes as a patch/diff with a test case?

Comment by Christian Seaman [ 05/Oct/10 ]

Hi Jonathan,

I'm not so hot at making patches or test cases, but it should be fairly easy if you know what you're doing...

Just try to create and save two records with the same hard-coded slug and the second one will fail with an ugly MySQL crash.

If you add the lines

        } else { // Still check for slug uniqueness when you insert
            $record->$name = $this->buildSlugFromSlugField($record);

to the Sluggable::preInsert() method then this problem is averted and the test cases will pass.

I have been running with this modification in our production version of Doctrine since I first reported this in May and it all seems to work well.

If you really need me to figure out how to make a patch and test case please re-comment on this ticket and I'll see what I can do when I have some free time.

C





[DC-674] NULL Dates are translated to '0000-00-00' after upgrading to 1.2.2 Created: 10/May/10  Updated: 06/Oct/10

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

Type: Bug Priority: Critical
Reporter: Ville Itämaa Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Zend Framework, Ubuntu 9.10, MySQL



 Description   

Once the upgrade was done from Doctrine 1.2.1 to 1.2.2 we discovered that date related issues started to appear.
With dates that are persisted in DB as NULL are translated to "0000-00-00" when retrieved from DB. This has occurred in multiple places and is quite worrying as there is a lot of dates in our project. This means that everywhere in our codebase where we check a datevalue in our Models is NULL we need also to check for the string literal "0000-00-00".



 Comments   
Comment by Jonathan H. Wage [ 10/May/10 ]

Are you able to reproduce this in a test case?

Comment by Ville Itämaa [ 11/May/10 ]

We reverted to Doctrine 1.2.1 after realising the bug to confirm it was Doctrine 1.2.2 that was the cause for the problem. And as a result the records with NULL dates in the DB became NULL in the Models.
But when using Doctrine 1.2.2, the NULL dates became '0000-00-00' in the Models.
I don't have any other way to reproduce this error.

Comment by Jonathan H. Wage [ 11/May/10 ]

Were you able to identity which changeset it was? You can read about creating test cases here http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

So far I am not able to reproduce the error you described.

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

I'd like to fix this. Did you ever figure out which changeset introduced the issue? I've been trying to figure it out myself.

Comment by Roland Huszti [ 06/Oct/10 ]

With 1.2.3 this works for me fine with both TIMESTAMP and DATE fields.

YAML

        date_of_birth:
            type: date

BASE MODEL

        $this->hasColumn('date_of_birth', 'date', null, array(
             'type' => 'date',

             // try these two
             // 'notnull' => false,
             // 'default' => null
         ));
YAML

        exported_at:
            type: timestamp(25)
            notnull: false
            default: null

            # in this model I have everything to make sure it accepts and defaults to NULL

BASE MODEL

        $this->hasColumn('exported_at', 'timestamp', 25, array(
             'type' => 'timestamp',
             'notnull' => false,
             'length' => '25',
             ));

You may try adding these to your YAML and (base) models

YAML

    fieldname:
         . . .
        notnull: false
        default: null

BASE MODEL

        $this->hasColumn('fieldname', . . .
             . . .
             'notnull' => false, // <<<<<<<
             // 'default' => null, // <<< maybe, probably not needed
             ));

I hope it helps.





[DC-690] Wrong data type for oracle integer Created: 18/May/10  Updated: 08/Jun/10

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

Type: Bug Priority: Critical
Reporter: Arian Maykon de Araújo Diógenes Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Trying to migrate from doctrine 1 to 1.2 and this problem came up to me, i cant map a column to integer(7) (which should create a number(7) column) using Oracle, he always create a NUMBER(20) field.

Taking a look at Doctrine_DataDict_Oracle i realize the problem is here.



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

We made a bunch of changes/fixes related to oracle. This was to fix another bug I believe. I can't remember the user that is responsible for these changes. Does anyone else remember or know anything?





[DC-725] Call record->get('RelationManyToManyName', FALSE) corrupt the record and generate a exception when calling record->save() Created: 09/Jun/10  Updated: 09/Jun/10

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

Type: Bug Priority: Critical
Reporter: David Jeanmonod Assignee: Jonathan H. Wage
Resolution: Unresolved 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 get_with_no_load_corrupt_many_to_many_assoc_.php    

 Description   

Imagine a simple case. Contact can have many categories.
Doing thoses calls:

$c = Doctrine::getTable('Contact')->findOneById($id);
$c->get('Categories', false);
$c->save();

Generate the following error

PHP Fatal error:  Call to a member function save() on a non-object in /lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Connection/UnitOfWork.php on line 443
PHP Stack trace:
PHP   1. {main}() /test/doctrine/get_with_no_load_corrupt_many_to_many_assoc_.php:0
PHP   2. Doctrine_Record->save() /test/doctrine/get_with_no_load_corrupt_many_to_many_assoc_.php:51
PHP   3. Doctrine_Connection_UnitOfWork->saveGraph() /lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Record.php:1705
PHP   4. Doctrine_Connection_UnitOfWork->saveAssociations() /lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Connection/UnitOfWork.php:137


 Comments   
Comment by David Jeanmonod [ 09/Jun/10 ]

Test case for the bug





[DC-735] Imported objects not converted to objects and parsed as string when a setter method exists Created: 14/Jun/10  Updated: 22/Jul/11

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

Type: Bug Priority: Critical
Reporter: Kevin Dew Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Mac OS X 10.6



 Description   

If you set a setter method for a model which is for a relation the data import no longer works. This seems to be because in the _processRow method it checks if a method exists and then passes the default value rather than checking whether a relation exists first and passing the imported object.

This effectively means you can't overload a setter method and still use the data import.



 Comments   
Comment by ryan [ 22/Jul/11 ]

added testcase here
https://github.com/rahx/doctrine1/commit/ba5628abaa5b3d60638d833d90b1cf439504d560





[DC-743] Incompatibilty between fixture import and accessors extends Created: 16/Jun/10  Updated: 22/Jul/11

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

Type: Bug Priority: Critical
Reporter: Brice Favre Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None
Environment:

Window, PHP5, Symfony



 Description   

Hello,

I had a problem when i try to import data with an extended accessors when i try to insert a content with a relation. I discovered this problem in symfony.

For example, here is my table :

 
News:
  tableName: ne_news
  columns:
    id:           { type: integer(4), primary: true, autoincrement: true }
    author_id:    { type: integer(4), notnull: true }
    name:         { type: string(255) }
    description:  { type: text }
  relations:
    author: { class: sfGuardUser, onDelete: NULL, local: author_id, foreign: id, foreignAlias: sfGuardUser }

And the fixture :

 
SfGuardUser:
  sadmin:
    username:       admin
    password:       admin
    is_super_admin: true
  author1:
    username: myname
    
News:
  News1:
    name: Test 1
    description: Description of news 1
    author: author1

I import it with symfony doctrine:data-load and it works.

If i add a news.class.php and extends the autogenerated class it fails.

 
    public function setAuthor($v)
    {
        //__log('extending setter');
        return $this->_set('author', $v);
    }

WhenDoctrine_Data_Import finds the setAuthor function, it wont transform author1 in object so $v will be a string, not an sfGuardUser object.

What do you think? Is a common behavior, how can i extends my accessor?



 Comments   
Comment by ryan [ 22/Jul/11 ]

this is the same issue as DC-735





[DC-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-755] CLONE [DC-558] incorrect handling of MODEL_CLASS_PREFIX causes Doctrine_Migration_Diff to drop the whole database when working from YAML (Regression) Created: 20/Jun/10  Updated: 10/Oct/10

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

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

Current HEAD of Doctrine 1.2


Attachments: File dc755TestCase.diff     File fix755.diff    

 Description   

Replicating the bug:
1. Set ATTR_MODEL_CLASS_PREFIX non-null
2. create schema file with entity
3. run doctrine build-all
4. copy schema file
5. edit schema file to add column to entity
6. run generate-migrations-diff from copy of schema file to edited schema file

Expected (previous) behaviour:
Migration is generated to add the new column to entity

Real behaviour:
Drops entity from database and creates new



 Comments   
Comment by Andrew Coulton [ 20/Jun/10 ]

This seems to be a regression caused by the fix for DC-558 which added the MODEL_CLASS_PREFIX to the $_toPrefix in Doctrine_Migration_Diff::generateChanges.

While this fixed the issue when generating diff from models to YAML, it has now created the reverse issue for generating diffs from YAML to YAML - as the models generated for the "from" schema do not get MODEL_CLASS_PREFIX prepended and so now this command will drop all existing tables and recreate.

I believe the fix may be to amend as:

Unable to find source-code formatter for language: php. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
        $from = $this->_generateModels(
            Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_fromPrefix,
            $this->_from);
        $to = $this->_generateModels(
            Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_toPrefix,
            $this->_to                
        );

Since it seems that when presented with a folder of models _generateModels ignores the prefix anyway. However, I'm not sure of other impacts possible as a result?

Comment by Andrew Coulton [ 29/Aug/10 ]

I've been using and testing the modified version above locally for some time and it seems to work as expected. Any chance of this making it into core? Otherwise, the migrations feature is completely unusable when working YAML-YAML and using model prefixes on the newly released 1.2.3

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

Has anyone been able to produce this in a test case?

Comment by Andrew Coulton [ 30/Aug/10 ]

I've attached a diff file with the DC755TestCase and the required from and to YAML schema files to reproduce this bug. I wasn't sure whether you prefer like this or as a git commit?

Comment by Andrew Coulton [ 30/Aug/10 ]

Also attached a diff file of my proposed change to Doctrine_Migration_Diff to resolve this, but as I say unsure if it has implications on other migration types.

Comment by Andrew Coulton [ 10/Oct/10 ]

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





[DC-802] Alias in select and having Created: 28/Jul/10  Updated: 07/Aug/10

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

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

Windows XP sp3



 Description   

i have query

$q = Doctrine_Query::create()
->select('g.,gp.,st.,np.,v.,s.,max(gp.card_date) as md')
->from('gragdans as g')
->innerJoin('g.Pribs_ gp')
->leftJoin('gp.Streets_ st')
->leftJoin('gp.Viddocs_ v')
->leftJoin('gp.Sobits_ s')
->leftJoin('st.Npunkts_ np')
->where('g.grid in '.$idlst,1)
->orderby('fam')
->having('gp.card_date=md');

When it runs i have error:

<b>Fatal error</b>: Uncaught exception
'Doctrine_Connection_Mysql_Exception' with message 'SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'md' in 'having clause'' in Z:
\home\new\www\system\application\plugins\doctrine\lib\Doctrine
\Connection.php:1082

SQL for it looks like:

SELECT g.grid AS g_grid, g.fam AS gfam, g.nam AS g_nam, g.otc AS
g_otc, g.date_rogd AS gdate_rogd, g.gosgrid AS g_gosgrid,
g.rogd_place AS g_rogd_place, g.pol AS g_pol, g.reg_date AS
g_reg_date, g.deesp AS gdeesp, p.pribid AS p_pribid, p.grid AS
p_grid, p.strid AS pstrid, p.hom AS phom, p.cor AS p_cor, p.kva
AS p_kva, p.reg_date AS preg_date, p.vidid AS p_vidid, p.pas_ser
AS p_pas_ser, p.pas_no AS ppas_no, p.org_name AS p_org_name,
p.pas_date AS p_pas_date, p.sobid AS p_sobid, p.reg_expire AS
p_reg_expire, p.card_date AS pcard_date, s.strid AS s_strid,
s.npid AS s_npid, s.name AS sname, v.vidid AS v_vidid, v.name AS
v_name, s2.sobid AS s2sobid, s2.cod_s AS s2_cod_s, s2.cod_oi AS
s2_cod_oi, s2.name AS s2name, n.npid AS nnpid, n.name AS n_name,
n.sid AS n_sid, MAX(p.card_date) AS p_0 FROM gragdans g INNER JOIN
prib p ON g.grid = p.grid LEFT JOIN streets s ON p.strid = s.strid
LEFT JOIN viddoc v ON p.vidid = v.vidid LEFT JOIN sobit s2 ON p.sobid
= s2.sobid LEFT JOIN npunkt n ON s.npid = n.npid WHERE (g.grid in (4,
13, 19, 20)) HAVING p.card_date=md ORDER BY g.fam

But i need Query looks like:

SELECT g.grid AS g_grid, g.fam AS gfam, g.nam AS g_nam, g.otc AS
g_otc, g.date_rogd AS gdate_rogd, g.gosgrid AS g_gosgrid,
g.rogd_place AS g_rogd_place, g.pol AS g_pol, g.reg_date AS
g_reg_date, g.deesp AS gdeesp, p.pribid AS p_pribid, p.grid AS
p_grid, p.strid AS pstrid, p.hom AS phom, p.cor AS p_cor, p.kva
AS p_kva, p.reg_date AS preg_date, p.vidid AS p_vidid, p.pas_ser
AS p_pas_ser, p.pas_no AS ppas_no, p.org_name AS p_org_name,
p.pas_date AS p_pas_date, p.sobid AS p_sobid, p.reg_expire AS
p_reg_expire, p.card_date AS pcard_date, s.strid AS s_strid,
s.npid AS s_npid, s.name AS sname, v.vidid AS v_vidid, v.name AS
v_name, s2.sobid AS s2sobid, s2.cod_s AS s2_cod_s, s2.cod_oi AS
s2_cod_oi, s2.name AS s2name, n.npid AS nnpid, n.name AS n_name,
n.sid AS n__sid, MAX(p.card_date) AS md FROM gragdans g INNER JOIN
prib p ON g.grid = p.grid LEFT JOIN streets s ON p.strid = s.strid
LEFT JOIN viddoc v ON p.vidid = v.vidid LEFT JOIN sobit s2 ON p.sobid
= s2.sobid LEFT JOIN npunkt n ON s.npid = n.npid WHERE (g.grid in (4,
13, 19, 20)) group by fam HAVING p.card_date=md

This query run fine and give me what i need.

Doctrine dont use 'md' alias instead it convert it to 'p__0'






[DC-815] Model's default sorting breaks subqueries Created: 11/Aug/10  Updated: 14/Mar/11

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

Type: Bug Priority: Critical
Reporter: Jacek Jędrzejewski Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None

Attachments: File DC9999TestCase.php    

 Description   

It works except subqueries. Main table's order is added to subquery and vice versa. SQL query looks like this:

{{
SELECT t.id AS t_id FROM ticket_d_c9999_record t WHERE (t.id = (SELECT MAX(t2.id) AS t20 FROM ticket_d_c9999__record t2 ORDER BY t.id ASC, t2.id ASC)) ORDER BY t.id ASC, t2.id ASC
}}

Query fails because there is >>no such column "t.id"<<.

I include a testcase when it is all visible.

BTW. there is nothing about that feature (and relation orderBy) in docs. It is only in UPGRADE file.



 Comments   
Comment by Jacek Jędrzejewski [ 25/Aug/10 ]

Anyone?

Comment by Alan Betteridge [ 10/Mar/11 ]

Am having the same issue!

Eventually found the orderBy option on both the model and on relationships and was over joyed as I'd been trying to find a way of doing this, but it didn't work!!

Found the patch http://www.doctrine-project.org/jira/browse/DC-651 which solved the first problem I encountered but now I'm getting this.

Comment by Alan Betteridge [ 14/Mar/11 ]

Had a look at the code and tried only setting the orderBy if the current component is actually referenced in the from sql part of the query.

Looking at what is selected from, $this->_sqlParts['from'], it appears that the main table ($map['table']->getTableName()) and $sqlAlias is include with a zero index and joined tables are keyed by their $alias (or at least the content of these variables within the loop).

From this I believe I could detect if the current entry in the loop was from a table that was in the current "FROM" part of the query by looking for the table name and alias as an entry or the current alias as a key in the "FROM" array.

Within my sub query the orderBy valeus would still get applied but only in the subquery and not in the main query where they were included before, out of scope.

With patch DC-651 applied my code in Query.php at line 1315 noew looks as follows:


                // Note: Only include orderBy values for tables we're actually selecting from (both the root table or
                // tables referenced from it)
                if (in_array("{$map['table']->getTableName()} {$sqlAlias}", $this->_sqlParts['from']) || array_key_exists($alias, $this->_sqlParts['from'])) {
                    if (isset($map['relation'])) {
                        if (isset($map['ref'])) {
                            $orderBy = $map['relation']['refTable']->processOrderBy($sqlAlias, $map['relation']['orderBy'], true);
                            if ($map['relation']['orderBy'] && $orderBy == $map['relation']['orderBy']) {
                                $orderBy = $map['relation']->getOrderByStatement($sqlAlias, true);
                            }
                        } else {
                            $orderBy = $map['relation']->getOrderByStatement($sqlAlias, true);
                            if ($orderBy == $map['relation']['orderBy']) {
                                $orderBy = null;
                            }
                        }
                    } else {
                        $orderBy = $map['table']->getOrderByStatement($sqlAlias, true);
                    }
                } else {
                        $orderBy = null;
                }

Am I correct in my assumptions?





[DC-857] postHydrate not called for One to One relations, when ATTR_HYDRATE_OVERWRITE == false, and the record is cached in the table's identityMap Created: 03/Sep/10  Updated: 05/Sep/10

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

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

All


Attachments: Text File DC857.patch     File DC857TestCase.php    

 Description   

When objects are hydrated with a join to a one to one relation, if the queried object is stored in the table's cache, and ATTR_HYDRATE_OVERWRITE set to false, then the one to one relation's postHydrate method will never be called.

This is due to this line.

 
} else if ( ! isset($prev[$parent][$relationAlias])) {

...which will always evaluate to false, and postHydrate will ever be called, as the record has been pulled from the table cache here



 Comments   
Comment by Ben Davies [ 03/Sep/10 ]

Test case attached.

Comment by Ben Davies [ 03/Sep/10 ]

There needs to be some kind of caching on the pre/postHydrate calls, which is done throughout the Doctrine_Hydrator_Graph, except for when the relation is one-to-one.
This is done just above, for relations that are not one-to-one.

Unfortunately, I couldn't work out how to implement it for one-to-one.
Probably a simple fix for someone familiar with the code

Comment by Ben Davies [ 03/Sep/10 ]

Correct Test Case

Comment by Ben Davies [ 03/Sep/10 ]

Correct Test Case

Comment by Ben Davies [ 05/Sep/10 ]

I was probably a little too tired to think this through clearly on a Friday after a long weeks work!
Patched attached, which doesn't break any of the existing unit tests.





[DC-922] master-slave replication with i18n behavior Created: 10/Nov/10  Updated: 10/Nov/10

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

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

php 5.3, doctrine 1.2, Symfony 1.4, mysql



 Description   

I'm trying to use sfDoctrineMasterSlavePlugin for database replication with Symfony 1.4 and PHP 5.3. But facing problem while selecting I18n records and receiving "Unknown relation alias Translation" error.

I've also tried same with implementation solution given in master-slave chapter of doctrine cookbook but no success.

Is anyone facing same problem with sfDoctrineMasterSlavePlugin and i18n behavio? Is there any solution of the problem?






[DC-932] Queries fail when a model contains underscore and we try to apply a limit Created: 19/Nov/10  Updated: 19/Nov/10

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

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

Doctrine 1.2, Symfony 1.4.6, MySQL, Postgresql



 Description   

Actually, I've a dead simple schema.yml, with two tables:

T_Media:
actAs:
Timestampable: ~
columns:
media_id:

{ type: integer, primary: true, autoincrement: true }

name: string(25)

J_Acl:
columns:
media_id: integer
relations:
Media:

{ class: T_Media, local: media_id, foreign: media_id, onDelete: CASCADE }

I have some fixtures:
T_Media:
m1:
name: foobar

J_Acl:
a1:
Media: m1

And then, the DQL query I want to execute:

"From T_Media m INNER JOIN m.J_Acl order by m.created_at limit 1"

But if I run this query, for instance in CLI, I got an error:
./symfony doctrine:dql "From T_Media m INNER JOIN m.J_Acl order by m.created_at limit 1"

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test_noel.t2__media' doesn't exist.
Failing Query: "SELECT DISTINCT t2.media_id FROM t2_media t2 INNER JOIN j2_acl j2 ON t2.media_id = j2.media_id ORDER BY t2.created_at LIMIT 1"

Notes:

  • the query works if I do not apply the limit clause.
  • if I remove the underscore from the model, or if I set manually the tableName to remove the double underscore, it works





[DC-963] Doctrine cache - Salt dissociation Created: 03/Feb/11  Updated: 18/Apr/11

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

Type: Improvement Priority: Critical
Reporter: Thomas Tourlourat - Armetiz Assignee: Roman S. Borschel
Resolution: Unresolved Votes: 1
Labels: None


 Description   

Doctrine Cache store data into a persistence storage.

Regarding APC, Doctrine use a share storage.
Doctrine is able to cache SQL from DQL, and DOM from SQL.
To do this, Doctrine create a DQL hash, and store the SQL result refer to the hash.

I'm using a server to host two Doctrine project, a preproduction & production Website. In some case, DQL is the same on both project, but the data model definition isn't.

Preproduction convert DQL to SQL using data model definition, and store the SQL result into APC cache refer to the DQL hash.
Production create a DQL hash, this is the same hash as preproduction.. So production instance use the SQL refer to the preproduction..

I'm not sure about the quality of this explanation... But I can add some information is needed.

The solution of this problem is easy. Just add a SALT to any cache id's. It's a Doctrine_Cache problem, not only a Doctrine_Cache_APC problem..
For Query cache it's not really important because this cache is optional, but for result cache.. It's more critical.
The SALT can be define when instantiate the Doctrine_Cache object, it's just an option..

$cacheDriver = new doctrine_Cache_Apc ();
$cacheDriver->setOption ("salt", "domain.tld");



 Comments   
Comment by Thomas Tourlourat - Armetiz [ 03/Feb/11 ]

to complete this bug, I think it's also a problem on DC 2..

Comment by Jaik Dean [ 18/Apr/11 ]

There is already an (undocumented?) option "prefix" that allows this.

$cacheDriver = new Doctrine_Cache_Apc(array('prefix' => 'MY UNIQUE SALT'));





[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-980] Moving all ALTERS queries to the end of generated sql file (task build-sql) Created: 04/Mar/11  Updated: 04/Mar/11

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

Type: Improvement Priority: Critical
Reporter: Sergey Eremenko Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: File Export.php    

 Description   

Actual in case of using multi database configuration and foreign keys between them.

Now build-sql task generates SQL query for database by database in alphabetical order. It's ugly when we have multidatabase configuration and foreign keys between their tables. It's impossible to do 'import-sql' without errors beucase foreign keys constrains to nonexisting tables are in next database in order.

I have added some code to strings 1176-...






[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-1009] save() also updates fields which should not be Created: 08/Jun/11  Updated: 08/Jun/11

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

Type: Bug Priority: Critical
Reporter: Yan Urquiza Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows server 2003 PHP 5.2.17 / XP PRO 32bits XAMPP PHP 5.3.5
MSSQL / MYSQL
Symfony 1.4.6


Attachments: PNG File after_with_execute.PNG     PNG File after_with_save.PNG     PNG File before.PNG     File retrieveByExamBatchStatus.php     File schema.yml    

 Description   

When I want to do a simple update like this :

$batches = ExamResultsBatchTable::getInstance()->retrieveByExamBatchStatus(ExamResultsBatch::valid_status_code);
foreach($batches as $batch)
{
$batch->setExamBatchStatusId($batchStatusId);
$batch->setStatusDate(date('Y-m-d'));
$batch->save();
}
Only exam_batch_status_id and status_date should be updated (see screenshot before), but columns exam_batch_status_id ,status_date AND exam_subject_id are updated,with the same value (23) (screenshot after_with_save).

If I run this:
$toto = Doctrine_Query::create()
->update('ExamResultsBatch erb')
->set('erb.exam_batch_status_id', 23)
->set('erb.status_date', date('Y-m-d'))
>where('erb.id = ?' , $batch>getId())
->execute();
Everything is correctly done.

here is the simpliest case.

The same problems are signaled on other tables in the database, but different tables can be impacted by one save() (the execute() query still works fine).

Example : 2 foreign tables will be updated , even if the save() action should only concern the main table, and one field (which is not a foreign key).
The corresponding foreign key fields in the 2 foreign tables, will be updated with the value given (here 23).

Because save() is used in a lot of different places in our app, I need to find a solution to fix save(), or if not possible to override it to run a execute()like query.

Thanks for your help.
Don't hesitate to ask if you want more details.

Yan






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

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

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

Windows 7 64Bit
PHP 5.3
Symfony 1.4


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

 Description   

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

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

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

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

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

// program 1:

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

// program 2:

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

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

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

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

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

Edit:

Doctrine_Connection::queryOne() is affected as well!

A solution is to replace

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

by

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



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

Suggested patch

Comment by joao guermandi [ 03/May/14 ]

Implementação





[DC-1052] limit() get lost on multiple joins Created: 20/Mar/12  Updated: 20/Mar/12

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

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


 Description   

$strSql = UserFeedTable::getInstance()>createQuery('q')>
select('q., f., fi., fav.')->
leftJoin('q.Feed f')->
leftJoin('f.FeedItem fi')->
leftJoin('fi.Favorite fav')->
andWhere('q.profile_id = ?', $intUserId)->
andWhere('q.is_active = ?', true)->
limit(10)->getSqlQuery();
var_dump($strSql);

string(1075) "SELECT u.id AS u_id, u.name AS uname, u.image AS uimage, u.lead AS ulead, u.headline AS uheadline, u.sort AS usort, u.is_active AS uis_active, u.is_favorite AS uis_favorite, u.feed_id AS ufeed_id, u.profile_id AS uprofile_id, u.category_id AS ucategory_id, u.created_at AS ucreated_at, u.updated_at AS uupdated_at, f.id AS fid, f.url AS furl, f.name AS fname, f.created_at AS fcreated_at, f.updated_at AS fupdated_at, f2.id AS f2id, f2.lead AS f2lead, f2.description AS f2description, f2.image AS f2image, f2.pub_date AS f2pub_date, f2.link AS f2link, f2.feed_id AS f2feed_id, f2.created_at AS f2created_at, f2.updated_at AS f2updated_at, f3.id AS f3id, f3.profile_id AS f3profile_id, f3.feed_item_id AS f3feed_item_id, f3.created_at AS f3created_at, f3.updated_at AS f3_updated_at FROM user_feed u LEFT JOIN feed f ON u.feed_id = f.id LEFT JOIN feed_item f2 ON f.id = f2.feed_id LEFT JOIN favorite f3 ON f2.id = f3.feed_item_id WHERE u.id IN ('7', '8', '9', '10', '11') AND (u.profile_id = ? AND u.is_active = ?)"

As you can see, the limit is missing.






[DC-1053] Renaming a doctrine 'string' field may result in loss of data as the field's type changes. (MySQL) Created: 26/Mar/12  Updated: 26/Mar/12

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

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

PHP 5.3.5-1ubuntu7.2ppa1~lucid with Suhosin-Patch (cli) (built: May 7 2011 03:12:27)
Zend Engine v2.3.0
Xdebug v2.0.5
Turnkey LAMP 10.04 LTS x86_64
Symfony 1.4.11
mysql Ver 14.14 Distrib 5.1.41, for debian-linux-gnu (i486) using readline 6.1



 Description   

Consider the following schema:

schema.yml
MyTable:
  columns:
    some_text:        string

Doctrine creates the table with:

CREATE TABLE `my_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `some_text` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, the following migration should rename the field from some_text to just_text:

<?php
class Version1 extends Doctrine_Migration_Base
{
    public function up()
    {
        $this->renameColumn('my_table', 'some_text', 'just_text');
    }

    public function down()
    {
      $this->renameColumn('my_table', 'just_text', 'some_text');
    }
}

...however the field gets renamed and the type becomes VARCHAR(255), as the resulting SHOW CREATE TABLE my_table shows:

CREATE TABLE `my_table` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `a_varchar` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Causes data in the column greater than 255 bytes to get truncated






[DC-1058] Warning: Invalid argument supplied for foreach() in SqlWalker.php line 899 Created: 29/Jul/12  Updated: 29/Jul/12

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

Type: Bug Priority: Critical
Reporter: Alexander Cucer Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: paginator
Environment:

Linux, Ubuntu 12, php 5.4



 Description   

Hallo, i get the error
Warning: Invalid argument supplied for foreach() in /var/www/phverbose/vendor/doctrine/Doctrine/ORM/Query/SqlWalker.php line 899

Here is the line
foreach ($assoc['relationToTargetKeyColumns'] as $relationColumn => $targetColumn) {

Here are the relations and the query
http://pastie.org/4352511
http://pastie.org/4352498

Here is the dump of $assoc before warning

array(16) {
["fieldName"]=>
string(5) "sites"
["joinTable"]=>
array(0) {
}
["targetEntity"]=>
string(13) "Entities\Site"
["mappedBy"]=>
string(6) "emails"
["inversedBy"]=>
NULL
["cascade"]=>
array(1)

{ [0]=> string(7) "persist" }

["orphanRemoval"]=>
bool(false)
["fetch"]=>
int(2)
["type"]=>
int(8)
["isOwningSide"]=>
bool(false)
["sourceEntity"]=>
string(14) "Entities\Email"
["isCascadeRemove"]=>
bool(false)
["isCascadePersist"]=>
bool(true)
["isCascadeRefresh"]=>
bool(false)
["isCascadeMerge"]=>
bool(false)
["isCascadeDetach"]=>
bool(false)
}






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

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

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





[DC-49] Wrong query parameter order when using limit() on PostgreSQL Created: 22/Sep/09  Updated: 26/Jul/10

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

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

latest doctrine 1.1 revision, linux x64, PostgeSQL 8.4, php 5.2.10


Attachments: File Doctrine_Query_Abstract.diff     File PostgresParamsBugTestCase.php    

 Description   

Trying to add limit() to complex query with many where's and some joins. In pgsql it causes nested limit subquery and in some cases parameter order (when limit subquery exists params array just merges with itself, i. e. (1,2) becomes (1,2,1,2)) makes result query wrong, i. e. params array order doesn't correspond placeholders order in query.

With named query parameters all ok.

Testcase attached.



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

here is the working test case:

class Doctrine_Ticket_DC49_TestCase extends Doctrine_UnitTestCase 
{
        public static $query;
        public static $params;

        public function init()
        {
                $this->dbh = new Doctrine_Adapter_Mock('pgsql');
                $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh);
                $this->conn->addListener(new PPB_QueryListener());
        }
        
        public function prepareTables()
        {
                $this->tables = array('PPB_Section', 'PPB_Post', 'PPB_PostVote');
                
                parent::prepareTables();
        }
        
        public function testBug()
        {
                $q = Doctrine_Query::create()->from('PPB_Post p')
                                             ->where('p.section_id = ?', 1)
                                             ->addWhere('p.id = ?', 15)
                                             ->leftJoin('p.Votes v WITH v.user_id = ?', 10)
                                             ->limit(10);
                                             
                $q->execute();
                
                $this->assertEqual(self::$query, "SELECT p.id AS p__id, p.section_id AS p__section_id, p2.id AS p2__id, p2.post_id AS p2__post_id, p2.user_id AS p2__user_id FROM p_p_b__post p LEFT JOIN p_p_b__post_vote p2 ON p.id = p2.post_id AND (p2.user_id = ?) WHERE p.id IN (SELECT doctrine_subquery_alias.id FROM (SELECT DISTINCT p3.id FROM p_p_b__post p3 LEFT JOIN p_p_b__post_vote p4 ON p3.id = p4.post_id AND (p4.user_id = ?) WHERE p3.section_id = ? AND p3.id = ? LIMIT 10) AS doctrine_subquery_alias) AND (p.section_id = ? AND p.id = ?)");
                
                $this->assertEqual(implode(",", self::$params), '10,10,1,15,1,15'); // correct order of params
        }
}

class PPB_Post extends Doctrine_Record
{
        public function setTableDefinition()
        {
                $this->hasColumn('section_id', 'integer');
        }
        
        public function setUp()
        {
                $this->hasOne('PPB_Section', array('local' => 'section_id',
                                                   'foreign' => 'id'));
                                                   
                $this->hasMany('PPB_PostVote as Votes', array('local' => 'id',
                                                              'foreign' => 'post_id'));
        }
}

class PPB_Section extends Doctrine_Record
{
        public function setTableDefinition()
        {
        }
}

class PPB_PostVote extends Doctrine_Record
{
        public function setTableDefinition()
        {
                $this->hasColumn('post_id', 'integer');
                $this->hasColumn('user_id', 'integer');
        }
}

class PPB_QueryListener extends Doctrine_EventListener
{
        public function postStmtExecute(Doctrine_Event $event)
        {
                //var_dump($event->getQuery());
                //var_dump($event->getParams());
                
                Doctrine_Ticket_DC49_TestCase::$query = $event->getQuery();
                Doctrine_Ticket_DC49_TestCase::$params = $event->getParams();
        }
}
Comment by Daniel Bojdo [ 26/Jul/10 ]

I fixed this bug. Patch in attachment. I hope it's clear enough.





[DC-67] Taggable not working Created: 28/Sep/09  Updated: 15/Apr/10

Status: Reopened
Project: Doctrine 1
Component/s: Extensions
Affects Version/s: 1.2.0-ALPHA1
Fix Version/s: None

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

PHP 5.2.8, Doctrine 1.2.0 Alpha1, Vista, Sandbox 1.2.0 Alpha1



 Description   

After enabling Taggable extension, magic methods on the tables (e.g. getPopularTags)
cannot be reached:

Doctrine::getTable('Upload')->getPopularTags();

Fatal error: Uncaught exception 'Doctrine_Table_Exception' with message 'Unknown method Doctrine_Table::getPopularTags' in C:\Users\user\www\extens.dev\lib\Doctrine\Table.php:2608 Stack trace: #0 [internal function]: Doctrine_Table->__call('getPopularTags', Array) #1 C:\Users\user\www\extens.dev\index.php(7): Doctrine_Table->getPopularTags() #2

{main}

thrown in C:\Users\user\www\extens.dev\lib\Doctrine\Table.php on line 2608



 Comments   
Comment by admirau [ 08/Oct/09 ]

The same with Alpha2

Comment by admirau [ 10/Oct/09 ]

Running the tests results in one failure:

Doctrine Unit Tests
===================
Doctrine_Template_Taggable_TestCase.............................................failed

Unexpected Doctrine_Connection_Sqlite_Exception thrown in [Doctrine_Template_Taggable_TestCase] with message [SQLSTATE[HY000]: General error: 1 no such column: a__2] in C:\Users\user\www\extens.dev\lib\Doctrine\Connection.php on line 1067

Trace
-------------

#0 C:\Users\user\www\extens.dev\lib\Doctrine\Connection.php(1015): Doctrine_Connection->rethrowException(Object(PDOException), Object(Doctrine_Connection_Sqlite))
#1 C:\Users\user\www\extens.dev\lib\Doctrine\Query\Abstract.php(936): Doctrine_Connection->execute('SELECT t.id AS ...', Array)
#2 C:\Users\user\www\extens.dev\lib\Doctrine\Query\Abstract.php(990): Doctrine_Query_Abstract->_execute(Array)
#3 C:\Users\user\www\extens.dev\tools\sandbox\extensions\Taggable\lib\Doctrine\Template\TaggableTag.php(76): Doctrine_Query_Abstract->execute(Array, 2)
#4 [internal function]: Doctrine_Template_TaggableTag->getPopularTagsTableProxy(Array)
#5 C:\Users\user\www\extens.dev\lib\Doctrine\Record.php(2569): call_user_func_array(Array, Array)
#6 [internal function]: Doctrine_Record->__call('getPopularTagsT...', Array)
#7 [internal function]: TaggableTag->getPopularTagsTableProxy(Array)
#8 C:\Users\user\www\extens.dev\lib\Doctrine\Table.php(2605): call_user_func_array(Array, Array)
#9 [internal function]: Doctrine_Table->__call('getPopularTags', Array)
#10 C:\Users\user\www\extens.dev\tools\sandbox\extensions\Taggable\tests\Template\TaggableTestCase.php(216): Doctrine_Table->getPopularTags(Array)
#11 C:\Users\user\www\extens.dev\tests\DoctrineTest\UnitTestCase.php(144): Doctrine_Template_Taggable_TestCase->testGetPopularTags()
#12 C:\Users\user\www\extens.dev\tests\DoctrineTest\GroupTest.php(61): UnitTestCase->run()
#13 C:\Users\user\www\extens.dev\tests\DoctrineTest.php(180): GroupTest->run(Object(DoctrineTest_Reporter_Cli), '')
#14 C:\Users\user\www\extens.dev\tools\sandbox\extensions\Taggable\tests\run.php(29): DoctrineTest->run()
#15

{main}

Tested: 1 test cases.
Successes: 26 passes.
Failures: 1 fails.
Number of new Failures: 0
Number of fixed Failures: 0

Tests ran in 1 seconds and used 15279.15625 KB of memory

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

The tests all pass now.

http://www.doctrine-project.org/extension/Taggable/1_2-1_0/tests

Comment by admirau [ 04/Nov/09 ]

It still does not work on my environment (Windows or Ubuntu 9.10, PHP 5.3/5.2.6)
The test result is a bit different, but still fails:

Doctrine Unit Tests
===================
Doctrine_Template_Taggable_TestCase.............................................failed

Unexpected Doctrine_Record_UnknownPropertyException thrown in [Doctrine_Template_Taggable_TestCase] with message [Unknown record property / related component "total_num" on "TaggableTag"] in /home/user/doctrine12b/lib/Doctrine/Record/Filter/Standard.php on line 55

Trace
-------------

#0 /home/taat/doctrine12b/lib/Doctrine/Record.php(1359): Doctrine_Record_Filter_Standard->filterGet(Object(TaggableTag), 'total_num')
#1 /home/taat/doctrine12b/lib/Doctrine/Record.php(1318): Doctrine_Record->_get('total_num', true)
#2 /home/taat/doctrine12b/lib/Doctrine/Access.php(117): Doctrine_Record->get('total_num')
#3 /home/taat/doctrine12b/tools/sandbox/extensions/Taggable/tests/Template/TaggableTestCase.php(217): Doctrine_Access->offsetGet('total_num')
#4 /home/taat/doctrine12b/tests/DoctrineTest/UnitTestCase.php(144): Doctrine_Template_Taggable_TestCase->testGetPopularTags()
#5 /home/taat/doctrine12b/tests/DoctrineTest/GroupTest.php(61): UnitTestCase->run()
#6 /home/taat/doctrine12b/tests/DoctrineTest.php(180): GroupTest->run(Object(DoctrineTest_Reporter_Cli), '')
#7 /home/taat/doctrine12b/tools/sandbox/extensions/Taggable/tests/run.php(29): DoctrineTest->run()
#8

{main}

Tested: 1 test cases.
Successes: 26 passes.
Failures: 1 fails.
Number of new Failures: 0
Number of fixed Failures: 0

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

Did you update Doctrine? I fixed something in Doctrine 1.2 that fixes it.

Comment by admirau [ 04/Nov/09 ]

Yes, the results above ("total_num") I get after updating to 1.2.0-BETA1.
At 1.2.0-ALPHA2 it was "no such column: a__2" (see above comments).

Do the extensions work with 2.0, or they are 1.2 specific?

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

1.2 specific. I don't get any fails now, can you try and troubleshoot it and figure out why it fails for you? They don't fail for me anywhere.

Comment by admirau [ 04/Nov/09 ]

Doctrine_Template_Taggable_TestCase::testGetPopularTags()
line 214:
$test = Doctrine::getTable('TaggableTag')->getPopularTags(array('ArticleTaggableTest', 'ArticleTaggableTest2'));

// compare this with your results
echo serialize($test);
result:
C:19:"Doctrine_Collection":169:{a:7:{s:4:"data";a:0:{}s:6:"_table";s:11:"TaggableTag";s:9:"_snapshot";a:0:{}s:14:"referenceField";N;s:9:"keyColumn";s:4:"name";s:8:"_locator";N;s:10:"_resources";a:0:{}}}

When I try to var_dump($test),
I get circular dependency.
I tried to save results of var_dump($test) to disk, by I get 1,5GB file, and still growing...

Maybe this article helps somehow:
http://www.bigroom.co.uk/blog/php-nesting-level-too-deep-recursive-dependency

Can I see the fix you mentioned above?

I'm sorry, but I do not know what else I can do.
Any ideas?

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

I am not sure what to say since it is working for me on all the machines I test. I'll be happy to look if I can get something to fail so I can troubleshoot it.

Comment by admirau [ 11/Nov/09 ]

I've tested on PLD Linux too.
The same thing.

Could you provide sample server/php configuration on which the tests are passing?

Can you describe the fix you've made to correct the errors with ''Unknown method Doctrine_Table::getPopularTags'.
Maybe I can manage to investigate it, but I do not know where to start.

Comment by admirau [ 11/Nov/09 ]

Sorry for reopening this again.

After upgrading to BETA2 all Taggable tests are passing OK for me too.

However, in the code I still get 'Unknown method BlogPostTable::getPopularTags' in /tools\sandbox\lib\Doctrine\Table.php:2793'
Isn't it a regression of the bug you've already fixed before ALPHA2?

Here is the description of how I came to this exception.

At the very end of config.php:

$manager->registerExtension('Taggable');

In the index.php:

<?php

require_once('config.php');

$models = Doctrine_Core::loadModels('models');

$post = new BlogPost();
$post->title = 'This is a sample blog post';
$post->description = 'Cool!';
$post->setTags('2009, symfony, doctrine');
$post->save();

$table = Doctrine::getTable('BlogPost');
echo get_class($table); // echoes Doctrine_Collection
$table->getPopularTags(); // this throws the exception

Then in the console:
php doctrine.php create-db
php doctrine.php generate-models-yaml (BaseBlogPost, BlogPost, BlogPostTable were generated)
php doctrine.php generate-sql (see SQL below)
php doctrine.php create-tables
(all ok)

php index.php

result:

BlogPostTablePHP Fatal error: Uncaught exception 'Doctrine_Table_Exception' with message 'Unknown method BlogPostTable::getPopularTags' in C:\Users\user\www\extens.dev\tools\sandbox\lib\Doctrine\Table.php:2793
Stack trace:
#0 [internal function]: Doctrine_Table->__call('getPopularTags', Array)
#1 C:\Users\user\www\extens.dev\tools\sandbox\index.php(15): BlogPostTable->getPopularTags()
#2

{main}
thrown in C:\Users\user\www\extens.dev\tools\sandbox\lib\Doctrine\Table.php on line 2793
Fatal error: Uncaught exception 'Doctrine_Table_Exception' with message 'Unknown method BlogPostTable::getPopularTags' in C:\Users\user\www\extens.dev\tools\sandbox\lib\Doctrine\Table.php:2793
Stack trace:
#0 [internal function]: Doctrine_Table->__call('getPopularTags', Array)
#1 C:\Users\user\www\extens.dev\tools\sandbox\index.php(15): BlogPostTable->getPopularTags()
#2 {main}

thrown in C:\Users\user\www\extens.dev\tools\sandbox\lib\Doctrine\Table.php on line 2793

And here is the generated SQL:

CREATE TABLE taggable_tag (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255) UNIQUE);
CREATE TABLE blog_post_taggable_tag (id INTEGER, tag_id INTEGER, PRIMARY KEY(id, tag_id));
CREATE TABLE blog_post (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(255) NOT NULL, description VARCHAR(255) NOT NULL);

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

When I test your code, it is working for me. You sure you don't have some old versions of PHP or something?

Comment by admirau [ 12/Nov/09 ]

Everything is up to date.
Tested on different servers, with different operating systems, different versions PHP, different versions of Doctrine, by different people.

Common thing for all these machines is that PHP (>5.2.10 <= 5.3.1) was installed from precompiled builds, not from source.

The error I get now is the same error I got earlier (at the beginning of this topic), which disapperared after your fix.
Then appeared the second error, which was fixed in BETA2, but the previous error is back. (strange, but the tests are passing now, despite the errors in the regular code).

When I find some spare time I'll try to trace the changes you've made since the beginning of the topic.

Comment by admirau [ 18/Nov/09 ]

Maybe the models are generated not properly.
Here are my models (three) for the reproduction procedure (above):

class BlogPostTable extends Doctrine_Table {}

class BlogPost extends BaseBlogPost {}

abstract class BaseBlogPost extends Doctrine_Record
{
public function setTableDefinition()

{ $this->setTableName('blog_post'); $this->hasColumn('title', 'string', 255, array( 'type' => 'string', 'notnull' => true, 'length' => '255', )); $this->hasColumn('description', 'string', 255, array( 'type' => 'string', 'notnull' => true, 'length' => '255', )); }

public function setUp()

{ parent::setUp(); $taggable0 = new Doctrine_Template_Taggable(); $this->actAs($taggable0); }

}

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

I have everything generated the same as you.

Comment by Benjamin Arthur Lupton [ 21/Nov/09 ]

Also getting this. Using doctrine 1.2.0-beta3 and also tried with latest SVN. Taggable is latest available.

PHP 5.3.0 running on Zend Server version 5.0.0Beta2

Comment by admirau [ 24/Nov/09 ]

No changes after upgrade to 1.2.0-RC1.

Comment by admirau [ 24/Nov/09 ]

Maybe this helps somehow:

// Following line throws:
// Doctrine_Table_Exception: Unknown method Doctrine_Table::getPopularTags in /home/user/doctrine12rc1/lib/Doctrine/Table.php on line 2799
$tags = Doctrine::getTable('BlogPost')->getPopularTags();

// This line returns collection of tags, as expected
$tags = Doctrine::getTable('TaggableTag')->getPopularTags('BlogPost');

$rel = Doctrine::getTable('BlogPost')->getRelations(); // is int(2)
$rel = Doctrine::getTable('TagableTag')->getRelations(); // is int(2)

Comment by Brian Smith [ 16/Dec/09 ]

Symfony 1.3 SVN updated as of this post.

Ubuntu Karmic with PHP 5.3.1

I have installed Taggable in mysymfonyproject/lib/doctrine_extensions/Taggable

I have two example tables defined with Taggable:

Video:
actAs:

{ Taggable: ~, Timestampable: ~ }

columns:
id:

{ type: integer, primary: true, autoincrement: true }

content_id:

{ type: integer, notnull: true }

title:

{ type: string(255) }

description:

{ type: clob }

relations:
Content:

{ local: content_id, foreign: id }

Photo:
actAs:

{ Taggable: ~, Timestampable: ~ }

columns:
id:

{ type: integer, primary: true, autoincrement: true }

content_id:

{ type: integer, notnull: true }

title:

{ type: string(255) }

description:

{ type: clob }

uri:

{ type: string(255) }

relations:
Content:

{ local: content_id, foreign: id }

The following code functions and populates the database:
$video = new Video();
...
$video->setTags(implode(", ", $tags));
$video->save();

The following code errors:
$tags = Doctrine::getTable('Video')->getPopularTags();

500 | Internal Server Error | Doctrine_Table_Exception
Unknown method VideoTable::getPopularTags

The following code errors:
$tags = Doctrine::getTable('TaggableTag')->getPopularTags('Video');

500 | Internal Server Error | Doctrine_Exception
Couldn't find class TagableTag

Comment by Sorin Neacsu [ 20/Jan/10 ]

Dont know if its related to this issue or not, but for some reason Doctrine::getTable('TaggableTag') throws a "

{Doctrine_Exception}

Couldn't find class TaggableTag" exception

I understand that you would normally do this:
Doctrine::getTable('Video')->getTags()
but I just want plain access to the TaggableTag model and Doctrine doesnt seem to generate any model classess for TaggableTag

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

I have tested everything everyone has provided and it is all working for me. The only thing I can suggest now is that someone creates a Doctrine failing test case so that I can run it to see the failure.

Comment by Benjamin Arthur Lupton [ 01/Mar/10 ]

Will create a test case this weekend for this and a few other problems I've across (with fixes). Nothing more frustrating than not being able to reproduce a problem, so I feel your pain.

Comment by Ivar Nesje [ 02/Mar/10 ]

I think this bug i related to the bug in the documentation http://www.doctrine-project.org/jira/browse/DC-378 to get the popular tags you will first have to load the models you want the tags for.

// load models that you want the tags from
Doctrine::getTable('blog');
Doctrine::getTable('products');
// then you can get the tags for the models currently loaded
$tags = Doctrine::getTable('TaggableTag')->getPopularTags();
Comment by Brian Smith [ 07/Mar/10 ]

This works for me:

// load models that you want the tags from
Doctrine::getTable('blog');
Doctrine::getTable('products');
// then you can get the tags for the models currently loaded
$tags = Doctrine::getTable('TaggableTag')->getPopularTags();

Comment by Benjamin Arthur Lupton [ 01/Apr/10 ]

Okie... Creating test cases for this turned out to be more complicated than I can handle - myself not being that familiar with phpunit.
Although within the test it is written as:
$test = Doctrine::getTable('TaggableTag')->getPopularTags(array('ArticleTaggableTest', 'ArticleTaggableTest2'));
Rather than:
$test = Doctrine::getTable('ArticleTaggableTest')->getPopularTags();
which is what this problem is about.

Although I do believe I've nailed the source of the problem - as well as others I've experienced.

Having either of the above causes the system to fall down. I've applied a bunch of fixes/changes to taggable to ensure it works with my systems, such as http://sos.7dots.co.uk/ (still in staging) which uses all of the above mentioned problems, not sure how to do a diff but here is the file:
http://www.2shared.com/file/12385197/c5911e42/Taggable.html

Hope that helps some people. Any changes I've made code can come under the same licence as doctrine, so no worries there.

Comment by admirau [ 15/Apr/10 ]

With 1.2.2 there is some progress.
There was still 1 test failing (CASCADE),
but with the version:
http://www.2shared.com/file/12385197/c5911e42/Taggable.html
provided by Benjamin Arthur Lupton
all test are passing now.

But now when I run:
getTable('ArticleTaggableTest')->getPopularTags();
I get: ERROR: column "i2__1" does not exist

The failing query on PostgreSql is:

SELECT t.id AS t_id, t.name AS tname, COUNT(DISTINCT i.id) AS i_0,
(COUNT(DISTINCT i.id)) AS i__1
FROM taggable_tag t
LEFT JOIN cms_model_image_taggable_tag c ON (t.id = c.tag_id)
LEFT JOIN image i ON i.id = c.id
WHERE t.id IN
(SELECT doctrine_subquery_alias.id
FROM
(SELECT DISTINCT t2.id, (COUNT(DISTINCT i2.id)) AS i2__1
FROM taggable_tag t2
LEFT JOIN cms_model_image_taggable_tag c2 ON (t2.id = c2.tag_id)
LEFT JOIN image i2 ON i2.id = c2.id
GROUP BY t2.id HAVING i2__1 > 0
ORDER BY i2__1 DESC LIMIT 10) AS doctrine_subquery_alias)
GROUP BY t.id HAVING i__1 > 0
ORDER BY i__1 DESC

Seems that this just a PostgreSql issue.
On Mysql it runs just fine.

Comment by Ivar Nesje [ 15/Apr/10 ]

The last comment is concerning how the poular tags are found and rated (on PostgreSql). I think this is unrelated to the rest of this issue and should be moved to a separate issue. (also I only got junk ads when I tried to get the file you are linking to).

Comment by admirau [ 15/Apr/10 ]

I have created separated issue for this:
http://www.doctrine-project.org/jira/browse/DC-634

And yes, this link is quite odd...
There is a lot of crap,
however there is a small link, to download improved code:

Look for: "Save file to your PC: click here"





[DC-81] Using WITH in combinations with LIMIT returns unexpected results Created: 06/Oct/09  Updated: 15/Jun/10

Status: Reopened
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.0-ALPHA1
Fix Version/s: None

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

Mac OS X 10.6.1



 Description   

When I try to limit left joined records with an additional WITH clause, it seems to be bugged when also specifying a LIMIT.

My DQL:

FROM Transporter t LEFT JOIN t.Profile p LEFT JOIN t.Requests r WITH (r.distributor_id = ?) WHERE t.is_active = ? ORDER BY p.company_country, p.company_name LIMIT 20

This returns me 0 results, while removing the LIMIT (or the WITH) will return me 2 results.



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

Sorry this is just not enough information to produce the problem. I ran some basic tests looking for what you pointed out but I didn't see any issues. Plus our tests cover this functionality so I imagine that if it were broke we'd get some failures. However, I could be wrong so if you could re-open and provide a failing test case for us that would help with getting it fixed.

Comment by Gerry Vandermaesen [ 16/Apr/10 ]

I actually ran into this problem once again in another problem.

Schema:

Story:
columns:
id:
type: integer(4)
unsigned: true
primary: true
autoincrement: true

Picture:
columns:
id:
type: integer(4)
unsigned: true
primary: true
autoincrement: true
story_id:
type: integer(4)
unsigned: true
notnull: true
is_selected:
type: boolean
notnull: true
default: false
relations:
Story:
foreignAlias: Pictures
local: story_id
foreign: id
type: one
foreignType: many
onDelete: CASCADE

Query:

Doctrine_Query::create()
->from('Story s')
->leftJoin('s.Pictures p WITH p.is_selected = ?', true)
->where('s.id = ?', 5)
->limit(10);

Outputted SQL:

SELECT "s"."id" AS "s_id", "s"."first_name" AS "sfirst_name", "s"."last_name" AS "slast_name", "s"."country" AS "scountry", "s"."email" AS "semail", "s"."content" AS "scontent", "s"."title" AS "stitle", "s"."summary" AS "ssummary", "s"."is_published" AS "sis_published", "s"."is_rejected" AS "sis_rejected", "s"."is_promoted" AS "sis_promoted", "s"."published_at" AS "spublished_at", "s"."created_at" AS "screated_at", "s"."updated_at" AS "supdated_at", "p"."id" AS "pid", "p"."story_id" AS "pstory_id", "p"."filename_original" AS "pfilename_original", "p"."filename_large" AS "pfilename_large", "p"."filename_thumb" AS "pfilename_thumb", "p"."mime_type" AS "pmime_type", "p"."is_selected" AS "pis_selected", "p"."created_at" AS "pcreated_at", "p"."updated_at" AS "p_updated_at" FROM "story" "s" LEFT JOIN "picture" "p" ON "s"."id" = "p"."story_id" AND ("p"."is_selected" = '1') WHERE "s"."id" IN (SELECT DISTINCT "s2"."id" FROM "story" "s2" LEFT JOIN "picture" "p2" ON "s2"."id" = "p2"."story_id" AND ("p2"."is_selected" = '5') WHERE "s2"."id" = '1' ORDER BY "s2"."published_at" DESC LIMIT 10) AND ("s"."id" = '5') ORDER BY "s"."published_at" DESC

Notice the WHERE "s2"."id" = '1' !

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

Can you provide a test case we can run?

Comment by Gerry Vandermaesen [ 15/Jun/10 ]

I could not figure out what test to write but I did narrow the problem down.

It seems that the order of the generated SQL clauses does not match the order of the passed parameters, so in the final SQL query the values are mixed up. You can actually see that happening in the SQL query above. I also noticed there a special cases hardcoded in the code for MySQL and PgSQL as far as these "limit subqueries" go, so that might be another reason why you havent bumped into problem before. I was using an SQLite driver.

I suppose something goes wrong in the SQL generation, but I don't know the core good enough to find out where exactly it does go wrong, so I'm afraid I can't attach a test case, but it should be easy to reproduce now anyway.





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

Status: Reopened
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.1.4, 1.1.5, 1.2.3
Fix Version/s: None

Type: Bug Priority: Major
Reporter: Fabian Brussa Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 7
Labels: None
Environment:

Windows XP, WampServer Version 2.0


Attachments: File DC185TestCase.php     Text File row_based_locking.patch    

 Description   

Scenario:
$entity = Doctrine::getTable('Steps')->find($pID);
$lockingManager = new Doctrine_Locking_Manager_Pessimistic( Doctrine_Manager::connection() );
$lockingManager->releaseAgedLocks(300);
$gotLock = $lockingManager->getLock($entity, 'user1' );

Running this code locks the entire table "Steps", and not just the record.

in the table "doctrine_lock_tracking", in the fields: "object_type" and "object_key" are saved in this case: "Steps" and "IDStep".
I think that here must be saved "Steps" and "120" (the value of IDStep).



 Comments   
Comment by Fabian Brussa [ 18/Nov/09 ]

Is anybody looking into this issue ?

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

Can you provide a test case that shows the issue? It is hard to look into the issue without a test to run When I look at the code and our tests everything is passing and fine so I am not sure what your issue could be. Re-open if you have more information to provide.

Comment by Fabian Brussa [ 19/Nov/09 ]

ok, I attach the test case

Comment by Fabian Brussa [ 03/Dec/09 ]

Have you already been able to look at the testcase ??

Comment by Fabian Brussa [ 14/Jan/10 ]

Any news ??

Comment by Piotr Leszczyński [ 25/Jun/10 ]

This issue is still valid for Doctrine 1.2. Doctrine_Locking_Manager_Pessimistic is UNUSABLE without this bug fixed!

Comment by Markus Wößner [ 02/Jul/10 ]

Having a look at "Doctrine_Locking_Manager_Pessimistic::getLock()" it becomes clear what causes this misbehaviour:

    public function getLock(Doctrine_Record $record, $userIdent)
    {
        $objectType = $record->getTable()->getComponentName();
        $key        = $record->getTable()->getIdentifier();

        $gotLock = false;
        $time = time();

        if (is_array($key)) {
            // Composite key
            $key = implode('|', $key);
        }

        try {
            $dbh = $this->conn->getDbh();
            $this->conn->beginTransaction();

            $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable
                                  . ' (object_type, object_key, user_ident, timestamp_obtained)'
                                  . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)');

            $stmt->bindParam(':object_type', $objectType);
            $stmt->bindParam(':object_key', $key);
            $stmt->bindParam(':user_ident', $userIdent);
            $stmt->bindParam(':ts_obtained', $time);

There is NO hint about the Record's identifier VALUE but only about the identifier's NAME (mostly "id") which appears to be redundant information. Instead of ...

        $key = $record->getTable()->getIdentifier();

..there should be something like ..

        $key = $record->get($record->getTable()->getIdentifier());

In case of composite keys a string concatenation, prefixed by identifier's name might work but I would recommend using "md5()" on resulting value to limit its length since field "object_key" is limited to 250 chars.

Comment by Florian Zumkeller-Quast [ 02/Jul/10 ]

Based on the previous comment by Markus Wößner i created a patch for row based locking.

It concatenates the PK fields and their values to a string and calculates the sha-1 hash as a unique string representing that record. This string is then used as key so that we'll only lock the single Record and not the whole table.

I hope you'll give this patch a try - It solved this problem for me.

Comment by Markus Wößner [ 02/Jul/10 ]

I applied patch from Mr. Florian Zumkeller-Quast and provided testcase didn't fail anymore. I think this should do it. By the way I find it strange that this issue isn't already fixed. I guess locking is not very much used by Doctrine users.

Comment by Jérôme Weber [ 21/Nov/11 ]

I applied patch too and it works now. I guess too that nobody use Lockings but when you use it ... without the patch it fails.

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

Duplicate of http://www.doctrine-project.org/jira/browse/DC-984





[DC-188] Pager breaks when HAVING clause references existing table column Created: 04/Nov/09  Updated: 20/Jul/10

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

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

Local: Windows/Cygwin/XAMPP
Stage & Prod: CentOS
Apache / MySQL
Framework: Zend



 Description   

Pager breaks when HAVING clause references any existing table column.

Query used:

$q = Doctrine_Query::create()
->select("u.id, u.first_name, u.last_name, u.is_active")
->addSelect('COUNT(u.id) as rolecount')
->from('User u')
->leftJoin('u.Roles r')
->groupBy('u.id')
->having("rolecount > 2 and u.is_active = 1");

Execution of query by itself works fine (eg via execute(), fetch...)

When putting this query in a Doctrine_Pager, error outputs:

$pager = new Doctrine_Pager(
$q,
$currentPage,
$resultsPerPage
);

$pager->execute();

Error Received:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'u.is_active' in 'having clause'



 Comments   
Comment by ryan [ 20/Jul/10 ]

a quick fix for this is to enclose the field in parentheses when selecting it, then use an alias to reference it inside the having clause. eg

$q = Doctrine_Query::create()
->select("u.id, u.first_name, u.last_name, (u.is_active) u_is_active")
->addSelect('COUNT(u.id) as rolecount')
->from('User u')
->leftJoin('u.Roles r')
->groupBy('u.id')
->having("rolecount > 2 and u_is_active = 1");





[DC-254] getLimitSubquery Not Including All Order By Parts Created: 18/Nov/09  Updated: 27/Feb/11

Status: Reopened
Project: Doctrine 1
Component/s: Query
Affects Version/s: 1.2.0-BETA3
Fix Version/s: 1.2.0-RC1

Type: Bug Priority: Major
Reporter: Michael Card Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None


 Description   

The getLimitSubquery function is only including the first orderby field and ignoring all remaining parts. The function also needs to be changed to include mssql and odbc.

The diff's below provide corrections.

Thanks,

Mike

diff -r Doctrine-1.1.2\lib\Doctrine\Query.php Doctrine-1.1.2-Fixes\lib\Doctrine\Query.php
1367c1367
<         if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci') {
---
>         if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc') {
1371,1387c1371,1392
<                 $part_original = trim($e[0]);
<                 $callback = create_function('$e', 'return trim($e, \'[]`"\');');
<                 $part = trim(implode('.', array_map($callback, explode('.', $part_original))));
< 
<                 if (strpos($part, '.') === false) {
<                     continue;
<                 }
< 
<                 // don't add functions
<                 if (strpos($part, '(') !== false) {
<                     continue;
<                 }
< 
<                 // don't add primarykey column (its already in the select clause)
<                 if ($part !== $primaryKey) {
<                     $subquery .= ', ' . $part_original;
<                 }
---
> 
>                 foreach ($e as $f) {
>                     if ($f == 0 || $f % 2 == 0) {
>                         $part_original = trim($f);
>                         $callback = create_function('$e', 'return trim($e, \'[]`"\');');
>                         $part = trim(implode('.', array_map($callback, explode('.', $part_original))));
> 
>                         if (strpos($part, '.') === false) {
>                             continue;
>                         }
> 
>                         // don't add functions
>                         if (strpos($part, '(') !== false) {
>                             continue;
>                         }
> 
>                         // don't add primarykey column (its already in the select clause)
>                         if ($part !== $primaryKey) {
>                             $subquery .= ', ' . $part_original;
>                         }
>                     }
>                 }



 Comments   
Comment by Michael Card [ 22/Dec/09 ]

Additonal fix for this issue, was missing dblib originally.

Mike


diff -r Doctrine-1.1.2\lib\Doctrine\Query.php Doctrine-1.1.2-Fixes\lib\Doctrine\Query.php
1367c1367
< if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc') {
—
> if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'mssql' || $driverName == 'odbc' || $driverName == 'dblib') {

Comment by Andrej Pavlovic [ 27/Feb/11 ]

Come on guys, please include this fix into 1.2.4...





[DC-278] Invalid qubquery generated if using oracle adapter instead of pdo_oci Created: 23/Nov/09  Updated: 09/Jun/10

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

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

Linux, Oracle 10g



 Description   

Doctrine generates the following invalid subquery if oracle adapter is used (same query is generated corret if pdo_oci is used):

SELECT DISTINCT "s2"."code"
FROM "spend_category" "s2"
INNER JOIN "company_spend_category" "c4" ON ("s2"."code" = "c4"."spendcategory_code")
INNER JOIN "company" "c3" ON "c3"."code" = "c4"."company_code"
WHERE "s2"."code" = '19000000'
AND "c3"."is_deleted" IS NOT NULL
AND "s2"."is_deleted" IS NOT NULL
ORDER BY "c3"."name" desc

The problem is that the order by column is not part of the selected columns.

Sample dql statement to reproduce this error:

$this->pageAllPager = new Doctrine_Pager(
$q = Doctrine_Query::create()
->select('c.code, c.name, c.is_activated, c.is_deleted, sc.code')
->from('SpendCategory sc')
->innerJoin('sc.Companies c')
->where("sc.code = '$spendcategory'")
->addWhere('c.is_deleted IS NOT NULL')
->addWhere('sc.is_deleted IS NOT NULL')
->orderBy($orderBy)
->setHydrationMode(Doctrine::HYDRATE_ARRAY),
$page,
$resultsPerPage);
}



 Comments   
Comment by Jonathan H. Wage [ 23/Nov/09 ]

I believe this is fixed now in the latest Doctrine 1.2. Can you test and confirm?

Comment by Thomas Wahle [ 24/Nov/09 ]

It is not fixed with 1.2 RC1

Same sql wich work fine with pdo_oci generates an error using the oracle adapter

<p>
<b>Message:</b> ORA-01791: Kein mit SELECT ausgewählter Ausdruck : SELECT s.code AS s_code, c.code AS ccode, c.name AS cname, c.is_activated AS cis_activated, c.is_deleted AS c_is_deleted FROM spend_category s INNER JOIN company_spend_category c2 ON (s.code = c2.spendcategory_code) INNER JOIN company c ON c.code = c2.company_code WHERE s.code IN (SELECT a.code FROM ( SELECT DISTINCT s2.code FROM spend_category s2 INNER JOIN company_spend_category c4 ON (s2.code = c4.spendcategory_code) INNER JOIN company c3 ON c3.code = c4.company_code WHERE s2.code = '37000000' AND c3.is_deleted IS NOT NULL AND s2.is_deleted IS NOT NULL ORDER BY c3.name desc ) a WHERE ROWNUM <= 10) AND (s.code = '37000000' AND c.is_deleted IS NOT NULL AND s.is_deleted IS NOT NULL) ORDER BY c.name desc.

Failing Query: "SELECT s.code AS s_code, c.code AS ccode, c.name AS cname, c.is_activated AS cis_activated, c.is_deleted AS c_is_deleted FROM spend_category s INNER JOIN company_spend_category c2 ON (s.code = c2.spendcategory_code) INNER JOIN company c ON c.code = c2.company_code WHERE s.code IN (SELECT a.code FROM ( SELECT DISTINCT s2.code FROM spend_category s2 INNER JOIN company_spend_category c4 ON (s2.code = c4.spendcategory_code) INNER JOIN company c3 ON c3.code = c4.company_code WHERE s2.code = '37000000' AND c3.is_deleted IS NOT NULL AND s2.is_deleted IS NOT NULL ORDER BY c3.name desc ) a WHERE ROWNUM <= 10) AND (s.code = '37000000' AND c.is_deleted IS NOT NULL AND s.is_deleted IS NOT NULL) ORDER BY c.name desc"</p>

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

I can't reproduce the issue in a test case. Can you help me with that? When I test what you're describing I get the results that are expected.

Comment by Thomas Wahle [ 25/Nov/09 ]

Hi Jon,

if i undestand the last comment correctly this issue will be fixed in 1.2 RC2.

I have reviewed lots of existing test cases but did not find an example where pdo_oci or oracle adapter is used.

Can you please forward the test case you have created for DC-278 to me? I will use this as a template for any further issues and hopefuly reduce your efforts.

Kind regards
Tom

> Jonathan H. Wage updated DC-278:
> --------------------------------
>
> Fix Version/s: 1.2.0-RC2
> (was: 1.2.0-RC1)

Comment by Thomas Wahle [ 10/Dec/09 ]

I do believe that I have found the reason and it is still an issue with Doctrine 1.2.1

Doctrine generate the following subquery which is processed in Doctrine_Query:: getLimitSubquery().

SELECT b.id FROM
(
SELECT a.*, ROWNUM AS doctrine_rownum FROM
(
SELECT DISTINCT i.id, i.lft
FROM item i
INNER JOIN oum o ON i.oum_id = o.id AND (o.is_deleted IS NOT NULL)
INNER JOIN item_type i2 ON i.type_id = i2.id AND (i2.is_deleted IS NOT NULL)
INNER JOIN item_translation i3 ON i.id = i3.id
LEFT JOIN attachment a ON i.id = a.item_id AND (a.is_deleted = 0)
WHERE i.bundling_id = ?
ORDER BY i.lft
) a
) b
WHERE doctrine_rownum BETWEEN 3 AND 4

This function replaces the table alias names. It looks like that the first occurance of "a" is detected and the inner alias for table attachment "a" is replaced by "a2" - that's fine. But also the outer table alias "a" is replaced by "a2" The result will be

SELECT b.id FROM
(
SELECT a.*, ROWNUM AS doctrine_rownum FROM
(
[...]
LEFT JOIN attachment a2 ON i.id = a2.item_id AND (a2.is_deleted = 0)
WHERE i.bundling_id = ?
ORDER BY i.lft
) a2  !!!!!!
) b

„a" is selected but the alias has been changed to „a2" and this will cause an sql error.

It looks like that this bug will only raise if a table is used in the subquery which starts with an "a"

Comment by Thomas Wahle [ 11/Dec/09 ]

As a workaround i have change "a" to "x" in the Doctrine_Connection_Oracle::_createLimitSubquery()

As far as no table in our projekt starts with character "x" this works fine for me.

By the way: Shouldn't it be $this->quoteIdentifier('a') . '.' instead of just a. ??

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

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

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

Can you provide the change that fixes the problem for you as a diff so we can test it?

Comment by Thomas Wahle [ 09/Jun/10 ]

Hi Jon,

long time with no hear from you. Hope you are well!

I am sorry, we did not fix this bug really. As writte above we have just implemented a work around by choosing a different character ("x" instead of "a") for the name of the generated sub query alias. This works fine with our data model (no table starts with "x") but may cause the same error with other data models.

At all: There was too much trouble in this project last year. Due to this we made the decision to go ahead with pdo_oci to finish the project in time.

Kind regards
Thomas

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

I'll leave this open if someone runs across the same problem, a test case showing the issue would help with pin pointing the problem area in the code.





[DC-280] Add pre/postHydrateResultSet() events Created: 23/Nov/09  Updated: 08/Jun/10

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

Type: New Feature Priority: Major
Reporter: Adam Jensen Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Over the last several weeks I've been working on streamlining the access control logic in the application I'm working on, and I realized that Doctrine's event listeners might be able to help. For more detailed background information take a look at http://groups.google.com:80/group/dallasphp/browse_thread/thread/91e3f107cd611adf ...but here's the problem in a nutshell:

Since my application's access control logic is all implemented in PHP rather than in the database (i.e., I can't add access control to my queries as a simple WHERE clause), I'm looking for a way to hook into the query process just after the records have been hydrated and actually modify the result set that gets returned, such that only permissible records show up in the final result set.

Unfortunately, although there are several listener methods that look promising for this, none of them seem to have access to the data being returned. For instance, if I run a custom query via Doctrine_Query::execute(), the postQuery() hook definitely runs ...but it doesn't give me access to anything but the query string itself.

Since, in some instances (e.g., hydration listeners), the Doctrine_Event object is assigned arbitrary data that the listener can modify, I'm wondering if the same thing couldn't be done more universally?



 Comments   
Comment by Jonathan H. Wage [ 24/Nov/09 ]

In Doctrine 1.2 you can create custom hydrators. You can extend the core hydrators to remove the data you want? I think that would work.

Comment by Adam Jensen [ 24/Nov/09 ]

Sure enough, that does the trick!

There are a couple of downsides, though, that might be worth considering in terms of future development:

1. It would be nice to be able to specify constructor arguments for the hydrator, so that collaborators can be injected. In my example, the hydrator needs access to the application's access control list object; currently it's simply retrieving it from a global registry, but it would be nice for testing's sake to be able to inject it instead.
2. It would also be nice to be able to chain multiple hydrators together; that's one reason I was looking at listeners, since they've got that capability already. That approach allows you to keep distinct behavior distinct a lot more easily.

Ultimately, I'd still kind of like to see another listener method available ...say, preHydrateResultSet() and postHydrateResultSet()? I think that would be a more flexible approach, even though the custom hydrator solution works quite well.

Thanks!
Adam

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

I like the idea. I'll move this to 1.3. I don't think we're gonna have a 1.3 version but if we do, it'll be there.

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

We can include this in a 1.2.x release if you would like to provide a patch and some tests. Thanks, Jon





[DC-287] Schema: package property for model Created: 25/Nov/09  Updated: 08/Jun/10

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

Type: Improvement Priority: Major
Reporter: Mickael HOAREAU Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None

Attachments: Text File DC-287.patch    

 Description   

There is a property "package" for the schema.yml file.
http://www.doctrine-project.org/documentation/manual/1_0/en/yaml-schema-files#features-examples:packages

But this should be used only for plugin symfony.

It will be good to have the same feature for classic model (not plugin), to be available to organize the model inside of the model folder.

This feature is critical for huge project. Indeed having 200 files at the root of the folder model/doctrine is very difficult to maintain.



 Comments   
Comment by Mickael HOAREAU [ 25/Dec/09 ]

Here a possible patch for doctrine 1.2, it is working for the basic cases.

It probably needs to be improved.

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

I agree this is a problem, but your patch is not good. It doesn't follow the coding standards and has some formatting problems. Also, it doesn't seem like a good solution. What do you think?





[DC-290] Relations need alias Created: 25/Nov/09  Updated: 09/Jun/10

Status: Reopened
Project: Doctrine 1
Component/s: Relations
Affects Version/s: 1.2.0-RC1
Fix Version/s: None

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


 Description   

While implementing a Record_Template and manipulating a query by using the preDqlSelect Event, i got massive problems if the query was generated by a refresh() or refreshRelated() call. I found out that the issue appears because the query has no alias for the table then. This makes it hard to add forther (sub-)selects to the query via preDqlSelect, e.g.

$params = $event->getParams();
		$alias = $params['alias'];

                if(!$query->isSubquery() && $alias == $queryClone->getRootAlias()) {	
				
				
				$countQuery = '(SELECT COUNT('.$alias.'_tcount.uid) FROM '.$modelName.' '.$alias.'_tcount WHERE '.$alias.'.'.$groupId.'='.$alias.'_tcount.'.$groupId.') AS '.$this->_options['terminationCount'];
				
				$query->addSelect($countQuery);
			}

The issue is solved by adding an alias in the foreignKey and localKey relation types' fetchRelatedFor methods (at least that's sufficient for my issue, maybe there is a need to add similar lines to the other relation types).

Doctrine_Relation_ForeignKey (from line 60):

$alias = $this->getTable()->getComponentName().'_rel';
            	
                $dql  = 'FROM ' . $this->getTable()->getComponentName()
                      .' '.$alias. ' WHERE ' . $this->getCondition($alias) . $this->getOrderBy(null, false);

Doctrine_Relation_LocalKey (from line 58):

$alias = $this->getTable()->getComponentName().'_rel';
        	
            $dql  = 'FROM ' . $this->getTable()->getComponentName()
                 .' '.$alias. ' WHERE ' . $this->getCondition($alias) . $this->getOrderBy(null, false);


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

If no alias is explicitly defined, the alias is automatically set to the model name. So in your code change you changed it from "ModelName" to "ModelName_rel". If you had the following:

SELECT * FROM User

The alias would be "User" and it is the same as if you did:

SELECT * FROM User User
Comment by Christian Jaentsch [ 01/Dec/09 ]

unfortunately this does not solve my problem... i narrowed it down to be a problem with addPendingJoinCondition in such a case.

here is a short scenario of what i want to do...

$modelName = 'Exhibition';
$alias = "exhibitionalias";
$subAlias = 'exhibitionsub';
		
$query = Doctrine_Query::create()
->from($modelName.' '.$alias);
		
$subQuery .= 'SELECT '.$subAlias.'.id FROM '.$modelName.' '.$subAlias.' WHERE '.$subAlias.'.id = '.$alias.'.id';
$query->addPendingJoinCondition($alias, $alias.'.id IN ('.$subQuery.')');
		
$query->execute();

this works so far as the alias is different from the model name... but if i change

$alias = "Exhibition";

i get the exception

exception 'Doctrine_Exception' with message 'Couldn't find class exhibitionsub' in /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Table.php:299
Stack trace:
#0 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Table.php(249): Doctrine_Table->initDefinition()
#1 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Connection.php(1126): Doctrine_Table->__construct('exhibitionsub', Object(Doctrine_Connection_Mysql), true)
#2 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1924): Doctrine_Connection->getTable('exhibitionsub')
#3 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1722): Doctrine_Query->loadRoot('exhibitionsub', 'exhibitionsub')
#4 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Where.php(76): Doctrine_Query->load('exhibitionsub', false)
#5 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Condition.php(92): Doctrine_Query_Where->load('exhibitionsub.i...')
#6 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(2077): Doctrine_Query_Condition->parse('exhibitionsub.i...')
#7 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1156): Doctrine_Query_Abstract->_processDqlQueryPart('where', Array)
#8 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1122): Doctrine_Query->buildSqlQuery(false)
#9 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(1137): Doctrine_Query->getSqlQuery(Array, false)
#10 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(1106): Doctrine_Query_Abstract->_getDqlCallbackComponents(Array)
#11 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1143): Doctrine_Query_Abstract->_preQuery()
#12 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1122): Doctrine_Query->buildSqlQuery(true)
#13 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/JoinCondition.php(87): Doctrine_Query->getSqlQuery()
#14 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Condition.php(92): Doctrine_Query_JoinCondition->load('Exhibition.id I...')
#15 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1089): Doctrine_Query_Condition->parse('Exhibition.id I...')
#16 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1013): Doctrine_Query->_processPendingJoinConditions('Exhibition')
#17 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1228): Doctrine_Query->_buildSqlFromPart()
#18 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query.php(1122): Doctrine_Query->buildSqlQuery(false)
#19 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(1137): Doctrine_Query->getSqlQuery(Array, false)
#20 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(1106): Doctrine_Query_Abstract->_getDqlCallbackComponents(Array)
#21 /var/www/erh_eeecore/core/lib/Doctrine/Doctrine/Query/Abstract.php(1001): Doctrine_Query_Abstract->_preQuery(Array)
#22 /var/www/erh_eeecore/app/modules/default/controllers/ExhibitionsController.php(75): Doctrine_Query_Abstract->execute()
Comment by Jonathan H. Wage [ 07/Dec/09 ]

Hmm. Christian, your issue doesn't seem at all related to the original issue. It seems like an entirely different problem, no?

Comment by Christian Jaentsch [ 08/Dec/09 ]

Well, I don't know where the reason for the problem is exactly... I just solved my problem by adding an alias to the foreignKey and localKey relations. The actual problem seems to be located in how the query is processed if the alias is equal to the name of the "from"-model. this causes problems while adding pending join conditions.

Comment by Jonathan H. Wage [ 08/Dec/09 ]

Ok, well what you described is totally un-related to this issue. If you have found a bug you can open another ticket with detailed information and a failing test case. Thanks, Jon

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

Can you show a patch with your changes?

Comment by Christian Jaentsch [ 09/Jun/10 ]

My patch is as shown in the description of this issue:

Doctrine_Relation_ForeignKey (from line 60):

$alias = $this->getTable()->getComponentName().'_rel';
            	
                $dql  = 'FROM ' . $this->getTable()->getComponentName()
                      .' '.$alias. ' WHERE ' . $this->getCondition($alias) . $this->getOrderBy(null, false);

Doctrine_Relation_LocalKey (from line 58):

$alias = $this->getTable()->getComponentName().'_rel';
        	
            $dql  = 'FROM ' . $this->getTable()->getComponentName()
                 .' '.$alias. ' WHERE ' . $this->getCondition($alias) . $this->getOrderBy(null, false);




[DC-292] no migrations diff on template change Created: 25/Nov/09  Updated: 01/Mar/10

Status: Reopened
Project: Doctrine 1
Component/s: None
Affects Version/s: 1.2.0-RC1
Fix Version/s: None

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


 Description   

the generate-migrations-diff does not create migrations if the template changes fields on the model.

For example:

File:
tableName: files
inheritance:
extends: Eeecore_Record_File
actAs:
Fileable:

The Fileable Template does the following... (the "fileFields" option stores a couple of fields to add to the model)

public function setTableDefinition()
{

foreach ($this->_options['fileFields'] as $key => $field)

{ $this->hasColumn($field['name'], $field['type'], $field['length'], $field['options']); }

}

everything works fine on generate-migrations-models (the initial migrations)... but if we change something on the "fileFields" the generate-migrations-diff call doesn't do anything. We have to rebuild all migrations or write a new migration by hand.



 Comments   
Comment by Jonathan H. Wage [ 07/Dec/09 ]

I added coverage for this issue and it is working as expected. I compare two schemas:

Article:
  columns:
    title: string(255)
    body: clob

and I compare it to this one:

Article:
  actAs: [Timestampable]
  columns:
    title: string(255)
    body: clob

And now I do this:

        $migration = new Doctrine_Migration(dirname(__FILE__) . '/DC292/migrations');
        $diff = new Doctrine_Migration_Diff(dirname(__FILE__) . '/DC292/from.yml', dirname(__FILE__) . '/DC292/to.yml', $migration);
        $changes = $diff->generateChanges();
        print_r($changes);

It has this in the array:

    [created_columns] => Array
        (
            [article] => Array
                (
                    [created_at] => Array
                        (
                            [notnull] => 1
                            [type] => timestamp
                            [length] => 25
                        )

                    [updated_at] => Array
                        (
                            [notnull] => 1
                            [type] => timestamp
                            [length] => 25
                        )

                )

        )

Comment by Christian Jaentsch [ 08/Dec/09 ]

The problem does not occur if you compare 2 schemas while one has a certain template and the other not.

In my case the problem occurs when the 2 schemas both already have the same template definition but in one case the template itself has changed (e.g. injects one more field into the database table of a certain model via setTableDefinition).

Comment by Jonathan H. Wage [ 08/Dec/09 ]

When I test that it works as well. Can you show some kind of reproducible test case?

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

Maybe you could add a test case for this?





[DC-293] Implement a self-reference class mechanism without the usage of associative classes Created: 25/Nov/09  Updated: 25/Nov/09

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

Type: Task Priority: Major
Reporter: Rui Miguel Gonçalves Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Ubuntu 9.10, Eclipse



 Description   

Equals to summary






[DC-312] Doctrine_Pager query "influences" Doctrine::getTable() query Created: 02/Dec/09  Updated: 02/Dec/09

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

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

Debian testing squeeze 32 bit.



 Description   

When I use the same procedure without Doctrine_Pager everything works fine, with Doctrine_Pager the behavior of later queries is strange. Example:
----------------WORKING:
1. I fetch list
Doctrine_Query::create()>select('z.,s.,o.*,u.jmeno as Vložil,k.nazev_cs as Kategorie')>from('ShopZbozi z,z.Obrazek o,z.Soubor s,z.Uzivatel u,z.ShopKategorie k')>orderby('z.nazev_cs ASC')>fetchArray();

2. I fetch a row to edit independently on the list above
$object = Doctrine::getTable('ShopZbozi')->find(123);

3. edit properties of the object...

4. $object->replace();
the object is fetched with no related objects like [Uzivatel] or [Soubor], so when I change for example $object->iduzivatel (related Uzivatel object id) and save it is OK

----------------BROKEN:
1. I fetch list in Pager
new Doctrine_Pager(Doctrine_Query::create()>select('z.,s.,o.*,u.jmeno as Vložil,k.nazev_cs as Kategorie')>from('ShopZbozi z,z.Obrazek o,z.Soubor s,z.Uzivatel u,z.ShopKategorie k')>orderby('z.nazev_cs ASC'),$this>page,$this->perpage);

2. I fetch a row to edit independently on the list above (in contrast to the first working example this $object is fetched with EMPTY RELATION OBJECTS, which causes inserting empty new rows when calling ->replace())
$object = Doctrine::getTable('ShopZbozi')->find(123);

3. edit properties of the object...

4. $object->replace();
-> the $object has all the related object fetched as it was defined in the list in Pager - like it was used as a template for getTable and when ->replace() - new empty related objects are inserted in DB.

I've been using Doctrine for I guess 2 years now and I believe this bug/strange behavior has always been there.
Maybe I'm wrong and it is not a bug, but the behavior is strange and it took me really long to find where the problem is and I still don't know how to use pager without influencing the later queries.
Thanx John Mathew






[DC-321] Doctrine/Import/Mssql.php does not handle default values Created: 03/Dec/09  Updated: 03/Dec/09

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

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

using odbc connection to sql server. (SQL Native Client)



 Description   

If I generate models from sql server I notice that the default values are empty although some columns in the database do have default values.

I did 'EXEC sp_columns @table_name = 'page';' in sql server and I could clearly see default values in 'column_def' so somehow the default values get lost.






[DC-322] Data dump fails on tables with quoted identifiers Created: 03/Dec/09  Updated: 04/Dec/09

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

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

linux, apache 2, mysql 5.1, php 5.2



 Description   

While dumping a table with a quoted identifier `numeric`, doctrine failed because the constructed query had an invalid alias the field: c__`numeric`.

Output:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`numeric`, c.alpha3 AS c_alpha3, c.alpha2 AS calpha2 FROM country_codes c' at line 1. Failing Query: "SELECT c.country AS ccountry, c.`numeric` AS c`numeric`, c.alpha3 AS calpha3, c.alpha2 AS c_alpha2 FROM country_codes c"

I know that using quoted identifiers is discouraged but I think this could be easily solvable.

Thanks.



 Comments   
Comment by Juozas Kaziukenas [ 03/Dec/09 ]

In which code part are you quoting that column? Because just enabling identifiers quoting would result in completely different results (at least there will be all columns quotes or none).

Comment by Massimiliano Torromeo [ 04/Dec/09 ]

I'm not using Doctrine::ATTR_QUOTE_IDENTIFIER, I generated a yaml from a preexisting db and then adapted it.

It generated the following definition:
CountryCodes:
columns:
country:
type: string(32)
notnull: true
`numeric`:
type: integer(2)
unsigned: 1
primary: true
alpha3:
type: string(3)
fixed: true
notnull: true
alpha2:
type: string(2)
fixed: true
notnull: true

but it was with an old version of Doctrine and this is not the case anymore (I tried regenerating it). I assumed it was correct to quote one single identifier, but I now guess it wasn't.

I think this can be closed as NotBug.

Sorry for the trouble.
Regards.

Comment by Juozas Kaziukenas [ 04/Dec/09 ]

However, variables cannot be quoted like that - quoting happens after actual columns are constructed, so now Doctrine needs to unquote it and do it's stuff. If you want quoting - enable that option and it will do it for you, or the best - don't use reserved words in your schema

This issue can be closed as Invalid.





[DC-325] doctrine pager class with sql server stored procedure Created: 04/Dec/09  Updated: 04/Dec/09

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

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

php 5.3.0 sql server 2000 symfony 1.2.9



 Description   

i am using doctrine pager class for pagination in symfony but not able to find any help how i can i use it

i am using sql server stored procedures for fetching databasae .

Thnaks

Khurram






[DC-326] Running out of memory while executing single record lookup. Created: 04/Dec/09  Updated: 07/Dec/09

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

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

Mac OS 10.5, Zend Server CE, PHP 5.3
Symfony 1.4



 Description   

I have the model class as follows:

schema.yml
options:
  collate: utf8_unicode_ci
  charset: utf8
  type: INNODB
Identity:
  tableName: Identity
  columns:
    id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    username:
      type: string(50)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    email:
      type: string(50)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    password:
      type: string(100)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    created_at:
      name: created_at
      type: timestamp
      # default: CURRENT_TIMESTAMP
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    updated_at:
      name: updated_at
      type: timestamp
      fixed: false
      unsigned: false
      primary: false
      default: null
      notnull: false
      autoincrement: false
  relations:
    Roles:
      class: Role
      local: id
      foreign: ident_id
      type: many
    Token:
      local: id
      foreign: entity_id
      type: many
    Devices:
      class: Device
      local: id
      foreign: account_id
      type: many
    Rides:
      class: Ride
      local: id
      foreign: account_id
      type: many
    OwnGroups:
      class: CoachGroup
      local: id
      foreign: owner_id
      type: many
    GroupMemberships:
      class: GroupMembership
      local: id
      foreign: ident_id
      type: many
  actAs:
    Timestampable:
      created:
        name: created_at
        type: timestamp
        expression: NOW()
      update:
        onInsert: false
Role:
  tableName: Role
  columns:
    identId:
      name: ident_id
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
    role:
      type: string(50)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: false
  relations:
    Identity:
      onDelete: CASCADE
      onUpdate: CASCADE
      local: ident_id
      foreign: id
      foreignAlias: Roles
Token:
  tableName: Token
  columns:
    entity_id:
      name: entity_id
      type: integer(4)
      fixed: false
      unsigned: false
      notnull: true
      primary: false
      autoincrement: false
    token:
      name: token
      type: string(50)
      fixed: true
      unsigned: false
      primary: true
      default: ''
      notnull: true
      autoincrement: false
    type:
      type: enum(50)
      fixed: false
      unsigned: false
      values:
        - EMAIL_VERIFICATION
        - PASS_RESET
      primary: false
      default: EMAIL_VERIFICATION
      notnull: true
      autoincrement: false
    created_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    expires_at:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
  indexes:
    entity:
      fields: [entity_id]
  relations:
    Identity:
      onDelete: CASCADE
      onUpdate: CASCADE
      local: entity_id
      foreign: id
      type: one
  actAs:
    Timestampable:
      created:
        name: created_at
        type: timestamp
      updated:
        disabled: true

and my unit test for the model:

TokenModelTest.php
$t = new lime_test(3);
$t->diag("=== Token model test ===");

$t->info('Token creation =>');
$token = new Token();
$token->setEntityId(1);
$token->generateUniqueToken();

$t->info('Set valid token type...');
$token->setType(Token::TYPE_EMAIL_VERIFICATION);
try{
  $t->info('Saving the token...');
  $token->save();
  $t->pass('Token was saved successfully...');
}
catch(Exception $e){
  $t->is(($e instanceof Exception), true, $e->getMessage());
}

$t->isnt($token->getCreatedAt(), null, ' Creation datetime is set to '.$token->getCreatedAt().'...');

$t->info('Get this token from DB...');
$tokenFromDb = Doctrine::getTable('Token')->findOneByToken($token->getToken());

$t->info('Compare the two...');
$t->is($tokenFromDb->getEntityId(), $token->getEntityId(), 'Entity ID...');
$t->is($tokenFromDb->getToken(), $token->getToken(), 'Token string...');
$t->is($tokenFromDb->getType(), $token->getType(), 'Token string...');
$t->is($tokenFromDb->getCreatedAt(), $token->getCreatedAt(), 'Token creation date...');
$t->is($tokenFromDb->getExpiresAt(), $token->getExpiresAt(), 'Token expration date...');
$t->is($tokenFromDb->getExpiresAt(), null, 'Token expration date is null...');

$t->info('Delete token...');
$t->is($token->delete(), true, 'Successful deletion...');

On test execution on this line:

$tokenFromDb = Doctrine::getTable('Token')->findOneByToken($token->getToken());

I'm getting a fatal error:

ERROR
# === Token model test ===
> Token creation =>
> Set valid token type...
> Saving the token...
ok 1 - Token was saved successfully...
ok 2 -  Creation datetime is set to 2009-12-04 01:13:31...
> Get this token from DB...
PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 261900 bytes) in /ApacheWebServer/htdocs/Clients/enki/enkiweb/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Core.php on line 550

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 261900 bytes) in /ApacheWebServer/htdocs/Clients/enki/enkiweb/lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Core.php on line 550


 Comments   
Comment by Jonathan H. Wage [ 07/Dec/09 ]

Anymore information? Not much I can really do right now. If you have some more information to help I can look at the problem again. A Doctrine test case would be helpful.





[DC-328] Multi-table query (left-join) problem in the Doctrine_Hydrator_Graph class Created: 04/Dec/09  Updated: 04/Dec/09

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

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

Ubuntu 9.10 Linux / PHP 5.2.x / Apache2 / Mysql 5


Attachments: File hasanozgan_com.sql    

 Description   

I tried below code. It must be return 2 records, but It returned 1 record. I traced Doctrine and found to reason in
Doctrine_Hydrator_Graph class line 165 ( $identifierMap[$rootAlias][$id[$rootAlias]] = $this->getLastKey($result); ) When couple $rootAlias not get record.

I attached my data and code. Is it problem?!

77 $q = Doctrine_Query::create();
78 $q->select("r.post_id as id, p.title as title, p.slug as slug, p.created_on as created_on")->
79 from("Relations r")->
80 leftJoin("r.Taxonomies t")->
81 leftJoin("t.Marks m")->
82 leftJoin("r.Posts p")->
83 where("m.slug = ?", $slug)->
84 andWhere("m.status = ?", self::PUBLISH)->
85 andWhere("p.status = ?", self::PUBLISH)->
86 andWhere("t.status = ?", self::PUBLISH)->
87 andWhere("t.type = ?", self::CATEGORY)->
88 orderBy("p.created_on desc");






[DC-329] Problem saving Self Referencing (Nest Relations) Created: 05/Dec/09  Updated: 03/Jun/11

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

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

Mac OSX 10.5, Symfony 1.4 and MAMP


Attachments: Zip Archive h2aEqualable.zip     PNG File saving process.png     File schema.yml     File testEqualNestRelationsTest.php     File testNestedEqualRelationWithObjectsTest.php    

 Description   

There is a problem when you save Many to Many Self Referencing (Nest Relations).

I used the same example that it's used on Doctrine 1.2 Self Referencing (Nest Relations) Documentation:

My Schema:

User:
columns:
name:

Unknown macro: { type}

relations:
Parents:
class: User
local: child_id
foreign: parent_id
refClass: UserReference
foreignAlias: Children

UserReference:
columns:
parent_id:
type: integer
primary: true
child_id:
type: integer
primary: true

Fixtures:

User:
james:
name: James
alexander:
name: Alexander
david:
name: David

The problem happens with the Children. The first time I assigned children and saved the User, there is no problem; but when I saved the User again (without any change on him) the values in the UserReference? table changes: the "parent_id" takes the value of the "child_id".

I test it with Sf 1.4 and with Sf 1.3 stable versions, and I've got the same error.

If it not clear to understand what I'm saying, I put a "very ilustrative" image about the form and how change the values of the UserReference? table. Please see it, because it would be very usefull for understanding (explains better than my terrible English)

Thanks for all your work!

P. D.

I forgot to to say that watching the stack trace I think that the problem is in:

symfony/lib/plugins/sfDoctrinePlugin/lib/vendor/doctrine/Doctrine/Connection/UnitOfWork.php

In the line 429:

public function saveAssociations(Doctrine_Record $record)

I would like to help more, but I couldn't figure out how this function works.



 Comments   
Comment by Jaime Suez [ 07/Dec/09 ]

This picture explains the error that it's done when you do an insert and then you save it again.

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

Can you provide a failing Doctrine test case? This may be a problem with Symfony and not Doctrine.

Comment by Jaime Suez [ 08/Dec/09 ]

First I published this bug on Symfony, because I thought that was a problem with Symfony, but you set it as invalid because it's belong to Doctrine.

This is the ticket on symfony:
http://trac.symfony-project.org/ticket/7690

I could do the Doctrine test case, but in one more mounth, because tomorrow I go out for vacations.
When I come back I'll do them.

Comment by psylosss [ 20/Dec/09 ]

Yes, I have got the same problem. During hours of debugging and exploring Doctrine's code, I found that problem localized in Hydrator component. I cannot digg deeper, so I ask you to fix it very much

Comment by Filippo De Santis [ 26/Dec/09 ]

Hi,
I had this problem in the 1.0 version of doctrine as well.
Using symfony, I upgraded to symfony 1.3 and doctrine 1.2 and I've found the same problem.

Attached to this comment you can find the files containing the schema I used (it is the same as that describe on this ticket but with a different class naming), and 2 unit tests. One using the symfony form and one using directly the doctrine objects. They report the bug discussed on this ticket and show another bug saving objects that already have one ore more relations.

As fixtures I used a fixtures.yml file containing:

Issue:
<?php for ($i = 1; $i <= 30; $i++): ?>
Issue_<?php echo $i; ?>:
title: "new issue <?php echo $i ?>"
<?php endfor; ?>

The following are the tests results:

– testEqualNestRelationsTest.php (using the forms) –

> First form for first issue: creation of the relation "issue 1 -> issue 2"
ok 1 - the edit form for issue 1 is valid
ok 2 - form1 saved
ok 3 - issue 1 is related with another issue
ok 4 - issue 1 is really related with issue 2

> Second form for first issue: saving the relation between "issue 1" and "issue 2" from "issue 2"'s form
ok 5 - the edit form for issue 2 is valid
ok 6 - form2 saved
not ok 7 - issue 2 is related with another issue ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 57)
  2. got: 0
  3. expected: 1
    not ok 8 - issue 2 is really related with issue 1
  4. Failed test (./test/unit/testEqualNestRelationsTest.php at line 58)
  5. got: NULL
  6. expected: 1

ok 9 - issue 1 is related with another issue
not ok 10 - issue 1 is really related with issue 2 ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 63)
  2. got: '1'
  3. expected: 2
    > Checking the relation table IssueReference ...
    ok 11 - There is only one relation saved on IssueReference
    ok 12 - 1 is the issue1 field of the relation
    not ok 13 - 2 is the issue2 field of the relation ******** this is the problem reported on this ticket ********
  4. Failed test (./test/unit/testEqualNestRelationsTest.php at line 71)
  5. got: '1'
  6. expected: '2'

> multi selection proof
ok 14 - the edit form for issue 1 is valid
ok 15 - form1 saved
ok 16 - the edit form for issue 2 is valid

                • this is the other bug I've found ********
                  not ok 17 - form2 exception catched : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 1
  1. Failed test (./test/unit/testEqualNestRelationsTest.php at line 114)

– testNestedEqualRelationWithObjectsTest.php (test using the "doctrine" objects ) –

> Saving relation directly from the objects and not using the forms...
ok 1 - issue1 saved
> checking issue1 relations
ok 2 - issue 1 is related with another issue
ok 3 - issue 1 is really related with issue 2

> checking "reverse" relation on issue2
ok 4 - issue 2 is related with another issue
ok 5 - issue 2 is really related with issue 1

> adding a relation issue2->issue1 directly
ok 6 - issue2 saved

> checking issue2 relations
not ok 7 - issue 2 is related with another issue ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 56)
  2. got: 0
  3. expected: 1
    not ok 8 - issue 2 is really related with issue 1
  4. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 57)
  5. got: NULL
  6. expected: 1

> checking issue1 relations
ok 9 - issue 1 is related with another issue
not ok 10 - issue 1 is really related with issue 2 ******** this is the problem reported on this ticket ********

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 63)
  2. got: '1'
  3. expected: 2

> Checking the relation table IssueReference ...
ok 11 - There is only one relation saved on IssueReference
ok 12 - 1 is the issue1 field of the relation
not ok 13 - 2 is the issue2 field of the relation

  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 71)
  2. got: '1'
  3. expected: '2'

> object multi adding relation proof
ok 14 - issue1 saved

                • this is the other bug I've found ********
                  not ok 15 - issue2 exception catched : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-1' for key 1
  1. Failed test (./test/unit/testNestedEqualRelationWithObjectsTest.php at line 112)
Comment by Jaime Suez [ 13/Jan/10 ]

With the test provided by Filippo De Santis is any other thing needed??

I still on vacations untill 3 of febrary, so then I could do any other thing needed.

Comment by Jaime Suez [ 01/Feb/10 ]

The necessary test have to be how are illustrated in this link???

http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

Comment by Alexander Sweis [ 09/Feb/10 ]

What has happen with this bug?? I also have the same problem...

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

Hi, yes. We still need a unit test case like described here: http://www.doctrine-project.org/documentation/manual/1_2/en/unit-testing

So we can run it with all the other tests and reproduce the issue in Doctrine by itself. Not in Symfony.

Thanks, Jon

Comment by psylosss [ 02/Mar/10 ]

Jon, here is the test for this bug: http://gist.github.com/319856

Please, fix it.. my work has been stopped cause of it

Comment by Jaime Suez [ 15/Mar/10 ]

Yes... please fix it... I'm also stuck in my work since a lot of time that the bug it's open.

Thanks

Comment by Nil Null [ 15/Mar/10 ]

I'm affected with this bug as well, fortunately, I found a way to get over it, it's ugly and innefficient, but at least my work isn't stopped due to this bug. I'll try to explain what I did commenting here later. Anyway, I really need this bug fixed too before I can start betatesting my app.
Thanks!

P.D: I'm using Doctrine 1.2.1.

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

I am trying to understand the issue but it just doesn't make much sense to me yet. The test case is wrong because you are dealing with instances of objects that have previously loaded references, then you try and re-fetch the same object instance. If you do $user1->free(true); then re-fetch the object the test passes as expected. So, I don't really have a proper failing test case still that actually exposes the problem. I'll keep playing around see if I can understand. let me know if anyone else has more information or a patch to test.

Thanks, Jon

Comment by Filippo De Santis [ 16/Mar/10 ]

Hi Jonathan,
This is the "translated" version of my unit test for symfony in "doctrine unit test"

http://github.com/ideato/phpcollab3/blob/phpcollabsf13/test/doctrine_unit_test/DC329TestCase.php

The first test is to show the error "SQLSTATE[23000]: Integrity constraint violation: 19 columns issue1, issue2 are not unique".
The second one is to show the fact that the relation are saved with wrong data.

Sorry for the late translation.

Filippo

Comment by Hendri Kurniawan [ 16/Mar/10 ]

Hi Jonathan,

It seems that the problem is caused by Doctrine_Collection::add() method line 456 (I could be totally wrong).

if (isset($this->referenceField)) {
    $value = $this->reference->get($this->relation->getLocalFieldName());
    if ($value !== null) {
        $record->set($this->referenceField, $value, false);
    } else {
        $record->set($this->referenceField, $this->reference, false);
    }
...

What is trying to do is to set the reference field value to the reference value that it's linked to.

This only happens when you try to fetch record from the "children".

Consider the following:

Employees:
  tableName: employees
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    name:
      type: string(100)
  relations:
    managing:
      class: Employees
      type: many
      local: manager_id
      foreign: employee_id
      foreignAlias: managedBy
      refClass: EmployeeManager

EmployeeManager:
...

Code:

// ----- The following will not give you any issues
  $manager = Doctrine::getTable('Issue')->findOneBy('id', '1'); // This is a manager
  foreach ($manager->managing as $employee) {
    ....
  }

  // This will not save anything
  $manager->save();
// -----

// ----- The following will
  $employee = Doctrine::getTable('Issue')->findOneBy('id', '2'); // This is an employee
  foreach ($employee->managedBy as $manager) {
    ...
  }

  // This will save the wrong data to the "EmployeeManager" table
  // because the code from Doctrine_Collection is overwriting "EmployeeManager" records
  // When they were being added to the collection by the Hydrator.
  $employee->save();
// -----

Debug backtrace when this happens:

string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1432"
string(103) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Collection.php @ line 461"
string(99) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Access.php @ line 131"
string(107) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Hydrator/Graph.php @ line 229"
string(101) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Hydrator.php @ line 137"
string(108) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Query/Abstract.php @ line 1036"
string(105) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Relation/Nest.php @ line 84"
string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1362"
string(100) "File: /Data/app/onlinevw-drupalvividwireless/libs/external-doctrine1/Doctrine/Record.php @ line 1333"

Comment by Pierrot Evrard [ 19/Mar/10 ]

Hi all,

For people who are looking for a workaround, I've found one that work for me.

Get the doctrine extension h2aEqualable (h2aEqualable.zip), register it as a doctrine extension (see http://www.doctrine-project.org/documentation/manual/1_2/0_11/extensions) and make your refClass of every equal nest relation acting as h2aEqualable.

In your PHP script :
{{
Doctrine::setExtensionsPath( 'path/to/unzip/place' );
Doctrine_Manager::getInstance()->registerExtension( 'h2aEqualable' );
}}

In your YAML schema :
{{
MyEqualNestRelationRefClassModel:
actAs:
h2aEqualable:
fields: [id_1,id_2]
}}

As I've said before, it works for me, so let me know if it solve your issues too...

Comment by Pierre Guéguin [ 18/Jun/10 ]

I have the very same issue with non equal nest relations.
It is stopping my project

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '87-87' for key 'PRIMARY'

execute : UPDATE cop_job_stream_successor SET job_stream_destination_id = ?, updated_at = ? WHERE job_stream_source_id = ? AND job_stream_destination_id = ? - (87, 2010-06-18 18:55:32, 87, 94)

CopJobStream:
columns:
name:
type: string(255)
notnull: false
....
relations:
SuccessorJobStreams:
class: CopJobStream
local: job_stream_source_id
foreign: job_stream_destination_id
refClass: CopJobStreamSuccessor
foreignAlias: PredecessorJobStreams
onDelete: CASCADE
onUpdate: CASCADE

CopJobStreamSuccessor:
columns:
job_stream_source_id:
type: integer
primary: true
job_stream_destination_id:
type: integer
primary: true
relations:
CopJobStream:
local: job_stream_source_id
foreignAlias: CopJobStreamSuccessors
onDelete: CASCADE
onUpdate: CASCADE

Comment by Pierre Guéguin [ 18/Jun/10 ]

It works anyway with above h2aEqualable extension

Comment by Daniel Reiche [ 26/Jan/11 ]

after stumbling into the same pit as everyone, i created a fresh report as DC-958. Later I found out that it has been reported before, so please mark DC-958 as duplicate of this. (or at least related, as I was using a Non-Equal Nested Set) also DC-952 refers to the same problem, but also with Non-Equal nestet sets.

My Case: Non-Equal-Nested-Set. Problems occur on saving Objects for 2nd or more time. Doctrine deletes all Child-Relations of the Object to be saved and updates Relations of the Childs to other Objects (other parents of the children objects) with references to the child itself!

the proposed h2aEqualable extension does prevent the wrong update statements but not the initial delete of the child-relations.

What exactly is missing on this bug to be fixed? It is now a year old, and clearly preventing people from using Self-Referencing relations with doctrine.

How can we help? More sample data, schema definitions, test cases?

Comment by Francesco Levorato [ 15/Feb/11 ]

Here is a better and simpler test case for the equal relation: https://gist.github.com/827414

There is clearly a memory problem here. I'll leave it up to Jonathan to decide whether it's a scenario which can be avoided in Doctrine itself or must be handled by Symfony (http://trac.symfony-project.org/ticket/9398).

In the Symfony context calls to refresh() might not be an option when modifying an object (aka saving a form).

Comment by Yitzchak Schaffer [ 17/Feb/11 ]

h2aEqualable seems to work for me.

Comment by Pavel Campr [ 02/Jun/11 ]

h2aEqualable works only partly for me (same as Daniel Reiche wrote).

I tried to identify the problem.

My usecase was:
1) I have an Article record in $article
2) I called $article->RelatedArticles->getPrimaryKeys() , where RelatedArticles is a name of my self reference
3) $article->save();

The problem originates from step 2), during hydratation process for related articles, which are added to a collection of related articles, in Collection->add() method (line 465) here:

if ($value !== null)

{ $record->set($this->referenceField, $value, false); }

else {

but, $this->referenceField contains wrong name of reference field. Self referenced model (Article) has two relations to the same class (one from "owning" side, second from "referencing" side). $this->referenceField in the collection is somewhere filled with the wrong relation name (not the"referencing" one, but the "owning" one).

When I save the $article, all referenced records are saved too and this is the problem, why the Doctrine tries to save corrupted data:

In my example, I have this data:

in Doctrine_Collection->add on line 457: $record) is a RelatedArticle (
article1 = string(1) "4"
article2 = string(1) "9"
)
in Doctrine_Collection->add on line 458: $this->referenceField) = string(19) "article1"
in Doctrine_Collection->add on line 459: $value) = string(1) "9"

BUT expected data is:

in Doctrine_Collection->add on line 458: $this->referenceField) = string(19) "article2"

This wrong behavior modified my RelatedArticle into this: RelatedArticle (
article1 = string(1) "9"
article2 = string(1) "9"
)

I have no idea how to fix it, but maybe someone can, I hope

(
my schema is:

Article
relations:
RelatedArticles:
class: Article
local: article1
foreign: article2
refClass: RelatedArticle
)

Maybe, when "refClassRelationAlias" option was invented to specifically point to a relation, instead of using "refClass", which can be used more times for one record and thus is not unambiguous, something for self referenced relations should be added as well. My "refClass: RelatedArticle" creates (probably) a relation from the foreign side too and Article contains two relations, which uses same refClass. Doctrine then doesn't know, which one should be used.

Comment by Pavel Campr [ 03/Jun/11 ]

Non-equal nest relations work properly, when refClassRelationAlias undocumented option is used, e.g.

Article:
...
relations:
RelatedArticles:
class: Article
local: article1
foreign: article2
refClass: RelatedArticle
refClassRelationAlias: RelatedArticleAlias

Anything can be used as a value for refClassRelationAlias.

Unfortunately, this doesn't fix equal nest relations.





[DC-331] Wrong SQL output from Doctrine_Expression for pgsql with timestamp with time zone field Created: 06/Dec/09  Updated: 05/Jan/10

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

Type: Bug Priority: Major
Reporter: Dennis Gearon Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None
Environment:

This is with Symfony 1.3 alpha (which is pretty good) Can't tell you which Doctrine it comes with



 Description   

(1) pgsql connection
(2) timestamp with time zone column
(3) $doctrine_expression = new Doctrine_Expression('NOW()');
echo $doctrine_expression->getSQL();
gives:
LOCALTIMESTAMP(0)

What I'd like to get access to using that Doctrine construct is the
functionality of 'CURRENT_TIMESTAMP', (has time zone,
stores time in TIMESTAMP WITH TIME ZONE columns in UTC time)

Fortunately, all the databases that I want to use implement
'CURRENT_TIMESTAMP', but not all PDO/Doctrine databases
support that construct, even though it's ANSI SQL standard,
(which ANSI I don't know.)



 Comments   
Comment by Michael Pearson [ 05/Jan/10 ]

I'm also seeing this with Symfony 1.4.1 (w/Doctrine 1.2). Affects timestampable tables (created_at, updated_at).

also, NOW() AT TIME ZONE 'UTC' translates to LOCALTIMESTAMP(0) AT TIME ZONE 'UTC' (via buildSqlQuery).





[DC-335] Oracle identifier too long in normal SELECT when using longer table name or column Created: 07/Dec/09  Updated: 13/Oct/10

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

Type: Bug Priority: Major
Reporter: Miloslav "adrive" Kmet Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Oracle



 Description   

Unfortunatelly oracle has max identifier length for 30 characters. When using longer model names eg. misCompanyContributor with column names the generated aliases for selected columns mix tableized modelname with colum name joined by two __, and sometimes the generated alias should exceed the allowed 30 characters long identifiers, and oracle complains with:

{{
ORA-00972: identifier is too long
}}

An example of large select with alias:
{{
SELECT
...
mis_contributor.contributor_id AS mis_contributor__contributor_id
..
FROM mis_contributor ...
}}



 Comments   
Comment by Michel D'HOOGE [ 13/Oct/10 ]

A workaround is available in DC-72 for version 1.1.4

Comment by Michel D'HOOGE [ 13/Oct/10 ]

I have applied the following patch to use aliases of identifiers (what is after the "as" when defining field name).

So far, it seems to work... But I am quite sure I didn't take all possible cases into consideration.

--- lib/vendor/doctrine/Doctrine/Hydrator/Graph.php.orig	2010-10-07 19:09:10.000000000 +0200
+++ lib/vendor/doctrine/Doctrine/Hydrator/Graph.php	2010-10-14 00:08:05.000000000 +0200
@@ -298,10 +298,10 @@
                 }
 
                 $e = explode('__', $key);
-                $last = strtolower(array_pop($e));
+                $fieldName = strtolower(array_pop($e));
                 $cache[$key]['dqlAlias'] = $this->_tableAliases[strtolower(implode('__', $e))];
                 $table = $this->_queryComponents[$cache[$key]['dqlAlias']]['table'];
-                $fieldName = $table->getFieldName($last);
+                $last = $table->getColumnName($fieldName);
                 $cache[$key]['fieldName'] = $fieldName;
                 if ($table->isIdentifier($fieldName)) {
                     $cache[$key]['isIdentifier'] = true;

--- lib/vendor/doctrine/Doctrine/Query.php.orig	2010-10-07 19:09:10.000000000 +0200
+++ lib/vendor/doctrine/Doctrine/Query.php	2010-10-14 00:03:28.000000000 +0200
@@ -494,12 +494,12 @@
                 $parentAlias = $this->getSqlTableAlias($componentAlias . '.' . $parent->getComponentName());
                 $sql[] = $this->_conn->quoteIdentifier($parentAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
                        . ' AS '
-                       . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
+                       . $this->_conn->quoteIdentifier($tableAlias . '__' . $fieldName);
             } else {
-                $columnName = $table->getColumnName($fieldName);
+                $columnName = $table->getColumnName($fieldName); // Really needed?
                 $sql[] = $this->_conn->quoteIdentifier($tableAlias) . '.' . $this->_conn->quoteIdentifier($columnName)
                        . ' AS '
-                       . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName);
+                       . $this->_conn->quoteIdentifier($tableAlias . '__' . $fieldName);
             }
         }
 
@@ -554,7 +554,7 @@
 
             return $this->_conn->quoteIdentifier($tableAlias . '.' . $name)
                    . ' AS '
-                   . $this->_conn->quoteIdentifier($tableAlias . '__' . $name);
+                   . $this->_conn->quoteIdentifier($tableAlias . '__' . $field);
         }
     }




[DC-338] Add setting charset to sandbox Created: 08/Dec/09  Updated: 10/Dec/09

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

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

mysql 5, ubuntu 9.04, php 5.2.10



 Description   

I try set charset adding to config.php in sandbox:
$manager = Doctrine_Manager::getInstance();
$manager->openConnection(DSN, 'doctrine');
$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_PEAR);
$manager->setCharset('utf8');

and this doesn't work.

Please update sandbox and give the how to right setCharset in this example. Almost used utf8.



 Comments   
Comment by Jonathan H. Wage [ 08/Dec/09 ]

This works properly. I test setCharset('utf8') and SET NAMES 'utf8' query is issued to the database properly. Please include reproducible code/information in your issue.

Comment by Ladislav Prskavec [ 09/Dec/09 ]

Try this example on my github http://github.com/abtris/doctrine-sandbox, screenshots included.

Comment by Ladislav Prskavec [ 10/Dec/09 ]

Try my sources, i now solution with add connection, but will be better support in manager for set encoding by options.





[DC-339] Documentation unclear about linking inherited objects Created: 08/Dec/09  Updated: 08/Dec/09

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

Type: Improvement Priority: Major
Reporter: Tarjei Huse Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

The (very nice) doctrine documentation fails to mention anything about how inherited objects handle relations.

I.e. if I got the model:
Entity:
columns:
username: string(20)
password: string(16)
created_at: timestamp
updated_at: timestamp

User:
inheritance:
extends: Entity
type: column_aggregation
keyField: type
keyValue: 1

Group:
inheritance:
extends: Entity
type: column_aggregation
keyField: type
keyValue: 2

Topic:
content: string
entity_id: integer
relations:
User:
class: Entity
local: entity_id
foreign: id

Can I then define both users and groups to link to Topic?






[DC-344] Trouble with auto including generate Base class with specifik name Created: 09/Dec/09  Updated: 21/Mar/10

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

Type: Bug Priority: Major
Reporter: Havelka Ondrej Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 3
Labels: None
Environment:

Linux, Ubuntu 9.04 64b



 Description   

I have found a problem during testing example model on page http://www.doctrine-project.org/documentation/cookbook/1_1/en/code-igniter-and-doctrine . A use YAML model with object name UserGroup and call method Doctrine_Core::createTablesFromModels('models'); process faling with error:

Fatal error: Class 'BaseUserGroup' not found in /sourcepath/models/UserGroup.php on line 13

Generate model file included abstract class BaseUserGroup exist and is OK. If I include BaseUserGroup manuly or rename object "UserGroup" on "UserGroups" everithing work fine. I thing here is a problem with autoloding base class with specifik name.

Here is my code example:

Doctrine_Core::dropDatabases();
Doctrine_Core::createDatabases();
Doctrine_Core::generateModelsFromYaml('sourcepath/yaml/model.yml', 'models');
Doctrine_Core::createTablesFromModels('models');

Trouble shotting YAML model is:

UserGroup:
columns:
user_id:
type: integer(4)
primary: true
group_id:
type: integer(4)
primary: true



 Comments   
Comment by Gustavo [ 26/Dec/09 ]

Same problem here following the same example of the 1.2 tutorial.

Comment by Michal Olszewski [ 08/Feb/10 ]

Hi,

I've stumbled upon the same problem and I think I know where the issue is.

So Doctrine_Core::createTablesFromModels() calls Doctrine_Export::exportSchema() which in turn calls Doctrine_Core::loadModels().

Doctrine_Core::loadModels() uses RecursiveIteratorIterator and iterates over all found files.

Now I think the order of files returned by RecursiveIteratorIterator is not always the same (depends on OS, filenames and cosmic radiation ), but the most important thing here is that class files from 'modules/generated' directory (as in examples) ARE NOT included before subclasses derived from generated classes. This means that Doctrine_Core::autoload() fails to load classes from 'modules/generated' directory, exactly this check fails:

if (0 !== stripos($className, 'Doctrine_') || class_exists($className, false) || interface_exists($className, false))

as base class is not starting with 'Doctrine_' and is not yet loaded.

To fix it properly the algorithm for loading modules must be changed to first include 'modules/generated' classes and then rest of classes. I am not sure but maybe Core::autoload() might be changed to include base classes properly.

QUICK WORKAROUND:
As a quick workaround I've changed parameters in call to createTablesFromModels() to:

Doctrine_Core::createTablesFromModels(array('models/generated','models'));

as createTablesFromModels() can accept array of directories.

Hope this helps you, please let me know if you need any more information. Thanks!

Comment by Svetoslav Shterev [ 09/Feb/10 ]

You are missing the model autoloader(http://www.doctrine-project.org/upgrade/1_2#Models%20Autoloading), which was added in 1.2

That should fix the problem with conservative autoloading.

Comment by Michal Olszewski [ 09/Feb/10 ]

I've tried registering modelsAutoload() and it works superb in this case for both aggressive and conservative loading.

It is a shame that it is not mentioned in 1.2 PDF I've got - it'd make life easier for some people

Thanks for your help.

Comment by blt [ 21/Mar/10 ]

i am a new user to doctrine and i hit this brick wall. this bug report was all that saved me, and it is a bit misleading. my test results are below. in the end i found a combination that worked, but this seems like a glaring bug especially since the pdf takes the user right down a path that fails completely in all cases (default aggressive loading, doesn't work for me at all).

i am using a pear loaded version 1.2 on ubuntu

here are my test results:
---------------------------------------------------------------------------------------------------
case 1: load models right after generating them, without modelsAutoLoad() call: SUCCESS/FAIL varies
---------------------------------------------------------------------------------------------------
in doctrine_bootstrap.php file:
<?
require_once('lib/vendor/doctrine/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('mysql:// DSN REMOVED ','doctrine');

in test.php:
<?
require_once('doctrine_bootstrap.php');
Doctrine_Core::generateModelsFromDb('models', array('doctrine'), array('generateTableClasses' => true));
Doctrine_Core::loadModels('models');

---------------------------------------------------------------------------------------------------
case 2: load models after they have already been generated, without modelsAutoLoad() call: FAIL
---------------------------------------------------------------------------------------------------
in doctrine_bootstrap.php file:
<?
require_once('lib/vendor/doctrine/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('mysql:// DSN REMOVED ','doctrine');

in test.php:
<?
// note: all model classes are in ./models and ./models/generated
require_once('doctrine_bootstrap.php');
Doctrine_Core::loadModels('models');

---------------------------------------------------------------------------------------------------
case 3: load models after they have already been generated, with the modelsAutoLoad() call and default aggressive setting: FAIL
---------------------------------------------------------------------------------------------------
in doctrine_bootstrap.php file:
<?
require_once('lib/vendor/doctrine/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('mysql:// DSN REMOVED ','doctrine');

spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));

in test.php:
<?
// note: all model classes are in ./models and ./models/generated
require_once('doctrine_bootstrap.php');
Doctrine_Core::loadModels('models');

---------------------------------------------------------------------------------------------------
case 4: load models after they have already been generated, with the modelsAutoLoad() call and conservative loading: SUCCESS
---------------------------------------------------------------------------------------------------
in doctrine_bootstrap.php file:
<?
require_once('lib/vendor/doctrine/Doctrine.php');
spl_autoload_register(array('Doctrine', 'autoload'));
$manager = Doctrine_Manager::getInstance();
$conn = Doctrine_Manager::connection('mysql:// DSN REMOVED ','doctrine');

$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));

in test.php:
<?
// note: all model classes are in ./models and ./models/generated
require_once('doctrine_bootstrap.php');
Doctrine_Core::loadModels('models');





[DC-348] Doctrine manual does not document that columns can be added with simple inheritance, or the semantics of accessing those columns in the parent Created: 10/Dec/09  Updated: 10/Dec/09

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

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


 Description   

The Doctrine manual's section on inheritance mentions simple inheritance only briefly. The examples do not show that columns can be added, nor do they explain that the parent model class can also access those columns (very useful when you override its methods at the application level in Symfony).

Both behaviors are supported (Jon suggested I take advantage of them at one point) but it's easy to miss the fact that they are available. For a long time I assumed column aggregation inheritance was the only way to add columns.

I'm now exploiting simple inheritance as a way to add columns to sfGuardUser rather than introducing an sfGuardUserProfile class with all of the attendant problems of trying to pretend two tables are actually one table. This is very useful.

(Out of curiosity, is there an alternative way to add columns to plugin schemas at the app level in Symfony 1.3 similar to the way it's now done for Propel?)






[DC-353] Doctrine_Query can't map a main query colum inside a subquery with join Created: 10/Dec/09  Updated: 10/Dec/09

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

Type: Bug Priority: Major
Reporter: Arian Maykon de Araújo Diógenes Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Apache 2.2.13, PHP 5.3, Fedora 11 or Ubuntu 9.04 (and Symfony 1.2.9/1.2.10 with Doctrine 1.0.12/1.0.14)



 Description   

If i have the following schema:

Medidor:
  tableName: TBLMEDIDOR
  columns:
    CODIGO:
      name: NRCODIGO as codigo
      type: integer(10)
      primary: true
      sequence: SEQMEDCODIGO
    DESCRICAO:
      name: TXDESCRICAO as descricao
      type: string(1000)
      notnull: true

AnaliseMedidor:
  tableName: TBLANALISE_MEDIDOR
  columns:
    CODIGO:
      name: NRCODIGO as codigo
      type: integer(10)
      primary: true
      sequence: SEQANMCODIGO
    DATA:
      name: DTDATA as dataAnalise
      type: date
      notnull: true
    MEDIDOR:
      name: FKMEDCODIGO as medidor_codigo
      type: integer(10)
      notnull: true
    OBSERVACAO:
      name: TXOBSERVACAO as observacao
      type: string(1000)
  relations:
    Medidor: { local: medidor_codigo, foreign: codigo, foreignAlias: Analises }

and execute the following query:

$query = Doctrine::getTable('Medidor')->createQuery()
    ->innerJoin('m.Analises a')
    ->where('a.dataAnalise = (SELECT MAX(a2.dataAnalise) FROM '
        . 'AnaliseMedidor a2 WHERE a2.medidor_codigo = a.medidor_codigo)');

the "a.medidor_codigo" in the subquery don't get correctly mapped. So Doctrine tells me:

{sfDoctrineLogger} executeQuery : SELECT t.nr80102codigo AS t__nr80102codigo, t.tx80102descricao AS t__tx80102descricao FROM TBL80102MEDIDOR t INNER JOIN TBL80103ANALISE_MEDIDOR t2 ON t.nr80102codigo = t2.fk80102codigo WHERE t2.dt80103data = (SELECT MAX(t3.dt80103data) AS t3__0 FROM TBL80103ANALISE_MEDIDOR t3 WHERE t3.fk80102codigo = t2.medidor_codigo)
{Doctrine_Connection_Oracle_Exception} SQLSTATE[HY000]: General error: 904 OCIStmtExecute: ORA-00904: "T2"."MEDIDOR_CODIGO": invalid identifier
 (/root/PDO_OCI-1.0/oci_statement.c:142)

If i put the real name column it runs ok:

$query = Doctrine::getTable('Medidor')->createQuery()
    ->innerJoin('m.Analises a')
    ->where('a.dataAnalise = (SELECT MAX(a2.dataAnalise) FROM '
        . 'AnaliseMedidor a2 WHERE a2.medidor_codigo = a.FKMEDCODIGO)');

But, this should not be done, right?

In Doctrine 1.2 it works fine. But in the related versions don't.



 Comments   
Comment by Arian Maykon de Araújo Diógenes [ 10/Dec/09 ]

Haven't added a TestCase because Doctrine 1.0.14 don't have them yet!





[DC-355] Call to a member function evictAll() if a table is retrieved, that is not existent Created: 12/Dec/09  Updated: 12/Dec/09

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

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

Ubuntu 8.04



 Description   

Hi!

Im not quite sure it this bahaviour is wanted, but i think that this
should be catched:

If i call Doctrine::getTable on a non existing model, the exception is
thrown. After them i want always to clear all Record Repositories, see
code:

try

{ $table = Doctrine::getTable('notexistent'); }

catch(Exception $e)

{ echo 'not existent'.$e->getMessage(); }

Doctrine_Manager::connection()->clear();

Then I get the error message:

Fatal error: Call to a member function evictAll() on a non-object in /
core/lib/Doctrine/Doctrine/Connection.php on line 1239

The problem is that the function clear doesnt check if a repository is
given.

public function clear()
{
foreach ($this->tables as $k => $table)

{ $table->getRepository()->evictAll(); // getRepository delivers FALSE $table->clear(); }

}

Is it normal behaviour? Or should it be checked first:

if ($repository = $table->getRepository())

{ $repository->evisctAll(); }

best regards,
aNj






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

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

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

Linux, php 5.2.10, apache 2.2.12



 Description   

I have this schema:

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

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

#Link
Conexion:
tableName: YT_CONEXION
columns:
cinterfazsrc:

{ type: integer, primary: true }

cinterfazdst:

{ type: integer, primary: true }

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

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

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

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

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



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

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

<?php

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

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

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

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

?>

.. and then when I ..

<?php

$pn = $dn->parentNodes;

?>

.. it goes like:

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

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

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

Using Doctrine 1.2.2

It seemed like the same thing as presented in the documentation

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

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

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

Please, oh please fix this ..

Comment by Danny Kopping [ 06/Mar/12 ]

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

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

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

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

Comment by Danny Kopping [ 06/Mar/12 ]

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

Comment by Jay Klehr [ 17/Jan/13 ]

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

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

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





[DC-357] setting "Doctrine_Core::ATTR_EXPORT" to "Doctrine_Core::EXPORT_TABLES" prevents i18n table creation Created: 14/Dec/09  Updated: 14/Dec/09

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

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


 Description   

When I try to prevent foreign key creation (because I am using a mix of MyISAM and InnoDB tables) using the given attribute, I notice that all the translation tables are also not getting created.



 Comments   
Comment by Jonathan H. Wage [ 14/Dec/09 ]

You can use the bit operator with this attribute.

http://www.doctrine-project.org/documentation/manual/1_2/en/configuration#exporting

Comment by Lukas Kahwe [ 14/Dec/09 ]

in that case the bug is bogus .. however the docs should probably make it clear that there are other export modes available, then illustrated atm.





[DC-359] concrete inheritance doesn't create all relations Created: 14/Dec/09  Updated: 16/Dec/09

Status: Open
Project: Doctrine 1
Component/s: Schema Files
Affects Version/s: 1.2.0, 1.2.1
Fix Version/s: None

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

PHP 5.2.11 (cli) (built: Oct 5 2009 21:36:09)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
with Xdebug v2.0.5, Copyright (c) 2002-2008, by Derick Rethans

Server version: Apache/2.2.13 (Unix)

Server version: 5.1.38-log MySQL Community Server (GPL)


Attachments: File fix-dc-359.diff     PNG File Picture 1.png    

 Description   

This is the YML schema

Entity:
  actAs:
    Timestampable:
  columns:
    id:
      type: integer(11)
      primary: true
      autoincrement: true
    name: string(50)
  relations:
    DynamicFields:
      class: DynamicField
      local: id
      foreign: dynamic_field_id
      refClass: EntityDynamicFields

DynamicField:
  actAs:
    I18n:
      fields: [name_xml]
  columns:
    id:
      type: integer(11)
      primary: true
      autoincrement: true
    name_xml: 
      type: string(50)
      notnull: true
  relations:
    Entities:
      class: Entity
      local: dynamic_field_id
      foreign: id
      refClass: EntityDynamicFields

EntityDynamicFields:
  actAs:
    I18n:
      fields: [value_xml]
  columns:
    id:
      type: integer(11)
      primary: true
    dynamic_field_id:
      type: integer(11)
      primary: true
    value_xml: string(250)

Airline:
  inheritance:
    extends: Entity
    type: concrete

Bank:
  inheritance:
    extends: Entity
    type: concrete

Client:
  inheritance:
    extends: Entity
    type: concrete

Employe:
  inheritance:
    extends: Entity
    type: concrete

Host:
  inheritance:
    extends: Entity
    type: concrete

Partner:
  inheritance:
    extends: Entity
    type: concrete

Person:
  inheritance:
    extends: Entity
    type: concrete

Supplier:
  inheritance:
    extends: Entity
    type: concrete

I run the commands

./doctrine build-all

and

./doctrine rebuild-db

The problem is when I verify if the foreign keys are created, but
these were only created for the "client" and "employee" models, to
"host" does not create the relationship in the MySQL, but if I rename
"host" with a name like "Ent", the relationship is established, or if I rename
the parent model "Entity" to "Zzzzz", all relations are created.

I did several tests, and the only way that the relation is created, is
that the model name, is alphabetically sorted before the parent model name.

This is a part of the dump of MySQL

ALTER TABLE `entity_dynamic_fields`
  ADD CONSTRAINT `entity_dynamic_fields_dynamic_field_id_dynamic_field_id` FOREIGN KEY (`dynamic_field_id`) REFERENCES `dynamic_field` (`id`),
  ADD CONSTRAINT `entity_dynamic_fields_id_airline_id` FOREIGN KEY (`id`) REFERENCES `airline` (`id`),
  ADD CONSTRAINT `entity_dynamic_fields_id_bank_id` FOREIGN KEY (`id`) REFERENCES `bank` (`id`),
  ADD CONSTRAINT `entity_dynamic_fields_id_client_id` FOREIGN KEY (`id`) REFERENCES `client` (`id`),
  ADD CONSTRAINT `entity_dynamic_fields_id_employe_id` FOREIGN KEY (`id`) REFERENCES `employe` (`id`),
  ADD CONSTRAINT `entity_dynamic_fields_id_entity_id` FOREIGN KEY (`id`) REFERENCES `entity` (`id`);

The other foreign keys are missed

you can view the diagram EER created with reverse engineering of MySQL Workbench



 Comments   
Comment by Juan Vega [ 15/Dec/09 ]

I know where is the problem, in Doctrine_Core::loadModels the list of models returned are alphabetically sorted, if I can rearrange the array by inheritance, the foreign keys for the models ('host' 'partner' 'person' 'supplier') are created.

more explicity:

I have this

Array
(
    [0] => Airline
    [1] => Bank
    [2] => Client
    [3] => DynamicField
    [4] => Employe
    [5] => Entity
    [6] => EntityDynamicFields
    [7] => Host
    [8] => Partner
    [9] => Person
    [10] => Supplier
)

I need this

Array
(
    [0] => Entity
    [1] => Airline
    [2] => Bank
    [3] => Client
    [4] => Employe
    [5] => Host
    [6] => Partner
    [7] => Person
    [8] => Supplier
    [9] => DynamicField
    [10] => EntityDynamicFields
)
Comment by Juan Vega [ 16/Dec/09 ]

ok, this is my patch to rearrange the models loaded, this array puts the child models before the parents





[DC-362] Doctrine fails to create correct table structure if model is named "User" Created: 16/Dec/09  Updated: 08/Jan/10

Status: Open
Project: Doctrine 1
Component/s: Behaviors, Query, Relations
Affects Version/s: 1.2.0-RC1
Fix Version/s: None

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

Mac OS X 10.6.2 (10C540) (Snow Leopard) with MAMP 1.8 bundle:
PHP Version: 5.2.10,
MySQL Version: 5.1.37



 Description   

When building models and database structure from YAML schema, Doctrine ignores the behaviors and relations on models if it is named "User":

...

User:  
  actAs:
    Timestampable:
    Sluggable:
      unique: true
      fields: username
      canUpdate: true
  columns:
    id:
      type: integer(4)
      primary: true
      autoincrement: true
    company_id
      type: integer(4)
    timezone_id:
      type: integer(1)
    role_id:
      type: integer(1)
    email:
      type: string(255)
    username:
      type: string(255)
      unique: true
    password:
      type: string(40)
    firstname:
      type: string(255)
    lastname:
      type: string(255)
    last_login:
      type: datetime
  relations:
    Company:
      local: company_id
      foreign: id
    Timezone:
      local: timezone_id
      foreign: id
    Role:
      local: role_id
      foreign: id

...

This creates the following table structure:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `company_id` int(11) DEFAULT NULL,
  `timezone_id` tinyint(4) DEFAULT NULL,
  `role_id` tinyint(4) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `firstname` varchar(255) DEFAULT NULL,
  `lastname` varchar(255) DEFAULT NULL,
  `last_login` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The table structure is both missing foreign key constraints to Company, Timezone and Role. It is also missing columns updated_at and created_at for Timestampable behavior. The slug column for Sluggable behavior is missing, as well.

When looking at the BaseUser::setUp() method it looks as it is supposed to:

class BaseUser extends Doctrine_Record
{

    ....

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Company', array(
             'local' => 'company_id',
             'foreign' => 'id'));

        $this->hasOne('Timezone', array(
             'local' => 'timezone_id',
             'foreign' => 'id'));

        $this->hasOne('Role', array(
             'local' => 'role_id',
             'foreign' => 'id'));

        $timestampable0 = new Doctrine_Template_Timestampable();
        $sluggable0 = new Doctrine_Template_Sluggable(array(
             'unique' => true,
             'fields' => 'username',
             'canUpdate' => true,
        ));
        $this->actAs($timestampable0);
        $this->actAs($sluggable0);
    }

    ....

}

So the only area where it goes wrong, is when generating the queries for creating the model tables. I don't know if the same problem appears with other model names, but it doesn't like models named "User".

If I rename the model to "Person" and rebuild, it all works perfectly as it should.



 Comments   
Comment by Michael Henriksen [ 16/Dec/09 ]

Forgot to mention, that it works perfectly when renaming model to something else than "User"

Comment by Sander [ 08/Jan/10 ]

Have the same problem in 1.2.1 at PostgreSQL 8.4





[DC-368] createTablesFromModels() wants to create already existing FOREIGN KEY constraints Created: 18/Dec/09  Updated: 24/Aug/10

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

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

mysql Ver 14.12 Distrib 5.0.75, for debian-linux-gnu (i486) using readline 5.2
PHP 5.2.11-0.dotdeb.1 with Suhosin-Patch 0.9.7 (cli) (built: Sep 20 2009 09:41:43)
Ubuntu 9.04


Attachments: Text File schema.txt     Zip Archive testcase.zip    

 Description   

If you create InnoDB tables from a given model directory, the table generator wants to create a foreign key constraint that already exists.

1. Doctrine_Core::generateModelsFromYaml('yaml', 'models');
2. Doctrine_Core::createTablesFromModels('models');
3. Running this setup twice, will print out the following error:

SQLSTATE[HY000]: General error: 1005 Can't create table './dev_mreiche/#sql-930_2cb7.frm' (errno: 121). Failing Query: "ALTER TABLE group_user ADD CONSTRAINT group_user_user_id_user_id FOREIGN KEY (user_id) REFERENCES user(id)". Failing Query: ALTER TABLE group_user ADD CONSTRAINT group_user_user_id_user_id FOREIGN KEY (user_id) REFERENCES user(id)



 Comments   
Comment by Mike Reiche [ 18/Dec/09 ]

Moved model and setup code from description to attachment.

Comment by Michal Olszewski [ 09/Feb/10 ]

Hi,

Just a quick comment - the test case you've provided works fine for me using 1.2.1 and also latest code from 1.2 branch... you might try that.

The error above (1005) is caused by mismatch between local and foreign key definitions. So it seems somewhere along the lines you/Doctrine messed up field definitions (although I can't see it provided test case). Try using integer without length definition in YAML, like:

id:
type: integer
autoincrement: true
primary: true

and check if this is working.

Comment by PpW8bNH3jy2A [ 01/Mar/10 ]

I'm having the same issue. However, I've tried the test case using a sqlite memory only database and i can't trigger the problem.

Here's my mysql schema, for your review - which does trigger the issue using 1.2.1.

Comment by PpW8bNH3jy2A [ 01/Mar/10 ]

I put some debugging statements in Doctrine/Export.php around line 1216:
------------
$connection->exec($query);
} catch (Doctrine_Connection_Exception $e) {
// we only want to silence table already exists errors
+ print_r($e->getPortableCode());
+ print_r(Doctrine_Core::ERR_ALREADY_EXISTS);
+ print_r($e->getMessage());
+ echo "<br><br>";
+// exit;
+
+
if ($e->getPortableCode() !== Doctrine_Core::ERR_ALREADY_EXISTS) {
$connection->rollback();

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

Here's the output I get:

-5-5SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'category' already exists. Failing Query: "CREATE TABLE category (id BIGINT AUTO_INCREMENT, name VARCHAR(80), company_id BIGINT, INDEX company_id_idx (company_id), PRIMARY KEY(id)) ENGINE = INNODB"

-5-5SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'company' already exists. Failing Query: "CREATE TABLE company (id BIGINT AUTO_INCREMENT, name VARCHAR(80) UNIQUE, address1 VARCHAR(80), address2 VARCHAR(80), city VARCHAR(80), state VARCHAR(10), zipcode VARCHAR(20), phone VARCHAR(20), fax VARCHAR(20), url VARCHAR(255), logo VARCHAR(255), perferedcolumn BIGINT, randomsort BIGINT, comment LONGTEXT, PRIMARY KEY(id)) ENGINE = INNODB"

-5-5SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'user' already exists. Failing Query: "CREATE TABLE user (email VARCHAR(255), password VARCHAR(80), fullname VARCHAR(80), company_id BIGINT, cellphone VARCHAR(20), voice VARCHAR(20), voiceext VARCHAR(20), fax VARCHAR(20), comment LONGTEXT, status TINYINT(1), admin TINYINT(1), timeadded DATETIME, timechagned DATETIME, INDEX company_id_idx (company_id), PRIMARY KEY(email)) ENGINE = INNODB"

-15-5SQLSTATE[HY000]: General error: 1005 Can't create table './iprfpartners/#sql-7eeb_2d8.frm' (errno: 121). Failing Query: "ALTER TABLE category ADD CONSTRAINT category_company_id_company_id FOREIGN KEY (company_id) REFERENCES company(id)"

Comment by B. Ariston Darmayuda [ 23/Aug/10 ]

I have same problem, but this problem is face on db engine side. When we look at the last query sql like:

ALTER TABLE category ADD CONSTRAINT category_company_id_company_id FOREIGN KEY (company_id) REFERENCES company(id)

The first call of createTablesFromModels will create the table and add contraint which run fine because table and constraint not exist yet. Then when we execute createTablesFromModels again it will fail because it still try to create constraint which already exist on table. I'm still looking on MySql section how to check the constrain if it exist or not. If the constraint not exist then we can execute the sql above, if not we need to avoid execution for sql above, this mean we cannot MODIFY the constrain (like ON UPDATE and ON DELETE mode).

Comment by B. Ariston Darmayuda [ 24/Aug/10 ]

I've figure out the errorno: 121 which I thinking is that the process try re-adding existing CONSTRAINT name. The resolve that I've found is for MySQL engine and modify some Doctrine libraries.

1. I've modify Doctrine_Export_Mysql by adding override function of:

public function createForeignKeySql($table, array $definition)
{
    $tableInfo = $this->conn->execute('SHOW CREATE TABLE '.$this->conn->quoteIdentifier($table));
    if ($tableInfo && ($row = $tableInfo->fetch()))
      if ($row['Create Table'] && preg_match('/CONSTRAINT `'.$definition['name'].'`.+/i', $row['Create Table'])) return '';
    return parent::createForeignKeySql($table, $definition);
}

2. Since if CONSTRAINT already exist the createForeignKeySql return empty string, we need modify function on Doctrine_Export with:

public function createForeignKey($table, array $definition)
{
    $sql = $this->createForeignKeySql($table, $definition);
    if ($sql != '')
      return $this->conn->execute($sql);
    else
      return -1;
}

Now by add/modify function above I can savely run createTablesFromModels because if CONSTRAINT of a table exist on database the ALTER TABLE ... ADD CONSTRAINT will not generated. Hope this can help some of you guys.





[DC-370] Doctrine serializes arrays, objects, etc. like 'string', which is never bigger than a TEXT, limited to 65535 characters (in MySQL) Created: 19/Dec/09  Updated: 29/Jan/10

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

Type: Improvement Priority: Major
Reporter: Tom Boutell Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Doctrine supports storing objects and arrays, and implements this via serialize().

However in DataDict/Mysql they are handled like the 'string' type, which means they are subject to the rules there that ensure nothing bigger than a 'TEXT' is ever used to represent them.

TEXT is not a great choice for objects and arrays because it's difficult to ensure they will not exceed 65,535 bytes in size.

This would be most easily fixed by moving them to the next block of case statements there, used for CLOBs. The logic there already picks suitable large types (MEDIUMTEXT and LONGTEXT) as needed, and defaults to LONGTEXT which is a good choice for objects and arrays.



 Comments   
Comment by David Abdemoulaie [ 29/Jan/10 ]

Array and Object data types now behave identically to clob.

See r7077

Comment by Tom Boutell [ 29/Jan/10 ]

Thanks David!





[DC-372] I18n record generator assumes relation alias is the table name Created: 20/Dec/09  Updated: 20/Dec/09

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

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

latest symfony 1.4 SVN.



 Description   

In Doctrine/I18n.php, method setTableDefinition, line 108:

        foreach($relations as $table => $relation) {

But the $relations array key is not a table name, but a relation alias.

So currently the generator assumes the relation alias IS the table name.
When it's not true, the I18n table definition fails.






[DC-373] Relating to Translation table (generated by Doctrine_I18n) doesn't work correctly after resetting connection Created: 20/Dec/09  Updated: 19/Dec/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...

Comment by Baptiste SIMON - Libre Informatique [ 15/Dec/14 ]

Hi guys,

I found a workaround for this bug on multiple DB connections :
In my *-schema.yml I have defined my i18n table as :

(...)
actAs:
I18n:
fields: [xxx, yyy, zzz]
generateFiles: true
generatePath: <?php echo sfConfig::get('sf_lib_dir'); ?>/model/doctrine/i18n
(...)

(notice the generateFiles & generatePath...)

This (alone) seems to solve my issue. I'll give more feed back if there is any.
FEEDBACK: do not work with inheritated behaviors... so it's not correct for our needs.

sources: http://forum.symfony-project.org/viewtopic.php?t=24071

Comment by Baptiste SIMON - Libre Informatique [ 15/Dec/14 ]

eventually, for a portable solution (web), you can use this path :

(...)
generatePath: ../<?php echo str_replace(sfConfig::get('sf_root_dir').'/', '', sfConfig::get('sf_lib_dir')) ?>/model/doctrine/i18n
(...)

this is a trick for file replication between servers that have different DOCUMENT_ROOT path.

Comment by Baptiste SIMON - Libre Informatique [ 19/Dec/14 ]

ok sorry for the multiple posts... I maybe have found a smart solution by patching Doctrine/Record/Generator.php that way :

Index: Doctrine/Record/Generator.php
===================================================================
— Doctrine/Record/Generator.php (révision 4690)
+++ Doctrine/Record/Generator.php (copie de travail)
@@ -163,7 +163,7 @@
// check that class doesn't exist (otherwise we cannot create it)
if ($this->_options['generateFiles'] === false && class_exists($this->_options['className']))

{ $this->_table = Doctrine_Core::getTable($this->_options['className']); - return false; + //return false; }

$this->buildTable();
@@ -461,10 +461,10 @@
} else

{ throw new Doctrine_Record_Exception('If you wish to generate files then you must specify the path to generate the files in.'); }
  • } else { + }

    elseif ( !class_exists($definition['className']) )

    { $def = $builder->buildDefinition($definition); eval($def); }

    }

This implicates multiple rebuilding of the same class, but at least, it works... without any modifications in the schema.

Comment by Baptiste SIMON - Libre Informatique [ 19/Dec/14 ]

I found another failing case, very very isolated... And I improved the patch.
To avoid some kind of flooding here, here is the reference of the latest solution :

http://www.e-glop.net/main/Rendre_Doctrine1_multi-connexions_fonctionnel_avec_ses_diff%C3%A9rents_Behaviors





[DC-375] Doctrine_Table getTable singleton issue Created: 22/Dec/09  Updated: 22/Dec/09

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

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

symfony 1.2.9



 Description   

first, i defined a table class :
class CohibaClientTable extends Doctrine_Table
{
public $_pager;

public function getAbstractList($arrParam = array(), $page=1, $maxPerPage=20)
{
$objQuery = $this->createQuery('t1')
->select('t1.*');

if(is_array($arrParam) && count($arrParam)>0)

{ QueryAssistant::processOption($objQuery, $arrParam); // dont set "offset" and "limit" option in it }

$this->_pager = new Doctrine_Pager($objQuery, $page, $maxPerPage);

$items = $this->_pager->execute();

$objQuery->free();
return $items;
}

public function getList($page=1, $maxPerPage=20)

{ $arrParam = array( 'orderBy'=>'t1.cle asc' ); return $this->getAbstractList($arrParam, $page, $maxPerPage); }

public function getPager()

{ return $this->_pager; }

}

and then, in the action, invoke it like this codes:
1>
$items = Doctrine::getTable("CohibaClient")->getList(1, $maxPerPage);
$pager = Doctrine::getTable("CohibaClient")->getPager();

$this->log("total records: ".$pager->getNumResults()." total page: ".$pager->getLastPage()."\n");
$lastPage = $pager->getLastPage();
2>
$table = Doctrine::getTable("CohibaClient");
$items = $table->getList(1, $maxPerPage);
$pager = $table->getPager();

$this->log("total records: ".$pager->getNumResults()." total page: ".$pager->getLastPage()."\n");
$lastPage = $pager->getLastPage();

#2 works, but not #1, error is "Fatal error: Call to a member function getNumResults() on a non-object in.... " is it an issue when singleton generation?






[DC-379] No description of ATTR_DEFAULT_IDENTIFIER_OPTIONS now in "Chapter 4 Configuration" Created: 23/Dec/09  Updated: 23/Dec/09

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

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


 Description   

In the previous (1.1) documentation version there were small but useful description about how to set up primary key (http://www.doctrine-project.org/documentation/manual/1_1/en/configuration#defaults-attributes:default-added-auto-id)
Now there is nothing about ATTR_DEFAULT_IDENTIFIER_OPTIONS and it takes about 20 minutes to debug and find out where did "id" field added

ps: message "If you find a problem with the documentation or have a suggestion, please register and open a ticket. " in the bottom of the docs pages is ambiguous due to it points to trac :-$






[DC-383] Migrations not respecting ATTR_TBLNAME_FORMAT Created: 23/Dec/09  Updated: 28/May/10

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

Type: Bug Priority: Major
Reporter: Karma Dordrak (Drak) Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Debian 5, Apache 2, PHP 5.2.9, MySQL 5.1


Attachments: Text File migration_table_prefix_doctrine_1.2.patch    

 Description   

I am using Doctrine 1.2.1 and Migrations don't appear to respect Doctrine::ATTR_TBLNAME_FORMAT when creating or dropping tables. This means while models create/drop tables with prefixes migrations don't. Also the migration_version table is created without the prefix too even though it was apparently fixed in DC-245.

I haven't tested but it also probably means other attributes like Doctrine::ATTR_IDXNAME_FORMAT and Doctrine::ATTR_SEQNAME_FORMAT are not obeyed either which makes things a little confusing knowing when to care for prefixes or not.



 Comments   
Comment by Erik Wegner [ 28/May/10 ]

Simple patch to set the table name inside constructor





[DC-386] Doctrine_Hydrator_ArrayDriver may segfault Php when loaded by Zend Framework Autoloader Created: 24/Dec/09  Updated: 24/Dec/09

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

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

Ubuntu 9.04 fully updated with Apache 2.2.11, Php 5.2.6, Zend Framework 1.9.6, Doctrine 1.2.1


Attachments: File Doctrine.php     File doctrine_trace.txt.xt     File TestingController.php    

 Description   

Apache and Php segfault with no error information in the logs and a white screen of death when I use Doctrine 1.2.1 in a Zend Framework controller.

I've traced the problem to line 126 of Zend/Loader/Autoloader.php which only seemed to occur when it autoloaded Doctrine_Hydrator_ArrayDriver during a call to save() in the controller.

I debugged with xdebug and have attached a simple test controller with no other code. The ZF page works fine when all Doctrine is commented out and a Doctrine test page with the same code but outside of ZF worked fine via Apache as did a CLI script.

Workaround is to not push Doctrine to Zend Loader in the bootstrap.

Here is the debug output just before a segfault, the stack and the variable values:

Remote Launch (stepping)
Library/Zend/Loader/Autoloader.php.Zend_Loader_Autoloader::autoload : lineno 126
Library/Zend/Loader/Autoloader.php.is_subclass_of : lineno 0
Library/Doctrine/Query.php.Doctrine_Query->processPendingFields : lineno 477
Library/Doctrine/Query.php.Doctrine_Query->buildSqlQuery : lineno 1213
Library/Doctrine/Query.php.Doctrine_Query->getSqlQuery : lineno 1122
Library/Doctrine/Query/Abstract.php.Doctrine_Query_Abstract->_getDqlCallbackComponents : lineno 1137
Library/Doctrine/Query/Abstract.php.Doctrine_Query_Abstract->_preQuery : lineno 1106
Library/Doctrine/Query/Abstract.php.Doctrine_Query_Abstract->execute : lineno 1001
Library/Doctrine/Template/Listener/Sluggable.php.Doctrine_Template_Listener_Sluggable->getUniqueSlug : lineno 207
Library/Doctrine/Template/Listener/Sluggable.php.Doctrine_Template_Listener_Sluggable->buildSlugFromFields : lineno 120
Library/Doctrine/Template/Listener/Sluggable.php.Doctrine_Template_Listener_Sluggable->preInsert : lineno 65
Library/Doctrine/Record/Listener/Chain.php.Doctrine_Record_Listener_Chain->preInsert : lineno 342
Library/Doctrine/Record.php.Doctrine_Record->invokeSaveHooks : lineno 355
Library/Doctrine/Connection/UnitOfWork.php.Doctrine_Connection_UnitOfWork->insert : lineno 551
Library/Doctrine/Connection/UnitOfWork.php.Doctrine_Connection_UnitOfWork->saveGraph : lineno 81
Library/Doctrine/Record.php.Doctrine_Record->save : lineno 1691
Application/controllers/TestingController.php.TestingController->indexAction : lineno 20
Library/Zend/Controller/Action.php.Zend_Controller_Action->dispatch : lineno 513
Library/Zend/Controller/Dispatcher/Standard.php.Zend_Controller_Dispatcher_Standard->dispatch : lineno 289
Library/Zend/Controller/Front.php.Zend_Controller_Front->dispatch : lineno 946
Library/Zend/Application/Bootstrap/Bootstrap.php.Zend_Application_Bootstrap_Bootstrap->run : lineno 77
Application/Bootstrap.php.Bootstrap->run : lineno 52
Library/Zend/Application.php.Zend_Application->run : lineno 346
Public/index.php.

{main}

: lineno 26

=====-=

$class Doctrine_Hydrator_ArrayDriver
$object Zend_Loader_Autoloader
_autoloaders Array [1]
0 Array [2]
0 Doctrine
1 autoload
_defaultAutoloader Array [2]
0 Zend_Loader
1 loadClass
_fallbackAutoloader false
_internalAutoloader Array [2]
0 Zend_Loader_Autoloader
1 _autoload
_namespaces Array [5]
Zend_ true
ZendX_ true
Lisantra_ true
Persistence_ true
Doctrine_ true
_namespaceAutoloaders Array [1]
Array [1]
0 Array [2]
0 Doctrine
1 autoload
_suppressNotFoundWarnings false
$self Zend_Loader_Autoloader
_autoloaders Array [1]
0 Array [2]
0 Doctrine
1 autoload
_defaultAutoloader Array [2]
0 Zend_Loader
1 loadClass
_fallbackAutoloader false
_internalAutoloader Array [2]
0 Zend_Loader_Autoloader
1 _autoload
_namespaces Array [5]
Zend_ true
ZendX_ true
Lisantra_ true
Persistence_ true
Doctrine_ true
_namespaceAutoloaders Array [1]
Array [1]
0 Array [2]
0 Doctrine
1 autoload
_suppressNotFoundWarnings false
$method _autoload
$autoloader Array [0]






[DC-387] mssql fails on find($key) Created: 25/Dec/09  Updated: 05/Jan/10

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

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


 Description   

Doctrine_Core::getTable('Project')->find($id)
this kind of expression produces query like "SELECT TOP 1 [inner_tbl].[id] AS [p__id] FROM (SELECT TOP 1 [p].[id] AS [p__id], [p].[name] AS [p__name], [p].[description] AS [p__description] FROM [project] [p] WHERE ([p].[id] = ?)) AS [inner_tbl]"
which fails because there is no [inner_tbl].[id]



 Comments   
Comment by Michael Card [ 05/Jan/10 ]

Close as duplicate of DC-289





[DC-388] Conservative loading not working Created: 26/Dec/09  Updated: 27/Jan/10

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

Type: Bug Priority: Major
Reporter: Karma Dordrak (Drak) Assignee: Benjamin Eberlei
Resolution: Unresolved Votes: 1
Labels: None
Environment:

Apache 2, MySQL 5.1, PHP 5.2.9, Debian 5



 Description   

Apparently, when setting Doctrine::MODEL_LOADING_CONSERVATIVE things like Doctrine_Core::createTablesFromModels() don't work. Have to enable aggressive model loading. This has been confirmed on the doctrine-user mailing list.

I took a brief look at the code: I may be missing something but it appears there may be a logic difference in the conservative vs. aggressive model loading method. Aggressive loading uses require_once on all files in the model directory and tries to determine the name of the class inside the file (by doing a difference on the loaded classes). This logic makes sense since the class and file name do not have to match.

However, conservative loading just tries to calculate the class name and store it in an array for later loading by the autoloader. This means there is a huge logic difference in behaviour between these two loading methods since the model class files actually must differ depending on case (specifically, the model class file name must follow a specific format to match the actual class name) otherwise the autoload array will never know the correct name of the class.

I would also like to comment that overall, require_once is a poor choice for performance reasons, it's vastly slower than include_once, but overall the logic should better be adjusted to use plain include (if possible), for performance reasons.






[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-390] doctrine_cache_keys bigger than 1mb Created: 30/Dec/09  Updated: 27/Jan/10

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

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

Issue Links:
Reference
is referenced by DC-460 Doctrine_Cache_Apc/Core changes in 1.... Closed

 Description   

When multiple projects using doctrine use the same memcached server the doctrine_cache_keys can get bigger then 1mb and php will be throwing warnings telling that the data is too big to be stored by memcached.

I am currently using a workaround, having 1 doctrine_cache_keys per application, on the file Cache/Driver.php i added the following line to the constructor

$this->_cacheKeyIndexKey = 'doctrine_cache_keys_' . md5(Doctrine_Manager::getInstance()->getCurrentConnection()->getOption('dsn'));

but if an application uses more than 1mb en keys then the notice will rise again.



 Comments   
Comment by circlechu [ 13/Jan/10 ]

Why doctrine need to save the keys when it is timeout? I found doctrine will hold the duplicated keys in doctrine_cache_keys map. So this is why it will become more and more bigger. So I think if I remove those duplicated key it will be better? Here is my solution
I add array_unique function to remove all duplicated keys in the map. This method is in the Doctrine_Cache_Driver class.

/**

  • Save a cache key in the index of cache keys
    *
  • @param string $key
  • @return boolean True if successful and false if something went wrong.
    */
    protected function _saveKey($key) { $keys = $this->fetch($this->_cacheKeyIndexKey); $keys[] = $key; $keys=array_unique ($keys); return $this->save($this->_cacheKeyIndexKey, $keys, null, false); }




[DC-392] Let the parser ignore .* (hidden) files Created: 02/Jan/10  Updated: 08/Jun/10

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

Type: Improvement Priority: Major
Reporter: Alessandro Vermeulen Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

When generating models from yml files starting with a `.' such as temporary files from certain editors and meta files from OS X are also parsed by the importer. I do not see any reasons too include these hidden files in parsing as they are hidden for a purpose. And there would be no point in deliberately using hidden files for your config files.

Also see:
http://blog.rajatpandit.com/2009/08/23/doctrine_parser_exception-fail-some-error-message/
and
http://alessandrovermeulen.me/2010/01/01/doctrine-unable-to-parse-string-unable-to-parse-line-0/



 Comments   
Comment by Alessandro Vermeulen [ 02/Jan/10 ]

Added affected versions.

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

We can include this fix in 1.2.3, does anyone have a patch? If not I'll try and hunt down the offending code and patch it. Not sure where it is off the top of my head anymore





[DC-396] Add timezone support for time and timestamp datatype in PostgreSQL Created: 05/Jan/10  Updated: 19/Aug/12

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

Type: New Feature Priority: Major
Reporter: Vladislav Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None

Attachments: File timestampable.diff    

 Description   

Please add support for the types of time with timezone and timestamp with timezone in the Doctrine when using PostgreSQL.



 Comments   
Comment by Alex Potter [ 19/Aug/12 ]

I came across this problem because I prefer to store timezone information instead of local dates.

I believe this is resolved by the attached patch, which patches the Timestampable template and it's listener to create and maintain 'timestamp with timezone' in Postgresql.





[DC-400] bit(1) columns are broken Created: 06/Jan/10  Updated: 11/Apr/11

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

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

Ubuntu 9.10 php 5.2 mysql 5.1, all installed with ubuntu's apt



 Description   

Ihave the following Doctrine schema:


TestTable:
columns:
bitty: bit(1)

I have created the database and table for this. I then have the following PHP code:

$obj1 = new TestTable();
$obj1['bitty'] = b'0';
$obj1->save();

$obj2 = new TestTable();
$obj2['bitty'] = 0;
$obj2->save();

Clearly my attempt is to save the bit value 0 in the bitty column.

However after running this PHP code I get the following odd results:

mysql> select * from test_table;
---------+

id bitty

---------+

1  
2  

---------+
2 rows in set (0.00 sec)

mysql> select * from test_table where bitty = 1;
---------+

id bitty

---------+

1  
2  

--------+
2 rows in set (0.00 sec)

mysql> select * from test_table where bitty = 0;
Empty set (0.00 sec)

Those boxes are the 0x01 character, i.e. Doctrine has set the value to 1, not 0.

However I can insert 0's into that table direct from MySQL:

mysql> insert into test_table values (4, b'0');
Query OK, 1 row affected (0.00 sec)

mysql> select * from test_table where bitty = 0;
---------+

id bitty

---------+

4  

---------+
1 row in set (0.00 sec)

See also this question on StackOverflow http://stackoverflow.com/questions/2008021/php-doctrine-orm-not-able-to-handle-bit1-types-correctly






[DC-401] Doctrine_Query->load crashes with additional ending whitespace in JOIN Created: 06/Jan/10  Updated: 06/Jan/10

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

Type: Bug Priority: Major
Reporter: Christian Michel Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

following will lead to an error:

->leftJoin('alias.RelatedTable alias2 WITH .....')

The problem is the additional whitespace behind alias2.
On line 1682 in Doctrine_Query class file:

$tmp = explode(' ', $path);

will create an array of 3 elements where the last one is empty but will be used as empty alias mapping after foreach from line 1698.






[DC-402] aliased fields from root class are not recognized als root class fields, if they're the only one Created: 06/Jan/10  Updated: 06/Jan/10

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

Type: Bug Priority: Major
Reporter: Christian Michel Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

If all selected fields from the root class are aliased,
Doctrine_Query->processPendingFields() won't recognize them as fields of the table and the following exception will be thrown:
"The root class of the query (alias c) must have at least one field selected."

In my real world example, this could only be fixed, using the primary key of the root class/table in select






[DC-403] Eliminate queries produced by Doctrine_Node_NestedSet::getDescendants() when possible Created: 06/Jan/10  Updated: 16/Apr/10

Status: Open
Project: Doctrine 1
Component/s: Nested Set
Affects Version/s: 1.2.1
Fix Version/s: 1.2.0

Type: Improvement Priority: Major
Reporter: alex Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 2
Labels: None


 Description   

How to reproduce

  1. fetch a tree with nested set
    $root = Doctrine::getTable($model)->getTree()->findRoot($rootId);
    $treeObject= Doctrine::getTable($model)->getTree()->fetchTree($root->getId()); 
    
  2. issue
    $root->getNode()->getChildren();
    
    or there will be a total query mess in a lambda function with a loop getChildren().
    ...
    <?php foreach($root->getChildren() as $child): ?>
       ....
    <?php endforeach; ?>
    ...
    
    

Problem is described more verbosely here – http://codeutopia.net/blog/2008/08/30/understanding-doctrines-nestedset-feature/

What behavior is expected

An already fetched record instance is returned, without calling database and without causing query flooding.

Like in propel.

In propel if you are calling ....::retrieveTree($id) it returns the root
with completed, pooled (cached) and linked tree.

What happens

An additional query is issued

This is a big slip in architecture of Doctrine`s nested set implementation.






[DC-412] Error defining "unique" constraint in a translated (i18n) column Created: 09/Jan/10  Updated: 10/Jan/10

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

Type: Bug Priority: Major
Reporter: David Marín Carreño Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 1
Labels: None


 Description   

Let's suppose we have a class "Element" with columns "name" and "description".

We want to set an "unique" constraint in column "name", and set the I18n behavior to columns name and description.

In the generated translation table "element_translation", doctrine sets an unique constraint in the column "name". This is an error, as various languages could translate that string in the same way. I think that the "unique" constraint should be set to the combination of columns "name" and "lang", so the restriction applies for a given language.






[DC-417] Unexpected results with equal many-to-many relations Created: 11/Jan/10  Updated: 14/Jan/10

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

Type: Bug Priority: Major
Reporter: Ivo Võsa Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

PHP 5.2.10-2ubuntu6.3 with Suhosin-Patch 0.9.7 (cli) (built: Nov 26 2009 14:52:57)
MySQL 5.0.84-0.dotdeb.0
Doctrine-1.1.6-Sandbox



 Description   

print_r's before refresh represent what i hoped to get and after that what was inserted into db.

INSERT INTO match_reference (match_id, user_id) VALUES (?, ?)
Array
(
    [0] => 2
    [1] => 1
)


UPDATE match_reference SET match_id = ? WHERE user_id = ? AND match_id = ?
Array
(
    [0] => 1
    [1] => 1
    [2] => 2
)


INSERT INTO match_reference (match_id, user_id) VALUES (?, ?)
Array
(
    [0] => 3
    [1] => 2
)


INSERT INTO match_reference (match_id, user_id) VALUES (?, ?)
Array
(
    [0] => 4
    [1] => 2
)
Array
(
    [0] => Array
        (
            [id] => 2
            [username] => 2
        )

)
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => 1
        )

    [1] => Array
        (
            [id] => 3
            [username] => 3
        )

    [2] => Array
        (
            [id] => 4
            [username] => 4
        )

)
Array
(
)
Array
(
    [0] => Array
        (
            [id] => 3
            [username] => 3
        )

    [1] => Array
        (
            [id] => 4
            [username] => 4
        )

)

schema/schema.yml

---
User:
  columns:
    username: string(255)
  relations:
    Matches:
      class: User
      local: user_id
      foreign: match_id
      refClass: MatchReference
      equal: true
      cascade: [delete]

MatchReference:
  columns:
    user_id:
      type: integer
      primary: true
    match_id:
      type: integer
      primary: true

index.php

require_once('config.php');

Doctrine::loadModels('models');

Doctrine_Query::create()
    ->delete('User')
    ->execute();

Doctrine_Query::create()
    ->delete('MatchReference')
    ->execute();

$u1 = new User();
$u1->id = $u1->username = 1;
$u1->save();

$u2 = new User();
$u2->id = $u2->username = 2;
$u2->save();

$u3 = new User();
$u3->id = $u3->username = 3;
$u3->save();

$u4 = new User();
$u4->id = $u4->username = 4;
$u4->save();

$profiler = new Doctrine_Connection_Profiler();
Doctrine_Manager::getInstance()->getCurrentConnection()->addListener($profiler);

$user_1 = Doctrine::getTable('User')->find(1);

$matches = Doctrine_Query::create()
    ->from('User')
    ->whereIn('id', array(2))
    ->execute(array(), Doctrine::HYDRATE_ARRAY);

$match = $matches[0];

$user_1->link('Matches', array($match['id']));
$user_1->save();

$user_2 = Doctrine::getTable('User')->find(2);

$matches = Doctrine_Query::create()
->from('User')
->whereIn('id', array(3, 4))
->execute(array(), Doctrine::HYDRATE_ARRAY);

foreach ($matches as $match) {
    $user_2->link('Matches', array($match['id']));
}

$user_2->save();

foreach ($profiler as $event) {
    if (in_array($event->getName(), array('execute')) && preg_match('/^(INSERT|UPDATE)/', $event->getQuery())) {
        echo print_r($event->getQuery(), true) . "\n";
        echo print_r($event->getParams(), true) . "\n\n";
    }
}

print_r($user_1->Matches->toArray());
print_r($user_2->Matches->toArray());

$user_1->refresh(true);
$user_2->refresh(true);

print_r($user_1->Matches->toArray());
print_r($user_2->Matches->toArray());



 Comments   
Comment by Ivo Võsa [ 11/Jan/10 ]

Just tested it on 1.2.1 with same results.





[DC-424] using boolean logic in select don't work Created: 14/Jan/10  Updated: 27/Jan/10

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

Type: Bug Priority: Major
Reporter: Ivo Võsa Assignee: Guilherme Blanco
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Continuing with same setup as in http://www.doctrine-project.org/jira/browse/DC-417
I discovered another issue

$result = Doctrine_Query::create()
    ->select('u.*, m.*, COUNT(m.id) > 0 AS match_check')
    ->from('User u')
    ->leftJoin('u.Matches m')
    ->groupBy('u.id')
    ->orderBy('match_check DESC, RAND()')
    ->execute(array(), Doctrine::HYDRATE_ARRAY);

match_check will actually be count of matches not 0 or 1 as i expected.
is it bug or feature?



 Comments   
Comment by Guilherme Blanco [ 14/Jan/10 ]

SelectExpressions cannot contain ComparisonExpressions.

That's a limitation of Doctrine 1, which was resolved in Doctrine 2.

Cheers,

Comment by Josh Boyd [ 27/Jan/10 ]

Something like this will work:

$result = Doctrine_Query::create()
    ->select('u.*, m.*)
    ->addSelect("QUOTE(IF(COUNT(m.id) > 0),1,0)) match_check')
    ->from('User u')
    ->leftJoin('u.Matches m')
    ->groupBy('u.id')
    ->orderBy('match_check DESC, RAND()')
    ->execute(array(), Doctrine::HYDRATE_ARRAY);




[DC-426] Doctrine incorrectly assigns a NULL value to primary key fields Created: 14/Jan/10  Updated: 14/Jan/10

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

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


 Description   

Hi,

in my project (MySQL 5.x, PHP 5.2.x), I use a combined primary key which looks as follows:

$this->hasColumn("guid", "string", 32, array('primary' => true));
$this->hasColumn("revision", "integer", 4, array('primary' => true));
$this->hasColumn("language", "string", 32, array('primary' => true));

My project automatically initializes the GUID and revision fields, but language is left empty. Doctrine assumes that NULL is a good value, and uses the NULL value after saving an object to reload it. This results in the following statement, generated by the find()-Method within Table.php:

SELECT b.guid AS b_guid, b.revision AS brevision, b.language AS blanguage, b.active AS bactive, b.title AS btitle, b.content AS bcontent, b.category AS b_category FROM blog_entry b WHERE (b.guid = '505f1a2d13864fa4aef461aa1b5b37a3' AND b.revision = '1' AND b.language = NULL)

Since MySQL does not allow NULL values in primary keys, MySQL uses an empty string (''). Doctrine should also use an empty string as default value if the primary key consists of a string, OR issue a warning that MySQL does not allow NULL values in primary keys. The problem with this "bug" is that problems occur in situations where you do not expect them, for example, when storing objects.

If a test case is required, just tell me and I'll prepare one.

Thanks and best regards,
Timo






[DC-427] Record Hydration error Created: 14/Jan/10  Updated: 14/Jan/10

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

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

Ubuntu 9.04
Apache 2.2.9
PHP 5.2.6-3ubuntu4.2 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 21 2009 19:14:44)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
with Xdebug v2.0.3, Copyright (c) 2002-2007, by Derick Rethans
MySQL 5.0.75-0ubuntu10.2 (Ubuntu)
Symfony 1.4.1



 Description   

schema.yml

CheCategory:
options:
collate: utf8_unicode_ci
charset: utf8
actAs:
Timestampable: ~
NestedSet: ~
columns:
name:
type: string(255)
CheItem:
options:
collate: utf8_unicode_ci
charset: utf8
actAs:
Timestampable: ~
columns:
name:
type: string(255)
category_id:
type: integer(12)
relations:
CheItemPhoto:
type: many
local: id
foreign: item_id
CheItemAttribute:
type: many
local: id
foreign: item_id
CheCategory:
local: category_id
foreign: id

CheAttribute:
options:
collate: utf8_unicode_ci
charset: utf8
columns:
name:
type: string(255)
attr_type:
type: integer(2)
label:
type: string(255)
sort_order:
type: integer(5)
default: 9999
relations:
CheItemAttribute:
local: id
foreign: attribute_id

CheItemAttribute:
options:
collate: utf8_unicode_ci
charset: utf8
columns:
item_id:
type: integer(12)
attr_value:
type: clob
attribute_id:
type: integer(12)
relations:
CheItem:
local: item_id
foreign: id
CheAttribute:
local: attribute_id
foreign: id

CheItemPhoto:
options:
collate: utf8_unicode_ci
charset: utf8
actAs:
Timestampable: ~
columns:
item_id:
type: integer(12)
basefile:
type: string(255)
caption:
type: string(255)
is_default:
type: boolean
default: false
relations:
CheItem:
local: item_id
foreign: id

fixtures.yml

CheAttribute:
Attr_price:
name: Price
label: price
sort_order: 1
attr_type: <?php echo CheAttribute::ATTR_STRING."\n" ?>
Attr_desc:
name: Desc
label: desc
sort_order: 2
attr_type: <?php echo CheAttribute::ATTR_HTML."\n" ?>

CheCategory:
Cat_0:
name: Items category
children:
Cat_1:
name: Cups
children:
Cat_2:
name: Beer
Cat_3:
name: Tea
children:
Cat_5:
name: China
Cat_6:
name: Russian
Cat_4:
name: Coffee

CheItem:
Item_8:
name: Vobla
CheCategory: Cat_1
Item_1:
name: Vobla2
CheCategory: Cat_2

CheItemAttribute:
Ite_attr_0:
CheItem: Item_1
CheAttribute: Attr_price
attr_value: 10
Ite_attr_1:
CheItem: Item_1
CheAttribute: Attr_desc
attr_value: abcsdd
Ite_attr_2:
CheItem: Item_8
CheAttribute: Attr_price
attr_value: 123
Ite_attr_3:
CheItem: Item_8
CheAttribute: Attr_desc
attr_value: test

code:

$b = Doctrine::getTable("CheAttribute")>createQuery("A2")>leftJoin("A2.CheItemAttribute IA2 WITH IA2.item_id = ?", 2)>addOrderBy("A2.sort_order ASC")>execute();

var_dump($b[0]>getCheItemAttribute()>getAttrValue());

$tb = Doctrine::getTable("CheAttribute")>createQuery("A")>leftJoin("A.CheItemAttribute IA WITH IA.item_id = ?", 1)>addOrderBy("A.sort_order ASC")>execute();

var_dump($tb[0]>getCheItemAttribute()>getAttrValue());
exit();

in browser i see:

string '10' (length=2)

string '10' (length=2)

but expected:

10

123

With hydration Array & Scalar hydrated data is ok.






[DC-430] I18n and inheritance Created: 15/Jan/10  Updated: 15/Jan/10

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

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

Doctrine 1.2 with Symfony 1.4



 Description   

When using i18n with inheritance, the localizables fields are overrinden by the second deriving class.
So, the translation table is containing only fields from one of the two descending classes.

The yml is below:

User:
columns:
email: string(255)
...

Employer:
inheritance:
extends: User
type: column_aggregation
actAs:
I18n:
fields: [description, company]
columns:
company: string(255)
description: text

Recruiter:
actAs:
I18n:
fields: [position]
inheritance:
extends: User
type: column_aggregation
columns:
position: string(255)






[DC-432] ::isValidType fails when input format is different from php default format Created: 15/Jan/10  Updated: 08/Jun/10

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

Type: Bug Priority: Major
Reporter: Jón Ragnarsson Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Windows XP (XAMPP Apache) & Linux


Attachments: File Validator.php    

 Description   

In Validator::isValidType():
return (string)$var == strval(floatval($var));

floatval($var) returns only the integer part if the decimal character is anything other than ".".
Therefore this evaluation fails.

I've added a small function 'ParseFloat' which takes locale settings into consideration.
There might be a better solution.



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

Can you provide the changes as patch?





[DC-436]  Change in 1.2 to Doctrine_Event::skipOperation() functionality Created: 18/Jan/10  Updated: 10/Feb/10

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

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

Debian



 Description   

I have been using Doctrine 1.1.6.

I have two related models, which are always saved together. In my application, save is called on class A and that save cascades to class B. I have a save listener which in some cases can intercept class A's save operation and call Doctrine_Event::skipOperation() to prevent class A from being persistently saved. However, in such cases, class B is still saved - the skipOperation() does not skip the entire operation, just class A's save operation, allowing subsequent operations to occur as normal.

This is the desired functionality and has been working fine. However, I have just upgraded to 1.2.1. only to find that something has changed, causing the skipOperation() to skip the entire operation, therefore not saving class B when class A's listener interferes.

I presume this is a bug. If not, what precisely has changed with skipOperation(), and how can I keep the traditional functionality?






[DC-438] Nesting Taggable and I18N Created: 19/Jan/10  Updated: 19/Jan/10

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

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

PHP 5.2.6, MySQL 5.0.75, Symfony 1.3.1



 Description   

The Taggable extension doesnt work correctly when nested under I18N.
The page_translation_taggable_tag table appears to be correctly created, it has 3 columns: id, lang, tag_id
But when you save a tag like this
$page->Translation['en']->setTags('tag 1, tag2');
the lang column in page_translation_taggable_tag is empty
and this doesnt work either:
$page->setTags('tag 1, tag2');

Schema is this:
Page:
actAs:
I18n:
fields: [title, contents]
actAs:
Taggable: ~
columns:
title:

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

contents: clob






[DC-440] doctrine migration fails with taggable extension Created: 20/Jan/10  Updated: 22/Jan/10

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

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

osx 10.6, apache 2, php 5.3, symfony 1.4



 Description   

When adding the Taggable behaviour to an entity, the doctrine migration fails (i'm using the symfony task) with the follwing error:

>> doctrine Migrating from version 0 to 1

The following errors occurred:

  • SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails. Failing Query: "DROP TABLE taggable_tag"

I have a single entity in my schema, with the Taggable behavior attached:

Article:
actAs:
Taggable: ~ 
columns:
title:

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

body:

{ type: clob }

The Version1 class which was generate by the generate-migrations-diff task looks like this:

<?php
/**

  • This class has been auto-generated by the Doctrine ORM Framework
    */
    class Version1 extends Doctrine_Migration_Base
    {
    public function up() { $this->dropTable('taggable_tag'); }

public function down()

{ $this->createTable('taggable_tag', array( 'id' => array( 'type' => 'integer', 'length' => '8', 'autoincrement' => '1', 'primary' => '1', ), 'name' => array( 'unique' => '1', 'type' => 'string', 'length' => '255', ), ), array( 'type' => '', 'indexes' => array( ), 'primary' => array( 0 => 'id', ), 'collate' => '', 'charset' => '', )); }

}



 Comments   
Comment by Robert Gruendler [ 22/Jan/10 ]

i think i found the reason for this. The sfDoctrineGenerateMigrationsDiffTask seems to build it's diff from yml schema files:

protected function execute()....

$this->callDoctrineCli('generate-migrations-diff', array(
'yaml_schema_path' => $this->prepareSchemaFile($config['yaml_schema_path']),
));

The task does not know anything about the models in the doctrine_extensions folder, and there are no yaml files for their
schema, so symfony migration tasks won't work with extensions.

It would be great if this would be mentioned somewhere in the docs of the extensions.





[DC-442] Refined definition of relations regarding "copy()" cloning behaviour Created: 21/Jan/10  Updated: 10/Feb/10

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

Type: New Feature Priority: Major
Reporter: Raphael Schumacher Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None


 Description   

Doctrine's cloning feature is based on the Doctrine_Record::copy($deep = false) method, while the $deep param says whether to clone the related objects as well, or not.

However, considering the perspective of the application logic, the functional need can also be stated as: "I wish you to clone yourself, expecting you to know yourself which related objects you need to clone as well, or even to de-reference, or whatever is needed (e.g. to remove the relation)."
For this, the $deep argument is somehow inaccurate, as it does not take into consideration the different meanings of the relations:

  • some relations (namely aggregations in UML terminology) need that the cloned object shall still refer to the same object (like referenced by the cloned object)
  • some relations (namely compositions) need to clone the related objects as well, as the latter are owned by the main object.

Practical example: when cloning an invoice (Doctrine_Record), application logic expects that its invoice line items be cloned as well (compositions), but not the reference to the customer (cloning my customers this way will not increase my business .

Thus it would be great if there were a means to specify the needed behaviour in the schema.yml etc.
Thinkable approach: extend the "application-level cascade" feature of Doctrine by adding a "clone" or "copy" parameters. Then the copy() method in Doctrine_Record will know which related objects to clone as well, or not, or to clear (null). I guess it's quite analogous to the "delete" cascade stuff.

So far my proposal. In case it will find support, I will then be happy to provide an implementation proposal.






[DC-443] Incorrect insert order in i18n entities Created: 22/Jan/10  Updated: 22/Jan/10

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

Type: Bug Priority: Major
Reporter: Rodrigo Borrego Bernabé Assignee: Jonathan H. Wage
Resolution: Unresolved Votes: 0
Labels: None
Environment:

Linux (2.6.21 kernel)
Apache/2.2.6
PHP 5.2.6
symfony version 1.4.1
doctrine 1.2


Attachments: File i18nrelation_problem.tgz    

 Description   

If the schema has an entity MyMain with all its fields i18n and an entity MySecondary related to MyMain and you try to create a new MySecondary item using Symfony forms you get an error.

I think the error is doctrine and in i18n because if you remove a field from the i18n behavior (fields: [a,b,c,d], for example) all works ok.
I've included a symfony project to help developpers replicate the error.

My Schema

 
MyMain:
  actAs:
    I18n:
      fields: [a,b,c,d, e]
  columns:
    a:  { type: string(255), notnull: true }
    b:  { type: string(255), notnull: true }
    c:  string
    d:  string
    e:  string

MySecondary:
  columns:
    my_main_id:  integer
    a:        string(255)
    b:        string(255)
  relations:
    MyMain:
      local: my_main_id
      foreign: id
      foreignType: one
      cascade: [delete]

And the form code

class MyMainForm extends BaseMyMainForm
{
  public function configure()
  {
    $this->embedI18n(array('en', 'es'));
  }
}

class MySecondaryForm extends BaseMySecondaryForm
{
  public function configure()
  {
    $this->widgetSchema['my_main_id'] = new sfWidgetFormInputHidden();
    $this->embedRelation('MyMain as main_subform');
  }
}

And last the queries (and its order when you get the error)

INSERT INTO my_secondary (my_main_id, a, b) VALUES (?, ?, ?) - (, my_secondary[a], my_secondary[b])
INSERT INTO my_main_translation (id, lang, a, b, c, d, e) VALUES (?, ?, ?, ?, ?, ?, ?) - 
  (, en, my_secondary[main_subform][en][a], my_secondary[main_subform][en][b], my_secondary[main_subform][en][c], 
   my_secondary[main_subform][en][d], my_secondary[main_subform][en][e])
Error Doctrine_Connection_Mysql_Exception	SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null 





[DC-447] Problem linking many-to-many relationships Created: 25/Jan/10  Updated: 25/Jan/10

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

Type: Bug Priority: Major
Reporter: Rytis Daugirdas