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

Untrusted Tcl


Using untrusted Tcl (pltclu) is one of the oldest ways to do things outside the database. pltclu is executed using a normal Tcl interpreter and is pretty much free to do anything you'd like. Tcl has a lot of commands available to interact with the operating system and the environment. We will now take a look at a few simple examples.

The first example, reads the contents of the file and returns them as text, as shown in the following code:

CREATE OR REPLACE FUNCTION read_file(text) RETURNS text
AS $$
  set fptr [open $1]
  set file_data [read $fptr]
  close $fptr #close the file as it is already read
  return $file_data
$$ LANGUAGE pltclu;

The function is quite simple; it opens a file provided as a parameter, reads all its contents at once, and returns the text.

Let's run the preceding function:

postgres=# select read_file('/usr/local/pgsql/data/postmaster.pid');
       read_file       
-----------------------
 61588                +
 /usr/local/pgsql/data+
 1401041744         ...