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 ...

Get Mastering PostgreSQL 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.