1

I'm working on a project where I use a database that is common to all sites and another that is specific to each. Is there a way to detect access to a specific table on a contrib module (maybe using a hook) and redirect the queries to a table on the db of the shared site?

The contrib module in question is Oauth2.0 server and the table in question is the one where clients are stored, namely oauth2_server_client .

1 Answer 1

0

You don't need to intercept all the query done for a database table. It is enough you change the settings for the database in the settings.php file.

Suppose that the default database definition is the following one.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'collation' => 'utf8_general_ci',
);

If you change it as follow, you change the database used for that particular table.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => array(
    'oauth2_server_client' => 'otherdatabase.',
  ),
  'collation' => 'utf8_general_ci',
);

In this way, you are telling Drupal that for the oauth2_server_client table, the otherdatabase database needs to be used. That database needs to be accessible from the same database user (username, in my example).

Generally speaking, you can alter the query done from a module if:

  • The query is a dynamic query
  • The module added a tag to that query, such as in the following code

    $query = db_select('node', 'n')
      ->addTag('node_access');
    

In that case, you could implement hook_query_alter() or hook_query_TAG_alter().

In your case, since you want to change the database table used for all the queries to that table, I would change the database definition in the settings.php file.

2
  • Just tried it by adding manually a new client to the server and I got this error: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'h.younes'@'localhost' for table 'oauth2_server_client': SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM {oauth2_server_client} oauth2_server_client WHERE (oauth2_server_client.server = :db_condition_placeholder_0) ) subquery; Array ( [:db_condition_placeholder_0] => server1 ) in EntityFieldQuery->execute() (line 1192 of /Users/share/Public/Sites/h.younes/includes/entity.inc).
    – sam
    May 26, 2016 at 6:54
  • Thanks for the response; just had to grant access credentials to db.
    – sam
    May 26, 2016 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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