The use of so called “procedural languages” in PostgreSQL allows the user to write user-defined functions in other languages than SQL or C. Since every query is sent to the server, the database server has to know how to interpret and handle function statements. As the PostgreSQL documentation describes, the function handler itself is a C language function compiled into a shared object and loaded on demand. All you have to do is to install the language into your database. Besides that you’ll have to install the pre-compiled shared objects on your system. On my system (Debian 5.0) I had to install the postgresql-plperl
package. Afterwars I connected to the database and typed:
|
|
Of course you’ll have to look up for the right file path in order to work. Finally I was able to use the language plpgsql
in my functions. If you need help installing languages just check out the PostgreSQL documentation (it helped me too).
Polymorphic types
When speaking of polymorphism in PostgreSQL, we actually refer to the polymorphic functions. So what’s the difference between a polymorphic type and a polymorphic function? They’re related to each other. In fact every function declared to use polymorphic types is called as a polymorphic function. These types (pseudo-types) are anyelement
and anyarray
. So when arguments of these types are passed to a function, it can handle with different data types. Imagine a function called equal
that compares two arguments and returns a boolean:
|
|
equal
will take 2 input values of the SAME data type. Otherwise how could you e.g. compare a string to an integer? Read more.
Getting started
I’ll use following employees table:
|
|
Then we insert some new data into the table:
|
|
t_employee
will now contain:
|
|
In the next step we’ll try to write a function which returns a SETOF containing our data.
SETOF vs. Array
Now we need a function which returns our data as a SETOF. In my function I can declare l_row
of type t_employee
(see below). In this variable data is structured as in the table t_employee
. So far, no big deal. Just let us have a look at the function:
|
|
Okay. But as you might have noticed, the purpose of this howto ist to show you how to get a SETOF from an array. Therefor we need some array. We’ll modify get_employees
in this way:
|
|
IN the next step we’ll have to extract SETOF data from the array. Since you can’t do that with built-in Postgres functions, we’ll need some auxiliary function:
|
|
I hope you have noticed the anyarray
which is given as a parameter to the function. So you can use unnest
for every type of array. That’s the great point when using polymorphic functions: You have some kind of generic function and you can use it for all arrays. Well having this function implemented, we can now modify get_employees
:
|
|