DO $$
	BEGIN
		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=2812) THEN
			RETURN;
	END IF;

	BEGIN

		ALTER TABLE public."EmailMessages" ADD "Uid" BIGINT DEFAULT(0) ;
		UPDATE public."EmailMessages" SET "Uid" = (case when "ExternalId"~E'^\\d+$' then "ExternalId"::integer else 0 end);
		
		CREATE SEQUENCE public.tmp_seq
	INCREMENT BY 1
	MINVALUE 1
	MAXVALUE 9223372036854775807
	START 1
	CACHE 1
	NO CYCLE;
		
		UPDATE public."EmailMessages" SET "Uid" = -nextval('tmp_seq') where "Uid"=0;
		
		drop SEQUENCE public.tmp_seq;
		
		ALTER TABLE public."EmailMessages" ADD CONSTRAINT "UIDX_EmailMessages" UNIQUE ("FolderId", "Uid");
 		ALTER TABLE public."EmailMessages" DROP COLUMN "ExternalId"; 
		EXCEPTION
			WHEN OTHERS THEN RAISE NOTICE 'Add Uid to table EmailMessages error.';
		END;
	END;
$$



