create or replace function agg_last(
    IN p_state       anyarray,
    IN p_new_element anyelement,
    IN p_limit       int4
    )
    returns anyarray
    language sql
    as $$
select ( case
    when array_length( p_state, 1 ) >= p_limit
        then p_state[(array_upper(p_state, 1) - p_limit + 2):array_upper(p_state, 1)]
    else
        p_state
    end ) || p_new_element;
$$;
