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

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

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

		BEGIN
				CREATE TABLE IF NOT EXISTS public."QuotaEntityRelations" (
				   "Id" bigserial NOT NULL,
				   "QuotaId" integer NOT NULL,
				   "EntityId" bigint NOT NULL,
				   "EntityType" integer NOT NULL,
				   "Timestamp" timestamp without time zone DEFAULT timezone('utc', now())  NOT NULL,
					PRIMARY KEY ("QuotaId", "EntityType", "EntityId")
					);

				CREATE INDEX IF NOT EXISTS "IDX_QuotaEntityRelations_EntityId-EntityType-OwnerId"
					ON public."QuotaEntityRelations" USING btree
					("EntityId" ASC NULLS LAST,"EntityType" ASC NULLS LAST,"QuotaId" ASC NULLS LAST)
					TABLESPACE pg_default;
			
                INSERT INTO public."QuotaEntityRelations" ("QuotaId", "EntityType","EntityId")
                SELECT um."QuotaId", 5, um."UserId" FROM public."UserMetrics" um
                JOIN public."Users" u ON u."Id" = um."UserId" AND u."Status" <> -1
                WHERE um."QuotaId" IS NOT NULL AND
                NOT EXISTS(SELECT "QuotaId" FROM public."QuotaEntityRelations" qer 
                            WHERE um."UserId" = qer."EntityId" AND qer."EntityType" = 5 LIMIT 1);

                INSERT INTO public."Versions" ("Path", "Build") VALUES (_path, 0);
            EXCEPTION
				WHEN OTHERS THEN RAISE NOTICE '[ERR] patch-2024-10-24-QuotaEntityRelations_Merge_Users: %', SQLERRM;
		END;
	END;
$$