Book Image

PostgreSQL Server Programming - Second Edition

Book Image

PostgreSQL Server Programming - Second Edition

Overview of this book

Table of Contents (21 chapters)
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Why untrusted?


PostgreSQL's ability to use an untrusted language is a powerful way to perform some non-traditional things from database functions. Creating these functions in a PL is a task of smaller magnitude than writing an extension function in C. For example, a function to look up a hostname for an IP address is only a few lines in PL/PythonU:

CREATE LANGUAGE plpythonu;
CREATE FUNCTION gethostbyname(hostname text) 
  RETURNS inet
AS $$
  import socket
  return socket.gethostbyname(hostname)
$$ LANGUAGE plpythonu SECURITY DEFINER;

You can test it immediately after creating the function by using psql:

hannu=# SELECT gethostbyname('www.postgresql.org');
 gethostbyname  
----------------
 98.129.198.126
(1 row)

Creating the same function in the most untrusted language, C, involves writing tens of lines of boilerplate code, worrying about memory leaks, and all the other problems coming from writing code in a low-level language. While we will look at extending PostgreSQL in C in the next chapter...