Database Reference
In-Depth Information
CREATE FUNCTION even_numbers_from_list(up_to
int)
RETURNS SETOF int
AS $$
return range(0,up_to,2)
$$ LANGUAGE plpythonu;
The list here is returned by a built-in Python function called range , which returns a
result of all even numbers below the argument. This gets returned as a table of in-
tegers, one integer per row from the PostgreSQL function. If the RETURNS clause of
the function definition would say int[] instead of SETOF int , the same function
would return a single number of even integers as a PostgreSQL array.
The next function returns a similar result using a generator and returning both the
even number and the odd one following it. Also, notice the different PostgreSQL syn-
tax RETURNS TABLE(...) used this time for defining the return set:
CREATE FUNCTION
even_numbers_from_generator(up_to int)
RETURNS TABLE (even int, odd int)
AS $$
return ((i,i+1) for i in xrange(0,up_to,2))
$$ LANGUAGE plpythonu;
The generator is constructed using a generator expression ( x for x in <seq> ).
Finally, the function is defined using a generator using and explicit yield syntax,
and yet another PostgreSQL syntax is used for returning SETOF RECORD with the
record structure defined this time by OUT parameters:
CREATE FUNCTION even_numbers_with_yield(up_to
int,
OUT even
int,
OUT odd
int)
RETURNS SETOF RECORD
Search WWH ::




Custom Search