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

Get PostgreSQL Server Programming - Second Edition 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.