Automatically Change Database Based on the Git Branch
While working on some larger enterprise Drupal projects we make extensive use of feature branches. Note: See A Successful Git branching model. When changing branches (e.g. git checkout) we've often run into issues where the code in that branch does not match up well with the database. This often happens if a branch includes a database update, new module, etc. and we aren't ready to merge that into the other feature branches.
We had several workarounds that weren't very efficient.
- Manually create a new database per branch and update the settings file every time.
- Create database dumps prior to switching branches and import a dump after switching.
Neither option was enjoyable and often led to mistakes so we came up with small solution inside the settings file.
Note: Recommendation is to first create environment specific settings files given that git may not be installed on every environment or we don't want to run the following bit of code.
At the bottom of our settings.[environment].php file we added the following code.
- /**
- * Acquire the current git branch and populate a variable to render on the
- * site.
- */
- $path_to_git_head = '/path/to/.git/HEAD';
- if ($git_head = file($path_to_git_head, FILE_USE_INCLUDE_PATH)) {
- $git_head = $git_head[0];
- $git_head_exploded = explode("/", $git_head);
- $git_branch = $git_head_exploded[2];
- $conf['current_git_branch'] = $git_branch;
- }
- /**
- * If we were able to determine the git branch, try to connect to a
- * branch-specific database if possible.
- */
- if (!empty($git_branch)) {
- $git_branch_db = preg_replace('/[^a-zA-Z0-9_]/', '', $git_branch);
- try {
- $dbh_test = new PDO('mysql:host=localhost;dbname=' . $databases['default']['default']['database'] . "_$git_branch_db", $databases['default']['default']['username'], $databases['default']['default']['password']);
- $databases['default']['default']['database'] .= "_$git_branch_db";
- } catch (PDOException $ex) {}
- }
What the above code does is attempt to acquire the current branch, and if so, then modify the default database settings established in the settings.[environment].php file.
To help make things more noticeable for the developer, we do render a few variables in our page.tpl.php file.
- <?php if ($is_admin): ?>
- <!-- Admin environment notification -->
- <div id="environment" class="messages warning">
- <strong><?php print variable_get('environment','Undefined'); ?></strong> Environment; <strong><?php print variable_get('current_git_branch','Undefined'); ?></strong> git branch; <strong><?php global $databases; print $databases['default']['default']['database']; ?></strong> database.
- </div>
- <?php endif; ?>
The above code lists the current environment, git branch, and database which are all set in our settings files.