DO $$ 
	DECLARE _path character varying(256) = 'patch-2024-10-11-Documents_HasRights';

	BEGIN
		IF EXISTS (SELECT "Id" FROM public."Versions" WHERE "Path"=_path) THEN
			RETURN;
		END IF;

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

		BEGIN 
			ALTER TABLE public."Documents"  ADD "HasRights" boolean DEFAULT false;
			ALTER TABLE public."Documents"  ADD "HasShare" boolean DEFAULT false; 

			CREATE INDEX "IDX_Documents_OwnerId-HasRights-HasShare"
    				ON public."Documents" USING btree
   				("OwnerId" ASC NULLS LAST, "HasRights" ASC NULLS LAST, "HasShare" ASC NULLS LAST)
    				TABLESPACE pg_default;  


 			UPDATE  public."Documents" 
				SET "HasRights" = true 
			WHERE EXISTS 
					(SELECT ua."EntityId" FROM public."UserAccessRights" AS ua 
			  			WHERE ua."EntityId"=public."Documents"."Id" AND ua."EntityType"=2)
	 				OR EXISTS (SELECT ra."EntityId" FROM public."RoleAccessRights" AS ra  
				 		WHERE ra."EntityId"=public."Documents"."Id"
				 AND ra."EntityType"=2);

			UPDATE  public."Documents" 
				SET "HasShare" = true 
			WHERE EXISTS (SELECT sl."EntityId" FROM public."SharedLinks" AS sl  
						  WHERE sl."EntityId"=public."Documents"."Id"
				 AND sl."EntityType"=2  AND sl."LifeTime" IN(10));



 
 			INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);

			EXCEPTION
				WHEN OTHERS THEN RAISE NOTICE '[ERR] patch-2024-10-11-Documents_HasRights: %', SQLERRM;
		END;
	END;
$$ 