ColdFusion Muse

Datasource Attribute in Application.cfc

Mark Kruger May 9, 2012 2:19 PM ColdFusion Comments (2)

You may know about the "datasource" property in ColdFusion 9. It allows you to create a variable in your Application.cfc file called "datasource" and then skip the "datasource" attribute of your query tags. That's pretty neato. Here's how it works. In the Application.cfc properties...

<cfscript> = 'mort';
    this.sessionmanagement = true;
    this.datasource = 'myDsn';
Then in any component that is "inside" of my application "mort" above I can do something like this:
<!--- myMethods.cfc --->
<cffunction name="getAllUsers">
    <cfset var 'myQry = ''/>
    <cfquery name="myQry">
        SELECT username, email
        FROM     users
    <cfreturn myQry/>
Do you notice what is missing? There's no "datasource" attribute in the cfquery tag. ColdFusion automatically picks up the datasource from the Application.cfc instead. It's a nice time saving effort that reduces code and allows for fewer mistakes. Good for multi-tenant code too.

A Minor Detail

There is one issue that I was made aware of with this approach. Super genius guru Phillip Senn had a head scratching problem where he would set this variable in Application.cfc. Periodically he began getting and error which said:

The value of the attribute datasource, which is currently "" is invalid.
He tried some different things - working with the application names and extended properties of the Application.cfc but nothing seemed to help. Finally he ran the var scope checker which identifies places where un'varred variables exist inside of CFCs. He found several un'varred variables. After he fixed them the problem went away.

So if you are using this Application based this.datasource approach and you get some random errors where the variable seems undefined - or seems defined as a blank string - start looking for vars that are not properly scoped within your components. It may just fix you right up.

  • Share:


Leave this field empty

Write a comment

If you subscribe, any new posts to this thread will be sent to your email address.

  • Phillip Senn's Gravatar
    Posted By
    Phillip Senn | 5/9/12 3:11 PM

    I can't take credit for this one.
    But thanks for posting "Super genius guru" next to my name!
  • Shark's Gravatar
    Posted By
    Shark | 5/5/14 8:10 PM
    Thanks so much, I have noticed the very occasional error like this, but could never find an answer.

    It then started happening half way through a bulk email send so I really needed to get it fixed. It uses a cfthread so sounds like this scoping issue is the problem.

    Thanks to Mark and Phillip.