DO $$
	DECLARE 
	 path character varying(256) =  'Patch-2024-06-04-UserAddressBookLinks-OwnerId';
	 BEGIN

		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Path"=path) THEN
	    		RETURN;
	    	END IF;
 
		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Build">=3780) THEN
			RETURN;
		END IF;

		ALTER TABLE   public."UserAddressBookLinks" ADD "OwnerId" bigint NULL;
		UPDATE public."UserAddressBookLinks"  SET "OwnerId"=(SELECT "OwnerId" FROM public."UserAddressBooks" u where u."Id"="AddressBookId");

		CREATE INDEX "UserAddressBookLinks_IDX_OwnerId_ContactId"
			  ON public."UserAddressBookLinks" USING btree
			   ("OwnerId" ASC NULLS LAST,"ContactId" ASC NULLS LAST,"ContactId" ASC NULLS LAST,"PhoneNumbers" ASC NULLS LAST)
			   TABLESPACE pg_default;

		INSERT INTO public."Versions" ("Path", "Build")
		  select path,0 ;

		EXCEPTION
			WHEN OTHERS THEN RAISE NOTICE 'Create table UserAddressBookLinks error.';
	END;
$$
