def upgrade():
    query = '''UPDATE "user"
                 SET ckan_api=null
                 WHERE id IN (SELECT id 
                    FROM (SELECT id, row_number() over (partition BY ckan_api ORDER BY id) AS rnum
                          FROM "user") t
               WHERE t.rnum > 1);
            '''
    op.execute(query)
    op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api'])