START TRANSACTION;
CREATE OR REPLACE FUNCTION inplace_upgrade.UserSpaceToOrigin()
RETURNS int
AS $$
DECLARE
    row_name record;
    query_str text;
    query_new text;
    dn_num int;
    new_limit bigint;
    record_cnt int;
BEGIN
    record_cnt := 1;
    SELECT count(*) into dn_num from pg_catalog.pgxc_node where node_type='D';
    query_str := 'SELECT * FROM inplace_upgrade.OrigSpaceLimit;';
    FOR row_name IN EXECUTE(query_str) LOOP
        IF row_name.roltabspace IS NOT NULL
        THEN BEGIN
            new_limit := ceil(to_number(btrim(row_name.roltabspace, 'K'))/dn_num);
            query_new := 'ALTER USER ' || row_name. rolname|| ' PERM SPACE '''|| new_limit ||'K'';';
            EXECUTE(query_new);
        EXCEPTION
        WHEN OTHERS THEN
            INSERT INTO inplace_upgrade.SpaceLimitSetFail VALUES (query_new);
        END;
        END IF;
        IF row_name.roltempspace IS NOT NULL
        THEN BEGIN
            new_limit := ceil(to_number(btrim(row_name.roltempspace, 'K'))/dn_num);
            query_new := 'ALTER USER ' || row_name.rolname || ' TEMP SPACE '''|| new_limit ||'K'';';
            EXECUTE(query_new);
        EXCEPTION
        WHEN OTHERS THEN
            INSERT INTO inplace_upgrade.SpaceLimitSetFail VALUES (query_new);
        END;
        END IF;
        IF row_name.rolspillspace IS NOT NULL
        THEN BEGIN
            query_new := 'ALTER USER ' || row_name.rolname|| ' SPILL SPACE '''|| row_name.rolspillspace||''';';
            EXECUTE(query_new);
        EXCEPTION
        WHEN OTHERS THEN
            INSERT INTO inplace_upgrade.SpaceLimitSetFail VALUES (query_new);
        END;
        END IF;
    END LOOP;
return record_cnt;
END; $$
LANGUAGE plpgsql NOT FENCED;

call inplace_upgrade.UserSpaceToOrigin();
COMMIT;