Using db.xml for an alternate database

Permalink 1 user found helpful
Is it possible to use db.xml within a package to configure a database outside of the one concrete5 is running in?

I have several database tables that are configured when a package installs and I need these tables to be located in an alternate database.

I already know how to config the database helper to use external databases, but haven't seen any documentation on utilizing db.xml files.

glockops
 
shahroq replied on at Permalink Reply
shahroq
You can wrap your your update query around the sql tag at db.xml
<sql>
    <query>
        UPDATE `myTable` SET `field1`=1;
    </query>
</sql>
glockops replied on at Permalink Best Answer Reply
glockops
I spent about 7 hours figuring this out yesterday. Here's the code that allows you to use a custom_db.xml file to create new tables in an alternative database during a package installation.

This code goes in the install() method of the package controller
// install custom_db.xml
      $xmlFile = dirname(__FILE__).'/custom_db.xml';
      if(file_exists($xmlFile)) {
         Log::AddEntry('PKG INSTALL: Custom DB file exists. Creating tables in storage DB.');
         // establish connection to custom database
         $db = Loader::db(DB_STORAGE_SERVER, DB_STORAGE_USERNAME, DB_STORAGE_PASSWORD, DB_STORAGE_DATABASE, true);
         Package::installDB($xmlFile);
         // reset connection to core database
         $db = Loader::db(false, false, false, false, true);
         Log::AddEntry('Connection re-established with core database.');
      }


It checks to see if the file custom_db.xml exists in the package's directory. If it does - it establishes a database connection to an alternative location. You can define DB_STORAGE_SERVER, etc in your site's config/site.php file (just like DB_SERVER, etc).

It uses the Package::installDB($xml) function to install a different xml file. This allows you to both install the custom xml and a regular db.xml (db.xml is installed during the parent::install() method).

Finally it establishes a connection back to the core database.

A special note: keep in mind that you cannot perform any concrete5 API functions when you are connected to an alternative database location - it's important to "reset" the Loader::db() as soon as you're done using the custom DB connection.

Also, you'll get really random error messages if you happen to be using a reserved/illegal word in your xml files. I called a column "group" and MySQL was throwing fits - but not giving me a proper error message - so if you're getting weird results - check for reserved words.
JohntheFish replied on at Permalink Reply
JohntheFish
You should write that up as a howto.