0

I need to run a new query on another database.

I configured the settings.php

 $databases = array (
      'default' => 
      array (
        'default' => 
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
      'slave' => 
      array (
        'default' => 
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
    );

and this is my custom function:

    function myModule_test()
{

    db_set_active('slave');

    sleep(90);

    $view = views_get_view('test_view');
    $view->set_display('page');
    $view->pre_execute();
    $view->execute();

    print $view->render();
    db_set_active();

    }

the query is performed on the second database, what I do not understand is if the database change is local or global, because during the sleep (90) I tried to insert a new 'article' content and it has been inserted into the 'default' database.

1

It's a per-request global setting. db_set_active calls:

Database::setActiveConnection($key);

Which sets the static $activeKey property of the Database class.

Database::getConnection(), which is where the connection for all queries comes from, then uses that same static $activeKey.

So once you've used db_set_active, all queries in that request will use the new connection until changed again.

It doesn't persist across multiple requests.

| improve this answer | |
  • I'm sorry, an explanation: why was the inclusion of a new content done in the main database? – Leo Oct 18 '18 at 7:08
  • 1
    You haven’t provided any details so I can only guess, but given that sleep blocks the request, if you managed to insert content while it wa sleeping, that would’ve been in a separate request. Presumably you didn’t change the connection from default for that separate request – Clive Oct 18 '18 at 7:15

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.