ColdFusion, PreserveSingleQuotes(), And Array Values

I think I may have stumbled upon some odd, unexpected and (definitely) undesired behavior with ColdFusion. The application that I’m working on has a module which needs to create a bit of dynamic SQL. Not a problem here, as I step through my conditions I’m populating an array that I can later loop through to generate the statement. The problem comes when I loop through the array to output it’s values as part of my query.

For the example, here is a small example of what I’m trying to do:


<!--- 

PreserveSingleQuotes Array Example 

--->

<cfif Elizabeth_Banks = Super_Pretty><!--- Always True --->
<cfset ArrayAppend(variables.dynamic_query, "AND name = 'Elizabeth Banks')" />
</cfif>

<cfif Wolverine = Super_Awesome><!--- Always True --->
<cfset ArrayAppend(variables.dynamic_query, "AND name = 'Wolverine')" />
</cfif>

<cftry>

<cfquery name="QUERY_NAME" datasource="datasource">
	SELECT * FROM super_stuff
	WHERE 0 = 0
	<cfloop from="1" to="#ArrayLen(variables.dynamic_query)#" index="i">
		#PreserveSingleQuotes(variables.dynamic_query[i])#
	</cfloop>
</cfquery>

<cfcatch>
	<cfdump var="#cfcatch#" label="Error Catch Data" />
</cfcatch>

</cftry>

If we step through the code above, it should be expected that I would end up executing a query that looks like this:


/*
 DESIRED SQL
*/
	SELECT * FROM super_stuff
	WHERE 0 = 0
	AND name = 'Elizabeth Banks'
	AND name = 'Wolverine'

But that doesn’t happen. Actually, nothing happens. ColdFusion throws an error. The parser ends up choking on the array element within the PreserveSingleQuotes() method. I can’t seem to find a rhyme or reason as to the cause of this is happening so I’m left to find a work around.

ColdFusion will strip the single quotes out of my strings (causing another error via bad SQL) if I remove the PreserveSingleQuotes() method, so I’m left to correct this by somehow playing with the array. The fix I found was quick and dirty. Assigning a temporary variable the current array element’s value and then having PreserveSingleQuotes parse that value I seems keep ColdFusion happy. So now I’m left with:


<!--- 

PreserveSingleQuotes Array Example 

--->

<cfquery name="QUERY_NAME" datasource="datasource">
	SELECT * FROM super_stuff
	WHERE 0 = 0
	<cfloop from="1" to="#ArrayLen(variables.dynamic_query)#" index="i">
<!--- My Temp Variable --->
<cfset variables.temp_variable = variables.dynamic_query[i] />
		#PreserveSingleQuotes(variables.temp_variable)#
	</cfloop>
</cfquery>

<cfcatch>
	<cfdump var="#cfcatch#" label="Error Catch Data" />
</cfcatch>

</cftry>

I suppose I should be happy, because the work around produced the desired output, but I can’t help but not like this solution. It seems to me that internal Coldfusion methods should be more than capable of handling individual array elements. Unless I’m really just missing something here… any ideas?

Leave a Reply