Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine - how to get the SQL INSERT query, in the postSave() event?

I would like to get the exact SQL INSERT query that Doctrine generates when an object's save() method is called.

Preferably, I would like to get it in the postSave() event of the model and log it in a txt file.

For instance:

<?php 
$user = new User(); // A Doctrine Model with timestampable behavior enabled
$user->first_name = 'Manny';
$user->last_name = 'Calavera';
$user->save();
?>

I want to get/log the following SQL query:

INSERT INTO user (first_name, last_name, created_at, updated_at) VALUES ('Manny', 'Calavera', '2010-08-03 12:00:00', '2010-08-03 12:00:00');

The background for needing this, is that I wish to mass-import later the data by parsing the txt file.

like image 941
aletzo Avatar asked Aug 03 '10 10:08

aletzo


2 Answers

I don't think there is any easy way to do this since the behaviour of save() varies depending on a few different things (if you're inserting/updating).

If you had created a doctrine query object, then you can call the getSqlQuery() method like this:

$q = Doctrine_Query::create()
->select('u.id')
->from('User u');

echo $q->getSqlQuery();

but the save() is a method, not an object so this won't work. I think you'll have to hack in some code to detect whether you're inserting or updating and build a query to log on the fly and then use save().

I know this suggestion is not ideal because it is not logging 'exactly' what save() is doing but for the purposes you stated it should still work just as well.

like image 88
Evernoob Avatar answered Oct 02 '22 22:10

Evernoob


Why don't you try to see how the symfony developers do it? Check their WebDebug Toolbar for Doctrine here. The WebDebug Toolbar outputs all query that you do on a page.

There's a hook on DoctrineEvent, and I think you can modify the code to do what you want. Check the getDoctrineEvents and getSqlLogs method.

Hope this helps. If you need further explanation, please write it in comment, I'll try my best to explain.

like image 21
bertzzie Avatar answered Oct 02 '22 23:10

bertzzie