DataFaucet ORM

Multiple Datasources

The majority of ColdFusion applications use only a single database and there's nothing wrong with that. Occasionally however there are reasons to access multiple databases within a single application. In a corporate environment for example, you might have a few different applications on the same server each having its own "primary" database but also needing to get certain information from a central corporate database. In this case the best-case scenario is that the system manages the databases centrally so that if there is a change to the corporate database, there aren't multiple applications on your server that need to be sync'ed.

You should already be familiar with using a single datasource with DataFaucet. You access the source via the getDatasource() method like this:

<cfset ds = request.DataFaucet.getDatasource() />

DataFaucet makes managing multiple datasources in your application easy through its source manager in the application scope. You won't be referencing the application scope however, you'll be fetching the source manager through the request manager like this:

<cfset sources = request.DataFaucet.getSources() />

Once you have the sources object you can then get() or set() datasources as needed.

Names: Each datasource used in a given application is named and names should be relevant to the context of the application in which they're used. The database returned by the getDatasource() method shown above is named "primary" indicating that it is the main datasource used within your application. So request.DataFaucet.getDatasource() is equivalent of request.DataFaucet.getSources().get("primary").

Configuring A Named Source: It's not necessary to set a datasource before getting it. If you simply get the datasource, the faucet will return a new datasource for you to initialize. You'll probably want to initialize your additional databases in the onApplicationStart event in your Application.cfc although this isn't strictly necessary. Initializing a new datasource might look like this:

  // get the datasource
  ds = request.DataFaucet.getDatasource(); 
  // get the source manager 
  sources = request.DataFaucet.getSources(); 
  // initialize the corporate database 
  sources.get("corp").init(datasource="corpDSN", server="oracle", usr="username", pwd="password"); 

Using A Named Source: Once you've configured a new datasource, using it is very similar and should be immediately obvious.

  // get the datasource
  ds = request.DataFaucet.getDatasource(); 
  // get the corporate datasource 
  ds = request.DataFaucet.getSources().get("corp"); 
  // get some data from the corporate database 
  // note the typical corporate database table name 
  qry ="*","dept_bud_budget_approval_schedule_2008_quarter4");