Skip to content

Instantly share code, notes, and snippets.

@liamcmitchell
Created January 2, 2013 07:46
Show Gist options
  • Save liamcmitchell/4432924 to your computer and use it in GitHub Desktop.
Save liamcmitchell/4432924 to your computer and use it in GitHub Desktop.
Drush script to remove table aliases from a Drupal 6 site. Usage: drush php-script remove-prefix.php [pretend]
<?php
/**
* Drush script to remove table aliases from a Drupal 6 site.
* Usage:
* drush php-script remove-prefix.php [pretend]
*/
$arg = drush_shift();
$pretend = $arg == 'pretend' ? TRUE : FALSE;
global $db_prefix;
$prefix = $db_prefix;
if ($prefix) {
drush_print("Removing prefix '$prefix'");
}
else {
drush_set_error('ERROR', 'Will only work if prefix is set in settings.php');
drush_set_context('DRUSH_EXECUTION_COMPLETED', TRUE);
exit;
}
$table_list = db_query("SHOW TABLES");
$prefix = strtolower($prefix);
while ($r = db_fetch_array($table_list)) {
$table_old = strtolower(current($r));
// check for $prefix on this table
if(substr($table_old,0,strlen($prefix)) == $prefix) {
$table_new = substr($table_old, strlen($prefix));
// first drop $table_new incase it already exists
$clean_sql = "DROP TABLE IF EXISTS {$table_new}";
// rename prefix table to standard/nonprefix name
$rename_sql = "RENAME TABLE {$table_old} TO {$table_new}";
if($pretend) {
drush_print($clean_sql);
drush_print($rename_sql);
} else {
if(!db_query($clean_sql)) {
drush_set_error('ERROR', "Failed query: $clean_sql");
}
if(!db_query($rename_sql)) {
drush_set_error('ERROR', "Failed query: $rename_sql");
}
}
} else {
drush_set_error('WARNING', "$table_old skipped");
}
}
# Remove prefix from settings.php
if (!$pretend) {
$regex = escapeshellarg('s|^\$db_prefix\s*=.*\;$|$db_prefix = \'\';|g');
$settings_path = conf_path().'/settings.php';
exec("sed -i $regex $settings_path", $out = '', $ret = 0);
if ($ret != 0) {
drush_set_error('ERROR', 'settings.php could not be changed: '.$out);
}
}
drush_print("Done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment