From e66431f4c39e58cccfd356e0300a246f1494b15e Mon Sep 17 00:00:00 2001 From: Christopher Allan Webber Date: Mon, 25 Feb 2013 16:16:21 -0600 Subject: [PATCH] Supplying migrations for a bold new era of mediagoblin entry slugs Okay, that's a totally confusing statement, but the docstring of this migration summarizes it well: Entries without slugs now display differently in the url like: /u/cwebber/m/id=251/ ... because of this, we should back-convert: - entries without slugs should be converted to use the id, if possible, to make old urls still work - slugs with = (or also : which is now also not allowed) to have those stripped out (small possibility of breakage here sadly) This commit sponsored by John Sullivan. Thanks johnsu01! :) --- mediagoblin/db/migrations.py | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/mediagoblin/db/migrations.py b/mediagoblin/db/migrations.py index b25d577d..3c997b94 100644 --- a/mediagoblin/db/migrations.py +++ b/mediagoblin/db/migrations.py @@ -195,3 +195,57 @@ def add_license_preference(db): col = Column('license_preference', Unicode) col.create(user_table) db.commit() + + +@RegisterMigration(9, MIGRATIONS) +def mediaentry_new_slug_era(db): + """ + Update for the new era for media type slugs. + + Entries without slugs now display differently in the url like: + /u/cwebber/m/id=251/ + + ... because of this, we should back-convert: + - entries without slugs should be converted to use the id, if possible, to + make old urls still work + - slugs with = (or also : which is now also not allowed) to have those + stripped out (small possibility of breakage here sadly) + """ + import uuid + + def slug_and_user_combo_exists(slug, uploader): + # Technically returns the number of entries with this slug and user + # that already exist + return db.execute( + media_table.select( + media_table.c.uploader==uploader, + media_table.c.slug==slug)).first().tbl_row_count + + def append_garbage_till_unique(row, new_slug): + """ + Attach junk to this row until it's unique, then save it + """ + if slug_and_user_combo_exists(new_slug, row.uploader): + # okay, still no success; + # let's whack junk on there till it's unique. + new_slug += '-' + uuid.uuid4().hex[:4] + # keep going if necessary! + while slug_and_user_combo_exists(new_slug, row.uploader): + new_slug += uuid.uuid4().hex[:4] + + db.execute( + media_table.update(). \ + where(media_table.c.id==row.id). \ + values(slug=new_slug)) + + metadata = MetaData(bind=db.bind) + + media_table = inspect_table(metadata, 'core__media_entries') + for row in db.execute(media_table.select()): + # no slug, try setting to an id + if not row.slug: + append_garbage_till_unique(row, unicode(row.id)) + # has "=" or ":" in it... we're getting rid of those + elif u"=" in row.slug or u":" in row.slug: + append_garbage_till_unique( + row, row.slug.replace(u"=", u"-").replace(u":", u"-")) -- 2.25.1