DO $$
DECLARE
	_path  character varying(256) := 'patch-2026_03_02-FlexibleTables-Status-DeleteUserId.sql';
	_build integer := 16616;
BEGIN
	IF EXISTS (SELECT 1 FROM public."Versions" WHERE "Path" = _path) THEN
		RETURN;
	END IF;

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

	BEGIN

		update public."FlexibleTables" set "Status" = 1 where "Status" = 0;
		alter table public."FlexibleTables" add column IF NOT exists "DeleteUserId" int8 NULL;
		alter table public."FlexibleTables" add column IF NOT exists "Updated" timestamp null;

		DROP INDEX "IDX_UserAccessRights_UserId-EntityId-EntityType";
		CREATE INDEX IF NOT exists "IDX_UserAccessRights_UserId-EntityType-EntityId"
		ON public."UserAccessRights" USING btree
		("UserId" ASC NULLS LAST,"EntityType" ASC NULLS LAST, "EntityId" ASC NULLS LAST)
		TABLESPACE pg_default; 

		CREATE INDEX IF NOT exists "IDX_ProjectFlexibleTableLinks-ProjectId-TableId" ON public."ProjectFlexibleTableLinks" ("ProjectId", "TableId"); 


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

	EXCEPTION
		WHEN OTHERS THEN
			RAISE NOTICE '[ERR] %: %', _path, SQLERRM;
	END;
END;
$$;
