var scope of query in cfc

May 3, 2007 3:00 PM
Related Categories: Web Dev

I made a silly code error.  I admit it.  In my CFC I had queries without var scoping them.  The result was some rather crazy errors for one client.  To my credit I had properly scoped and locked my loading of the cfc and its init vars, etc.  Why didn't I?  Not sure why but it just didn't occur to me that I needed to.  Makes sense now of course.  A handy guide to scoping in CFC was made by Ray Camden for those that need more general info.

The code as it was works very well as is on my server and all our clients servers.  All but one.  At first it was maddening to determine just what the issue was.  Then I found out the client web server was a P2 400mhz 512mb Ram.  Yes you read that right.  So basically each request was quite slow.  Very easy to have heavy load on the server and thus for the vars to swap data, etc.  Something I couldn't reproduce on any other server was easily reproducible on theirs.

So to recap I did:

<cffunction name="mysamplefunction" >

    <cfquery name="GetData" datasource="blah">
    Select MyField
    From MyTable
    </cfquery>
   
<cfreturn getData />
</cffunction>

Because GetData wasn't specifically scoped it was by default in the variables scope and GetData then lived throughout the entire CFC and swapped data and all kinds of bad things.

I should have done:

<cffunction name="mysamplefunction" >
   <cfset var GetData = "">
    <cfquery name="GetData" datasource="blah">
    Select MyField
    From MyTable
    </cfquery>
   
<cfreturn getData />
</cffunction>

 

 

 This blog post is to help me remember to not do that again.  Bad josh.  bad.  :-)


Like this entry? Subscribe to my blog.

Comments (moderation on)

Umm...what?
# Posted By Liberty | 5/3/07 3:19 PM
Man bugs as a result of this can make you tear your hair out. A few years ago when CFMX came out I had some code I was working with and was trying to get to the bottom of a bug ... I had some code running in a loop and was tearing my hair out figuring how the index was looping 1,2,3,4,10,5,6,7,8 etc. crazy until I realised the Index variable hadn't been vared (thats another one to look out for).

Also check out varscper - very useful

http://www.schierberl.com/cfblog/index.cfm/2006/7/...
# Posted By kola | 5/3/07 4:49 PM
Hey Kola,

Looks like a great tool. Good to have those in your arsenal just in case. :-)
# Posted By Joshua Cyr | 5/4/07 2:45 PM

Sponsors


Savvy Content Manager