Capturing the SQL Generated by CFQUERY
Posted At : January 20, 2009 9:40 PM | Posted By : Bob Silverberg
Related Categories: ColdFusion
Have you ever wanted to capture the SQL that was generated by a CFQUERY? It's pretty well known that you can see the SQL if you do a CFDUMP on your query result, but what if you want to capture it programmatically? Maybe you want to display it on a page, or log it, or compare it to an expected value.
Well, we can accomplish this feat using the query's underlying coldfusion.sql.QueryTable object. Here's an example:
2 SELECT myId FROM myTable
3</cfquery>
4
5<cfoutput>
6The SQL generated is: #qryTest.getMetaData().getExtendedMetaData().sql#
7</cfoutput>
Obviously in the above example we don't need to capture the generated SQL as it's hardcoded inside the CFQUERY tag. But what if we're generating our SQL statement dynamically? What if we're using an ORM that generates queries for us?
As well, if we're using CFQUERYPARAM (and who isn't?), we can also get a structure of the parameter values passed into the query using qryTest.getMetaData().getExtendedMetaData().sqlparameters.
Cool, eh?
<cfquery datasource="myDSN" name="qryTest" result="my_query_result">
SELECT myId FROM myTable
</cfquery>
<cfoutput>my_query_result.sql</cfoutput>
This is also handy if your CFQUERY is buried in your model, but you're trying to debug a view. It's much easier to just add the single line of code into the view that makes use of the query object, than digging into the model and changing the CFQUERY tag.
One last note: I mispoke when I said that sqlparameters returns a structure. It actually returns an array ;-)
query.getSQL().toString()
This returns the sql statement with ? replaced by their values.
If you need access to the parameters, you can call:
query.getSQL().getItems()
which returns an array. You can then call getValueForCF() on each of the items to get the value.
thank you so much for posting this! I was having problem with serialzejson crashing if a query contain a binary column. Your information enable me to find a work around.
@jeroen
thanks for posting how to do this with railo :)
you all rock!
Paul Alkema