Monday, June 3, 2013

How to rename/merge projects in sonar

Sonar doesn't support merging of projects out of the box so when you happen to rename a project as I just did, you're suddenly stuck with 2 projects of the same name unless you do a little bit of sql trickery in the back. Here's how you do it (quick & dirty approach). What we're going to to is: rename the old projects (with all the juicy metrics) to the new groupid/artifactid and delete the new one (which only has a handful of builds anyway and we can afford to loose these, but not the yearlong history we've collected):

Stop everything accessing the sonar server

This is to make sure noone else accesses the database while you're messing with it.

# ssh into the box
# service sonar stop

Make a db backup

# pg_dump sonar > sonar-backup.sql
Here's more info on backup/restore for postgresql.

Rename!

First you'll need to get a list of all projects you want to rename:

# su - postgres
# psql -c "SELECT kee FROM projects WHERE kee like 'old.groupid.and:artifactid%';" > to-be-renamed.sql

Rewrite the output you got above into an update statement that looks something like this:

UPDATE PROJECTS SET kee = 'new.groupid.and:artifactidXXX' WHERE kee = 'old.groupid.and:artifactidXXX';
Where XXX is whatever else is at the end of these lines, note that the root project does not have a trailing colon after the artifactId. I constructed the update statements by hand because it's very fast to do with Sublime Text's Column Editing Capabilities.

Now that the updates are ready, execute them:

# psql sonar -f the-rename.sql

Cleanup

Restart sonar and point your browser at it, you'll notice you still have 2 projects. Go to sonar's settings and choose "bulk deletion" from the menu on the left. Look at the source of the page and carefully choose the newer project (you can tell by the project id). Select that project in the ui and delete it. You're done!