Database::setActiveConnection()
doesn't influence those objects that already have a \Drupal\Core\Database\Connection
object, which means that the following code will not use the preview connection for altering the database table.
use \Drupal\Core\Database\Database;
$schema = Database::getConnection()->schema();
$old_key = Database::setActiveConnection('preview');
$schema->addField($table, $field, $spec, $keys_new);
Database::setActiveConnection($old_key);
When you call \Drupal::logger()
, you get a DbLog
object that was already initialised before Database::setActiveConnection('preview')
is executed, which means it will use the old connection.
To be able to use the new connection for logging, you should try creating a custom logger that uses the connection you want, without you setting the connection before calling its methods.
As side note, Database::setActiveConnection()
returns the old key; it's easy to restore it: Just call again Database::setActiveConnection()
passing the value returned from the previous call, as I did with the code I shown.