Amarok: Album Release Dates from MusicBrainz

This code should* select all the albums in a MySQL Amarok database for which the release year is unknown, look them up from MusicBrainz and update the database as appropriate. The found year isn't written to the tracks' ID3 tags, unfortunately, as there doesn't seem to be a DCOP call to update the year.

Then you can make a smart playlist like this:

* NOTE: backup your database first

#! /usr/bin/env python
import sys, time, MySQLdb
from musicbrainz2.webservice import Query, ReleaseFilter
db = MySQLdb.connect(db="DB_NAME", user="DB_USER", passwd="DB_PASS", use_unicode=True, charset="utf8")
c = db.cursor()
c.execute("""SELECT as 'artist', as 'artist_id', as 'album', as 'album_id' FROM `artist` a INNER JOIN `tags` t ON = t.artist INNER JOIN `album` b ON t.album = WHERE t.year = 1 AND t.sampler = 0 GROUP BY, ORDER BY ASC""")
print "%d rows" % c.rowcount
albums = c.fetchall()
for (artist, artist_id, album, album_id) in albums:  
  if (artist and album):
    q = Query()
    print "Looking up: %s - %s" % (artist, album)
    f = ReleaseFilter(artistName=artist, title=album, limit=1)
    results = q.getReleases(f)
    if results:
      result = results[0]
      release = result.release
      print "Found: %s - %s" % (, release.title)
      if (release.releaseEvents and release.releaseEvents[0].date):
        ymd = release.releaseEvents[0].date.split('-');
        print ymd[0];
        c.execute ("""SELECT `id` FROM `year` WHERE `name` = %s""", (ymd[0]))
        year_id = c.fetchone()
        if year_id:
          c.execute ("""UPDATE tags SET year = %s WHERE artist = %s AND album = %s""", (year_id[0], artist_id, album_id))
      print "No results"