I have some extremely complex queries that I need to use to generate a report in my application. I'm using symfony as my framework and doctrine as my ORM.
My question is this:
What is the best way to pass in highly-complex sql queries directly to Doctrine without converting them to the Doctrine Query Language? I've been reading about the Raw_SQL
extension but it appears that you still need to pass the query in sections (like from()
). Is there anything for just dumping in a bunch of raw sql commands?
Conclusion. Raw SQL is for sure the most powerful way to interact with your database as it is the databases native language. The drawback is that you might use features which are specific to that database, which makes a future database switch harder.
ORM is good only for developers and maintenance because most developers aren't very good at SQL, but if you're actually talking about performance, SQL completely trumps it.
An SQL injection security hole allows an attacker to execute new or modify existing SQL statements to access information that he is not allowed to access. Neither Doctrine DBAL nor ORM can prevent such attacks if you are careless as a developer.
$q = Doctrine_Manager::getInstance()->getCurrentConnection(); $result = $q->execute(" -- RAW SQL HERE -- ");
See the Doctrine API documentation for different execution methods.
Yes. You can get a database handle from Doctrine using the following code:
$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
and then execute your SQL as follows:
$query = "SELECT * FROM table WHERE param1 = :param1 AND param2 = :param2"; $stmt = $pdo->prepare($query); $params = array( "param1" => "value1", "param2" => "value2" ); $stmt->execute($params); $results = $stmt->fetchAll();
You can use bound variables as in the above example.
Note that Doctrine won't automatically hydrate your results nicely into record objects etc, so you'll need to deal with the results being returned as an array, consisting of one array per row returned (key-value as column-value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With