Created
January 4, 2011 01:44
-
-
Save erikvold/764276 to your computer and use it in GitHub Desktop.
A ColdFusion UDF to convert a query to a struct, or an array of structs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cffunction name="QueryToStruct" returntype="any" hint="Converts a query to a struct, or an array of structs"> | |
<cfargument name="query" type="query" required="true"/> | |
<cfargument name="row" type="query"/> | |
<cfargument name="forceArray" type="boolean" default="false"/> | |
<cfscript> | |
var local = StructNew(); | |
var result = StructNew(); | |
var idx = ""; | |
var colName = ""; | |
var columnLabels = arguments.query.getMetaData().getColumnLabels(); | |
</cfscript> | |
<cfif isDefined("arguments.row")> | |
<cfset local.row = arguments.row/> | |
<cfelseif arguments.query.recordCount eq 1> | |
<cfset local.row = 1/> | |
</cfif> | |
<cfif isDefined("local.row") and not arguments.forceArray> | |
<cfloop array="#columnLabels#" index="colName"> | |
<cfset StructInsert(result, colName, arguments.query[colName][local.row])/> | |
</cfloop> | |
<cfelseif isDefined("local.row")> | |
<cfset result = ArrayNew(1)/> | |
<cfset ArrayAppend(result, StructNew())/> | |
<cfloop array="#columnLabels#" index="colName"> | |
<cfset StructInsert(result[1], colName, arguments.query[colName][local.row])/> | |
</cfloop> | |
<cfelse> | |
<cfset result = ArrayNew(1)/> | |
<cfloop from="1" to="#arguments.query.recordCount#" index="idx"> | |
<cfset local.tempStruct = StructNew()/> | |
<cfloop array="#columnLabels#" index="colName"> | |
<cfset StructInsert(local.tempStruct, colName, arguments.query[colName][idx])/> | |
</cfloop> | |
<cfset ArrayAppend(result, local.tempStruct)/> | |
</cfloop> | |
</cfif> | |
<cfreturn result/> | |
</cffunction> |
I was using Ben's but it set the column names to uppercase. I need to preserve case for Javascript. This one appears to be broken as of today's date.
Actually, Coldfusion changes the column names to upper case. You could add a column map argument:
<cfset columnLabels = ArrayToList(arguments.query.getMetaData().getColumnLabels())>
<cfset local.temp = columnLabels>
<cfloop list="#arguments.columnmap#" index="columnamepreservecase">
<cfset local.temp = ReplaceNoCase(local.temp,columnamepreservecase,columnamepreservecase,"ALL")>
</cfloop>
<cfif ListLen(local.temp)>
<cfset columnLabels = ListToArray(local.temp)>
</cfif>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does this compare in terms of functionality with the methodology available at http://www.bennadel.com/blog/149-Ask-Ben-Converting-A-Query-To-A-Struct.htm ?