create or replace function downgrade_to_84()
returns int as $$
begin
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_83()
returns int as $$
begin
    drop table retention_policies;
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_82()
returns int as $$
begin
    insert into flags (mailbox, uid, flag)
        select mailbox, uid, (select id from flag_names where name=E'\\Seen')
        from mailbox_messages where seen;
    insert into flags (mailbox, uid, flag)
        select mailbox, uid, (select id from flag_names where name=E'\\Deleted')
        from mailbox_messages where deleted;
    alter table mailbox_messages drop seen, drop deleted;
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_81()
returns int as $$
begin
    drop trigger mailbox_update_trigger on mailboxes;
    drop function check_mailbox_update();
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_80()
returns int as $$
begin
    drop trigger mailbox_owner_trigger on mailboxes;
    drop function set_mailbox_owner();
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_85()
returns int as $$
begin
    drop trigger retention_policies_trigger on retention_policies;
    drop function notify_retention_policies();
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_86()
returns int as $$
begin
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_87()
returns int as $$
begin
    alter table users alter alias set not null;
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_88()
returns int as $$
begin
    alter table connections add userid integer;
    update connections set userid=users.id from users where users.login=connections.username;
    alter table connections drop username;
    alter table connections add foreign key(userid) references users(id);
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_89()
returns int as $$
begin
    alter table deliveries drop deliver_after;
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_90()
returns int as $$
begin
    return 0;
end;$$ language 'plpgsql';

create or replace function downgrade_to_91()
returns int as $$
begin
    alter table connections drop userid;
    return 0;
end;$$ language 'plpgsql';
