--
-- cmp_pg_version/1
--
create or replace function cmp_pg_version(
  p__version character varying
) returns int4 as $$

DECLARE
    pg_version integer[];
    user_pg_version integer[];
    index integer;
    ret_val integer;
    i integer;
BEGIN
    ret_val = 0;

    user_pg_version := string_to_array(trim(p__version),'.')::int[];
    select string_to_array(setting, '.')::int[] into pg_version from pg_settings where name = 'server_version';


    for index in array_length(user_pg_version, 1) + 1..array_length(pg_version, 1) loop
        user_pg_version[index] := 0;
    end loop;

    index := 1;

    while (index <= array_length(pg_version, 1) and ret_val = 0) loop
        if user_pg_version[index] > pg_version[index] then
            ret_val := -1;
    elsif user_pg_version[index] < pg_version[index] then
            ret_val := 1;
        end if;
        index := index + 1;
    end loop;

    return ret_val;
END;

$$ language plpgsql;