def add_if_not_exists(string):
    # this workaround was adapted and expanded from
    # http://dba.stackexchange.com/questions/35616/create-index-if-it-does-not-exist/35626#35626
    # The following basically means "if not exists":
    #     IF (SELECT to_regclass('%(name)s') is NULL)
    # and the 'DO $do$ BEGIN ... END $do' stuff
    # is just to make postgres allow the IF statement
    return ''.join([
        "DO $do$ BEGIN IF (SELECT to_regclass('%(name)s') is NULL) THEN ",
        string,
        "; END IF; END $do$"
    ])
turn a 'CREATE INDEX' template into a 'CREATE INDEX IF NOT EXISTS' template
dataset/ETHPy150Open dimagi/commcare-hq/corehq/util/django_migrations.py/add_if_not_exists