How to validate connection using db_set_active
| Project: | Drupal |
| Version: | 6.12 |
| Component: | database system |
| Category: | support request |
| Priority: | critical |
| Assigned: | Unassigned |
| Status: | active |
Jump to:
I want to create some blocks that query an external database.
Per instructions on http://drupal.org/node/18429, I have been able to successfully do this as long as the connection is working. Since the database is on a different server, sometimes the connection may be broken. If the connection is broken, I get a big, ugly error page that kills the entire page.
My question is: how can I gracefully check to see that the connection to the secondary database is working and show a nice, friendly "sorry, this database isn't available", rather than a big giant error that breaks everything??
I looked at the DB abstraction layer page at http://api.drupal.org/api/group/database and couldn't find anything that works. I presume this is because the connection is defined in settings.php and the array variable exists for my block code to proceed even though the actual connection is broken.
Help!?!?

#1
Would be nice if there was a built in function.
But there isn't so I did this:
<?php
db_set_active('otherDB');
// check to see if we have connected successfully
$sql = 'SELECT value from {variable} WHERE name = "site_name"';
$result = db_query($sql);
$site = strtolower(unserialize(db_result($result)));
if($site == "site_name_of_other_db") {
// do your stuff
}
else {
// set error, etc
}
db_set_active();
?>
It's not perfect, but might help. Also, it assumes you are connecting to another Drupal database, but you could make appropriate changes if you needed. Maybe add a custom table to your "other" database that does not exist on the default one.
#2
Thanks very much for the suggestion emackn, but the workaround you propose does not help me.
It seems that the db_set_active() call itself causes the _db_error_page to be returned, before we can even get to the test that checks if the current site name matches the "otherDB" site name.
Any other suggestions out there? It does not seems right that a connection problem to an external database must produce an error page, rather than returning a value that can be tested and acted on. Do we have to make do and write something with php functions for now?
#3
>It does not seems right that a connection problem to an external database must produce an error page
Unfortunately (for you) that is the way it works at the moment. You would probably need to write a customized version of db_connect() (see http://api.drupal.org/api/drupal/includes--database.mysql.inc/6/source) and maybe also of http://api.drupal.org/api/function/db_set_active/6 so that if you can't connect then you can do something other than show the DB error page. Then invoke these from the block. Or put the whole lot into a small custom module.