Friday, January 15, 2016

Debugging queries the dirty way

What if you have some hideously complex query generation code, and you're trying to figure out exactly what that query ends up looking like? Also, you can't just dump the query object to peek at the SQL property. (Perhaps it performs an update or some other non-select query; these will result in the query variable being undefined.)

There is, it turns out, a quick and only slightly dirty answer. Use an inner cfsavecontent. To take a vastly simplified example, suppose this query that is giving you trouble:

(Complicated query code has been omitted for demonstration purposes. Just imagine a twisting nether of ifs and function calls and who knows what else.)

You could pull the body out and stick it inside a cfsavecontent. This will work, but you'll also need manually remove every cfqueryparam, as these will crash when used outside a query. But, it turns out that you can safely use them inside a cfsavecontent as long as this is done within the cfquery.

So, wrap the body of the query in the cfsavecontent. Right after that, but still within the query, output the variable you saved the content to. Otherwise, the cfquery will crash because it has nothing to send. Once you're outside the cfquery, output that sql content again, wrapped in <pre> tags for easier reading, like so:

In this case, the output was:

 update D_customer
 set customername = ?
 where pkid = ?

Notice that the cfqueryparam tags were automatically converted into question marks, and the query runs just like it did before.

Notice also that I didn't adjust the indentation of my query when I wrapped cfsavecontent around it. The expectation is that you will remove this as soon as you figure out the problem. Do not leave this stuff in your code! Get in, solve the problem, and then get it out.

No comments:

Post a Comment