0

I have two databases set in my settings.php file. One is used for drupal, one is for our backend which is external from the drupal installation and databases. I would like to query the backend database but cannot change the db_active because then our site users will have issues accessing their profiles. How can I go about connecting to the two databases simultaneously?

  • What do you mean by 'simultaneously' exactly? A query can obviously only be run against a single connection at once, so conceptually (as in forget about Drupal for a second) how are you looking to solve this? Are you looking to intercept every single query and then change the connection based on some criteria? If so, what is that criteria? How are you planning to detect/handle queries that are made as part of a transaction? – Clive Mar 11 '14 at 12:51
2

I think you are inventing a problem that doesn't exist.

The active database will be per-request, not site wide. So if one user is accessing your backend, another user can do whatever they need against your default Drupal database.

Within a request, you can use the db_set_active() function to switch databases as much as you want. eg

$query = db_query(...);   // runs against the default database
db_set_active('backend'); // change databases
$query = db_query(...);   // runs against $databases['backend'];
db_set_active();          // change back to default databases
$query = db_query(...);   // runs against the default database

As PHP is single threaded w/in a single request, you don't have to worry about a query running against the wrong database.

So, in summary, just use db_set_active() to change databases when you need to, and then remember to switch back when you are done. If you isolate your code (which you really need to do in Drupal anyway), you shouldn't run into trouble.

I would also look into hook_views_data(). This works very well to being in external data into Drupal.

  • also if your 2 databases share mysql credentials. There is nothing stopping you from writing like $results = db_query("select table1.* from table1 join db2.table2.* where table1.id = 5 and db2.table2.id=1;")->execute();. MySQL supports cross-database queries so long as the mysql user has the proper privileges. SQLite and I believe Postgres support this as well. – tenken Mar 11 '14 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.