Skip to Content
Mastering PostgreSQL 12 - Third Edition
book

Mastering PostgreSQL 12 - Third Edition

by Hans-Jürgen Schönig
November 2019
Beginner to intermediate
470 pages
11h 59m
English
Packt Publishing
Content preview from Mastering PostgreSQL 12 - Third Edition

Using the SPI interface

Like all procedural languages, PL/Python gives you access to the SPI interface. The following example shows how numbers can be added up:

CREATE FUNCTION add_numbers(rows_desired integer)  
  RETURNS integer AS 
$$ 
mysum  = 0 
 
cursor = plpy.cursor("SELECT * FROM 
  generate_series(1, %d) AS id" % (rows_desired)) 
 
while  True: 
  rows  = cursor.fetch(rows_desired) 
  if not rows: 
    break 
 
  for row in rows: 
    mysum  += row['id'] 
return mysum 
$$ LANGUAGE 'plpythonu'; 

When you try this example out, make sure that the call to the cursor is actually a single line. Python is all about indentation, so it does make a difference if your code consists of one or two lines.

Once the cursor has been created, we can loop over it and add up those numbers. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering PostgreSQL 11 - Second Edition

Mastering PostgreSQL 11 - Second Edition

Hans-Jürgen Schönig
Learning PostgreSQL 11 - Third Edition

Learning PostgreSQL 11 - Third Edition

Christopher Travers, Andrey Volkov
PostgreSQL Server Programming - Second Edition

PostgreSQL Server Programming - Second Edition

Usama Dar, Hannu Krosing, Jim Mlodgenski, Kirk Roybal

Publisher Resources

ISBN: 9781838988821Supplemental Content