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

A simple PL/Tcl function


Now, let's write our first simple Tcl function to make sure that PL/Tcl is installed. We will write a simple factorial calculation function, as shown here:

CREATE OR REPLACE FUNCTION tcl_factorial(integer) RETURNS integer
AS $$
  set i 1; set fact 1
  while {$i <= $1} {
    set fact [expr $fact * $i]
    incr i
  }
  return $fact
$$ LANGUAGE pltcl  STRICT;

This function calculates the factorial of a number in an iterative way. Let's try and run it:

postgres=# SELECT tcl_factorial(5);
 tcl_factorial 
---------------
           120
(1 row)

It works and the function looks similar to other functions we have been writing in PL/pgSQL and PL/Python. The CREATE FUNCTION statement creates a function. It needs a name, function argument type list (you have to use parentheses, even if there are no arguments), a result type, and a language.

The body of the function is just a Tcl script. PostgreSQL passes the body on to a Tcl interpreter to run this subroutine and return the results...