Introduction
Currently there is no pointy, clicky way to change a field’s machine name once you’ve created it. With due credit to a blog post here I present a very simple script to create the SQL necessary to make the changes to the field name using PostgreSQL. A few notes:
- I had to change a lot of field names, it was tedious and error-prone, hence the script.
- Note, this is for PostgreSQL! Only wierdos like me use PostgreSQL for Drupal, most people use MySQL. At the time of writing PostgreSQL support in Drupal 7 (and the module community) still isn’t as solid as that for MySQL. I have my reason for using PostgreSQL over MySQL which is, in a word, ‘PostGIS’.
- I found some schema naming convention changes already between the original bloggers post and this one. In this case it was the convention of a column name ending changing from _tid to _target_id. Beware, poking the Drupal SQL database with the SQL stick is laying yourself bare to breakages in the future. This works for me, today, on Drupal 7.12. I don’t expect it to work on 7.13 or later – if it does, I am lucky.
- As the original poster noted, if you have module-based things that depend on the machine names that you are changing, expect them to break. A common thing would be Views that you created using the old machine names for those fields.
Script and Its Usage
./genFieldChangeSQL field_old_name field_new_name > my_field_name_change_script.sql
Then run the SQL script on PostgreSQL. Be sure to flush caches before going back to Drupal, e.g. with drush cc all.
#!/usr/bin/perl
use strict;
die if scalar @ARGV != 2;
die if @ARGV[0] !~ /^field_/;
die if @ARGV[1] !~ /^field_/;
print "update field_config set field_name" .
"='@ARGV[1]' where field_name='@ARGV[0]';n";
print "update field_config_instance set field_name" .
"='@ARGV[1]' where field_name='@ARGV[0]';n";
print "alter table field_data_@ARGV[0] rename " .
"to field_data_@ARGV[1];n";
print "alter table field_data_@ARGV[1] rename column " .
"@ARGV[0]_target_id to @ARGV[1]_target_id;n";
print "alter table field_revision_@ARGV[0] rename " .
"to field_revision_@ARGV[1];n";
print "alter table field_revision_@ARGV[1] rename column " .
"@ARGV[0]_target_id to @ARGV[1]_target_id;n";