Writing simple PL/Python code

In this section, you will learn to write simple Python procedures. The example discussed here is quite simple: if you are visiting a client by car in Austria, you can deduct 42 euro cents per kilometer as expenses in order to reduce your income tax. So, what the function does is to take the number of kilometers and return the amount of money we can deduct from our tax bill. Here is how it works:

CREATE OR REPLACE FUNCTION calculate_deduction(km float)  
  RETURNS numeric AS 
$$ 
if   km <= 0: 
  elog(ERROR, 'invalid number of kilometers') 
else: 

return km * 0.42

$$ LANGUAGE 'plpythonu';

The function ensures that only positive values are accepted. Finally, the result is calculated and returned. As you can see, the way a Python function is passed to PostgreSQL does not really differ from Perl or PL/pgSQL.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset