insert into groups_permissions
(id,
 project_id,
 parent_id,
 title,
 description,
 admin,
 permissions,
 total_groups,
 total_members,
 deleted,
 created_at,
 updated_at,
 deleted_at,
 options)
select id,
       project_id,
       parent_id,
       title,
       description,
       (case when admin is null then false else admin end),
       (case when permissions is null then '' else permissions end),
       total_groups,
       total_members,
       deleted,
       created_at,
       updated_at,
       deleted_at,
       (case when "options" is null then '' else "options" end)
from groups
where not exists(select 1 from groups_permissions where groups_permissions.id = groups.id);

update groups set options = '{"ReceiveProjectNotifications":false}' where options = '';
update groups_permissions set options = '{"ReceiveProjectNotifications":false}' where options = '';

declare
    ex number;
begin
    select MAX(id)  + 1 into ex from groups_permissions;
    If ex > 0 then
        begin
            execute immediate 'DROP SEQUENCE groups_permissions_id_seq';
            exception when others then
                null;
        end;
        execute immediate 'CREATE SEQUENCE groups_permissions_id_seq INCREMENT BY 1 START WITH ' || ex || '';
    end if;
end;

declare
    ex2 number;
begin
    select MAX(id)  + 1 into ex2 from groups;
    If ex2 > 0 then
        begin
            execute immediate 'DROP SEQUENCE groups_id_seq';
            exception when others then
                null;
        end;
        execute immediate 'CREATE SEQUENCE groups_id_seq INCREMENT BY 1 START WITH ' || ex2 || '';
    end if;
end;

insert into group_permissions_members (id, group_id, user_id, deleted, created_at, updated_at, deleted_at, restored_at)
select *
from group_members
where not exists(select 1 from group_permissions_members where group_permissions_members.id = group_members.id);
declare
    ex3 number;
begin
    select MAX(id)  + 1 into ex3 from group_permissions_members;
    If ex3 > 0 then
        begin
            execute immediate 'DROP SEQUENCE group_permissions_members_id_seq';
            exception when others then
                null;
        end;
        execute immediate 'CREATE SEQUENCE group_permissions_members_id_seq INCREMENT BY 1 START WITH ' || ex || '';
    end if;
end;

declare
    ex4 number;
begin
    select MAX(id)  + 1 into ex4 from group_members;
    If ex4 > 0 then
        begin
            execute immediate 'DROP SEQUENCE group_members_id_seq';
            exception when others then
                null;
        end;
        execute immediate 'CREATE SEQUENCE group_members_id_seq INCREMENT BY 1 START WITH ' || ex2 || '';
    end if;
end;
