DO
$$
    DECLARE
        _path character varying(256) := 'patch-2025_11_26-FlexibleTableEntity';
    BEGIN
        IF EXISTS (SELECT 1 FROM public."Versions" WHERE "Path" = _path) THEN
            RETURN;
        END IF;

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

        BEGIN

            DROP INDEX IF EXISTS "IDX_FlexibleTableEntity-TableId";
            alter table public."FlexibleTableEntity" add column "Order" bigserial not null;
            CREATE INDEX IF NOT EXISTS "IDX_FlexibleTableEntity-TableId-Order"
                ON public."FlexibleTableEntity" USING btree
                ("TableId" ASC NULLS LAST, "Order" ASC NULLS LAST)
                TABLESPACE pg_default;

            WITH cte_RankedRows AS (
                SELECT
                    "Id" as EntityId, "TableId", 
                    ROW_NUMBER() OVER (
                        PARTITION BY "TableId"
                        ORDER BY "Id" ASC 
                    ) AS new_order
                FROM public."FlexibleTableEntity"
            )
            UPDATE public."FlexibleTableEntity"
            SET "Order" = cr.new_order
            FROM  cte_RankedRows cr 
            where cr.EntityId = "Id";

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