In: |
plruby.rb
|
To create a function in the PLRuby language use the syntax
CREATE FUNCTION funcname(arguments_type) RETURNS type AS ' # PLRuby function body ' LANGUAGE 'plruby';
when calling the function in a query, the arguments are given as string values in the array args. To create a little max function returning the higher of two int4 values write :
CREATE FUNCTION ruby_max(int4, int4) RETURNS int4 AS ' if args[0].to_i > args[1].to_i return args[0] else return args[1] end ' LANGUAGE 'plruby';
Tuple arguments are given as hash. Here is an example that defines the overpaid_2 function (as found in the older Postgres documentation) in PLRuby.
CREATE FUNCTION overpaid_2 (EMP) RETURNS bool AS ' args[0]["salary"].to_f > 200000 || (args[0]["salary"].to_f > 100000 && args[0]["age"].to_i < 30) ' LANGUAGE 'plruby';
For example to define a function (int4[], int4) and return int4[], in version < 7.4 you write
CREATE FUNCTION ruby_int4_accum(_int4, int4) RETURNS _int4 AS ' if /\\{(\\d+),(\\d+)\\}/ =~ args[0] a, b = $1, $2 newsum = a.to_i + args[1].to_i newcnt = b.to_i + 1 else raise "unexpected value #{args[0]}" end "{#{newsum},#{newcnt}}" ' LANGUAGE 'plruby';
This must now (>= 7.4) be written
CREATE FUNCTION ruby_int4_accum(_int4, int4) RETURNS _int4 AS ' a = args[0] [a[0].to_i + args[1].to_i, a[1].to_i + 1] ' LANGUAGE 'plruby';