Wednesday 28 August 2013

CFML: Referencing a query column via dot notation or associative array notation

G'day:
A few days back I asked a question via a Survey Monkey survey, relating to people's awareness of some CFML syntax relating to query columns.

The question was this:
What values for "dotNotation" and "arrayNotation" does this code return:

<cfscript>
q = queryNew("");
queryAddColumn(q, "id", "varchar", ["a","b","c","d","e"]);

writeDump({
    dotNotation        = isArray(q.id),
    arrayNotation    = isArray(q["id"])
});
</cfscript>
(NB: originally the values in the query column were 1-5, but as there was some question about values being treated as booleans, I changed that (the values were irrelevant to the question)).

The answer (on ColdFusion, which I purposely didn't specify) is this:

struct
ARRAYNOTATIONYES
DOTNOTATIONNO

On Railo it's this:

Struct
ARRAYNOTATION
booleanfalse
DOTNOTATION
booleanfalse

And for the sake of completeness, on OpenBD it's this:

struct
arrayNotationYES
dotNotationNO

Bottom line: when using associative array notation, query[column] is a reference to the entire column, whereas using dot notation, query.column is a reference to the individual value of the current row of that column.

I got 17 responses (which ain't great), and six people got it right. One person gets a bonus point because they answered for both Railo and ColdFusion.

I brought this up because some of my code written for CF broke on Railo because of the mismatch in behaviour. I spotted a bug that covered similar ground: "ArrayToList on query columns throws errors (RAILO-534)", and chatted to Micha about it briefly. I found myself saying it was a widely-used practice to leverage this whole-column-reference thing, but I thought I better see if it actually was the case. Hence the survey to poll whether people knew about it.

And... seemingly not. But it's handy knowledge to tuck away in the back of yer mind; and the difference in behaviour of the two platforms is perhaps also handy info to tuck away.

That's the only reason I was asking.

Thanks to all the bods who helped out.

--
Adam