2
$PostgreSQL: pgsql/doc/src/sgml/pltcl.sgml,v 2.33.4.1 2005-01-22 23:05:48 momjian Exp $
6
<title>PL/Tcl - Tcl Procedural Language</title>
8
<indexterm zone="pltcl">
9
<primary>PL/Tcl</primary>
12
<indexterm zone="pltcl">
13
<primary>Tcl</primary>
17
PL/Tcl is a loadable procedural language for the
18
<productname>PostgreSQL</productname> database system
19
that enables the <ulink url="http://www.tcl.tk/">Tcl</ulink>
20
language to be used to write functions and
24
<!-- **** PL/Tcl overview **** -->
26
<sect1 id="pltcl-overview">
27
<title>Overview</title>
30
PL/Tcl offers most of the capabilities a function
31
writer has in the C language, except for some restrictions.
34
The good restriction is that everything is executed in a safe
35
Tcl interpreter. In addition to the limited command set of safe Tcl, only
36
a few commands are available to access the database via SPI and to raise
37
messages via <function>elog()</>. There is no way to access internals of the
38
database server or to gain OS-level access under the permissions of the
39
<productname>PostgreSQL</productname> server process, as a C function can do.
40
Thus, any unprivileged database user may be
41
permitted to use this language.
44
The other, implementation restriction is that Tcl functions cannot
45
be used to create input/output functions for new data types.
48
Sometimes it is desirable to write Tcl functions that are not restricted
49
to safe Tcl. For example, one might want a Tcl function that sends
50
email. To handle these cases, there is a variant of <application>PL/Tcl</> called <literal>PL/TclU</>
51
(for untrusted Tcl). This is the exact same language except that a full
52
Tcl interpreter is used. <emphasis>If <application>PL/TclU</> is used, it must be
53
installed as an untrusted procedural language</emphasis> so that only
54
database superusers can create functions in it. The writer of a <application>PL/TclU</>
55
function must take care that the function cannot be used to do anything
56
unwanted, since it will be able to do anything that could be done by
57
a user logged in as the database administrator.
60
The shared object for the <application>PL/Tcl</> and <application>PL/TclU</> call handlers is
61
automatically built and installed in the
62
<productname>PostgreSQL</productname>
63
library directory if Tcl support is specified
64
in the configuration step of the installation procedure. To install
65
<application>PL/Tcl</> and/or <application>PL/TclU</> in a particular database, use the
66
<command>createlang</command> program, for example
67
<literal>createlang pltcl <replaceable>dbname</></literal> or
68
<literal>createlang pltclu <replaceable>dbname</></literal>.
72
<!-- **** PL/Tcl description **** -->
74
<sect1 id="pltcl-functions">
75
<title>PL/Tcl Functions and Arguments</title>
78
To create a function in the <application>PL/Tcl</> language, use the standard syntax:
81
CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
82
# PL/Tcl function body
86
<application>PL/TclU</> is the same, except that the language has to be specified as
91
The body of the function is simply a piece of Tcl script.
92
When the function is called, the argument values are passed as
93
variables <literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal> to the
94
Tcl script. The result is returned
95
from the Tcl code in the usual way, with a <literal>return</literal>
100
For example, a function
101
returning the greater of two integer values could be defined as:
104
CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS $$
105
if {$1 > $2} {return $1}
107
$$ LANGUAGE pltcl STRICT;
110
Note the clause <literal>STRICT</>, which saves us from
111
having to think about null input values: if a null value is passed, the
112
function will not be called at all, but will just return a null
113
result automatically.
117
In a nonstrict function,
118
if the actual value of an argument is null, the corresponding
119
<literal>$<replaceable>n</replaceable></literal> variable will be set to an empty string.
120
To detect whether a particular argument is null, use the function
121
<literal>argisnull</>. For example, suppose that we wanted <function>tcl_max</function>
122
with one null and one nonnull argument to return the nonnull
123
argument, rather than null:
126
CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS $$
128
if {[argisnull 2]} { return_null }
131
if {[argisnull 2]} { return $1 }
132
if {$1 > $2} {return $1}
140
to return a null value from a PL/Tcl function, execute
141
<literal>return_null</literal>. This can be done whether the
142
function is strict or not.
146
Composite-type arguments are passed to the function as Tcl
147
arrays. The element names of the array are the attribute names
148
of the composite type. If an attribute in the passed row has the
149
null value, it will not appear in the array. Here is an example:
152
CREATE TABLE employee (
158
CREATE FUNCTION overpaid(employee) RETURNS boolean AS $$
159
if {200000.0 < $1(salary)} {
162
if {$1(age) < 30 && 100000.0 < $1(salary)} {
171
There is currently no support for returning a composite-type
172
result value, nor for returning sets.
176
<application>PL/Tcl</> does not currently have full support for
177
domain types: it treats a domain the same as the underlying scalar
178
type. This means that constraints associated with the domain will
179
not be enforced. This is not an issue for function arguments, but
180
it is a hazard if you declare a <application>PL/Tcl</> function
181
as returning a domain type.
186
<sect1 id="pltcl-data">
187
<title>Data Values in PL/Tcl</title>
190
The argument values supplied to a PL/Tcl function's code are simply
191
the input arguments converted to text form (just as if they had been
192
displayed by a <command>SELECT</> statement). Conversely, the
194
command will accept any string that is acceptable input format for
195
the function's declared return type. So, within the PL/Tcl function,
196
all values are just text strings.
201
<sect1 id="pltcl-global">
202
<title>Global Data in PL/Tcl</title>
204
<indexterm zone="pltcl-global">
205
<primary>global data</primary>
206
<secondary>in PL/Tcl</secondary>
211
is useful to have some global data that is held between two
212
calls to a function or is shared between different functions.
213
This is easily done since
214
all PL/Tcl functions executed in one session share the same
215
safe Tcl interpreter. So, any global Tcl variable is accessible to
216
all PL/Tcl function calls and will persist for the duration of the
217
SQL session. (Note that <application>PL/TclU</> functions likewise share
218
global data, but they are in a different Tcl interpreter and cannot
219
communicate with PL/Tcl functions.)
222
To help protect PL/Tcl functions from unintentionally interfering
223
with each other, a global
224
array is made available to each function via the <function>upvar</>
225
command. The global name of this variable is the function's internal
226
name, and the local name is <literal>GD</>. It is recommended that
227
<literal>GD</> be used
228
for persistent private data of a function. Use regular Tcl global
229
variables only for values that you specifically intend to be shared among
234
An example of using <literal>GD</> appears in the
235
<function>spi_execp</function> example below.
239
<sect1 id="pltcl-dbaccess">
240
<title>Database Access from PL/Tcl</title>
243
The following commands are available to access the database from
244
the body of a PL/Tcl function:
249
<term><literal><function>spi_exec</function> <optional role="tcl">-count <replaceable>n</replaceable></optional> <optional role="tcl">-array <replaceable>name</replaceable></optional> <replaceable>command</replaceable> <optional role="tcl"><replaceable>loop-body</replaceable></optional></literal></term>
252
Executes an SQL command given as a string. An error in the command
253
causes an error to be raised. Otherwise, the return value of <function>spi_exec</function>
254
is the number of rows processed (selected, inserted, updated, or
255
deleted) by the command, or zero if the command is a utility
256
statement. In addition, if the command is a <command>SELECT</> statement, the
257
values of the selected columns are placed in Tcl variables as
261
The optional <literal>-count</> value tells
262
<function>spi_exec</function> the maximum number of rows
263
to process in the command. The effect of this is comparable to
264
setting up a query as a cursor and then saying <literal>FETCH <replaceable>n</></>.
267
If the command is a <command>SELECT</> statement, the values of the
268
result columns are placed into Tcl variables named after the columns.
269
If the <literal>-array</> option is given, the column values are
270
instead stored into the named associative array, with the
271
column names used as array indexes.
274
If the command is a <command>SELECT</> statement and no <replaceable>loop-body</>
275
script is given, then only the first row of results are stored into
276
Tcl variables; remaining rows, if any, are ignored. No storing occurs
278
query returns no rows. (This case can be detected by checking the
279
result of <function>spi_exec</function>.) For example,
282
spi_exec "SELECT count(*) AS cnt FROM pg_proc"
285
will set the Tcl variable <literal>$cnt</> to the number of rows in
286
the <structname>pg_proc</> system catalog.
289
If the optional <replaceable>loop-body</> argument is given, it is
290
a piece of Tcl script that is executed once for each row in the
291
query result. (<replaceable>loop-body</> is ignored if the given
292
command is not a <command>SELECT</>.) The values of the current row's columns
293
are stored into Tcl variables before each iteration. For example,
296
spi_exec -array C "SELECT * FROM pg_class" {
297
elog DEBUG "have table $C(relname)"
301
will print a log message for every row of <literal>pg_class</>. This
302
feature works similarly to other Tcl looping constructs; in
303
particular <literal>continue</> and <literal>break</> work in the
304
usual way inside the loop body.
307
If a column of a query result is null, the target
308
variable for it is <quote>unset</> rather than being set.
314
<term><function>spi_prepare</function> <replaceable>query</replaceable> <replaceable>typelist</replaceable></term>
317
Prepares and saves a query plan for later execution. The
318
saved plan will be retained for the life of the current
319
session.<indexterm><primary>preparing a query</><secondary>in
323
The query may use parameters, that is, placeholders for
324
values to be supplied whenever the plan is actually executed.
325
In the query string, refer to parameters
326
by the symbols <literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal>.
327
If the query uses parameters, the names of the parameter types
328
must be given as a Tcl list. (Write an empty list for
329
<replaceable>typelist</replaceable> if no parameters are used.)
330
Presently, the parameter types must be identified by the internal
331
type names shown in the system table <literal>pg_type</>; for example <literal>int4</> not
335
The return value from <function>spi_prepare</function> is a query ID
336
to be used in subsequent calls to <function>spi_execp</function>. See
337
<function>spi_execp</function> for an example.
343
<term><literal><function>spi_execp</> <optional role="tcl">-count <replaceable>n</replaceable></optional> <optional role="tcl">-array <replaceable>name</replaceable></optional> <optional role="tcl">-nulls <replaceable>string</replaceable></optional> <replaceable>queryid</replaceable> <optional role="tcl"><replaceable>value-list</replaceable></optional> <optional role="tcl"><replaceable>loop-body</replaceable></optional></literal></term>
346
Executes a query previously prepared with <function>spi_prepare</>.
347
<replaceable>queryid</replaceable> is the ID returned by
348
<function>spi_prepare</>. If the query references parameters,
349
a <replaceable>value-list</replaceable> must be supplied. This
350
is a Tcl list of actual values for the parameters. The list must be
351
the same length as the parameter type list previously given to
352
<function>spi_prepare</>. Omit <replaceable>value-list</replaceable>
353
if the query has no parameters.
356
The optional value for <literal>-nulls</> is a string of spaces and
357
<literal>'n'</> characters telling <function>spi_execp</function>
358
which of the parameters are null values. If given, it must have exactly the
359
same length as the <replaceable>value-list</replaceable>. If it
360
is not given, all the parameter values are nonnull.
363
Except for the way in which the query and its parameters are specified,
364
<function>spi_execp</> works just like <function>spi_exec</>.
365
The <literal>-count</>, <literal>-array</>, and
366
<replaceable>loop-body</replaceable> options are the same,
367
and so is the result value.
370
Here's an example of a PL/Tcl function using a prepared plan:
373
CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS $$
374
if {![ info exists GD(plan) ]} {
375
# prepare the saved plan on the first call
376
set GD(plan) [ spi_prepare \
377
"SELECT count(*) AS cnt FROM t1 WHERE num >= \$1 AND num <= \$2" \
380
spi_execp -count 1 $GD(plan) [ list $1 $2 ]
385
We need backslashes inside the query string given to
386
<function>spi_prepare</> to ensure that the
387
<literal>$<replaceable>n</replaceable></> markers will be passed
388
through to <function>spi_prepare</> as-is, and not replaced by Tcl
389
variable substitution.
397
<primary>spi_lastoid</primary>
399
<term><function>spi_lastoid</></term>
402
Returns the OID of the row inserted by the last
403
<function>spi_exec</> or <function>spi_execp</>,
404
if the command was a single-row <command>INSERT</>. (If not, you get zero.)
410
<term><function>quote</> <replaceable>string</replaceable></term>
413
Doubles all occurrences of single quote and backslash characters
414
in the given string. This may be used to safely quote strings
415
that are to be inserted into SQL commands given
416
to <function>spi_exec</function> or
417
<function>spi_prepare</function>.
418
For example, think about an SQL command string like
421
"SELECT '$val' AS ret"
424
where the Tcl variable <literal>val</> actually contains
425
<literal>doesn't</literal>. This would result
426
in the final command string
429
SELECT 'doesn't' AS ret
432
which would cause a parse error during
433
<function>spi_exec</function> or
434
<function>spi_prepare</function>.
435
To work properly, the submitted command should contain
438
SELECT 'doesn''t' AS ret
441
which can be formed in PL/Tcl using
444
"SELECT '[ quote $val ]' AS ret"
447
One advantage of <function>spi_execp</function> is that you don't
448
have to quote parameter values like this, since the parameters are never
449
parsed as part of an SQL command string.
456
<primary>elog</primary>
457
<secondary>in PL/Tcl</secondary>
459
<term><function>elog</> <replaceable>level</replaceable> <replaceable>msg</replaceable></term>
462
Emits a log or error message. Possible levels are
463
<literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
464
<literal>NOTICE</>, <literal>WARNING</>, <literal>ERROR</>, and
465
<literal>FATAL</>. <literal>ERROR</>
466
raises an error condition; if this is not trapped by the surrounding
467
Tcl code, the error propagates out to the calling query, causing
468
the current transaction or subtransaction to be aborted. This
469
is effectively the same as the Tcl <literal>error</> command.
470
<literal>FATAL</> aborts the transaction and causes the current
471
session to shut down. (There is probably no good reason to use
472
this error level in PL/Tcl functions, but it's provided for
473
completeness.) The other levels only generate messages of different
475
Whether messages of a particular priority are reported to the client,
476
written to the server log, or both is controlled by the
477
<xref linkend="guc-log-min-messages"> and
478
<xref linkend="guc-client-min-messages"> configuration
479
variables. See <xref linkend="runtime-config"> for more
490
<sect1 id="pltcl-trigger">
491
<title>Trigger Procedures in PL/Tcl</title>
494
<primary>trigger</primary>
495
<secondary>in PL/Tcl</secondary>
499
Trigger procedures can be written in PL/Tcl.
500
<productname>PostgreSQL</productname> requires that a procedure that is to be called
501
as a trigger must be declared as a function with no arguments
502
and a return type of <literal>trigger</>.
505
The information from the trigger manager is passed to the procedure body
506
in the following variables:
511
<term><varname>$TG_name</varname></term>
514
The name of the trigger from the <command>CREATE TRIGGER</command> statement.
520
<term><varname>$TG_relid</varname></term>
523
The object ID of the table that caused the trigger procedure
530
<term><varname>$TG_relatts</varname></term>
533
A Tcl list of the table column names, prefixed with an empty list
534
element. So looking up a column name in the list with <application>Tcl</>'s
535
<function>lsearch</> command returns the element's number starting
536
with 1 for the first column, the same way the columns are customarily
537
numbered in <productname>PostgreSQL</productname>. (Empty list
538
elements also appear in the positions of columns that have been
539
dropped, so that the attribute numbering is correct for columns
546
<term><varname>$TG_when</varname></term>
549
The string <literal>BEFORE</> or <literal>AFTER</> depending on the
550
type of trigger call.
556
<term><varname>$TG_level</varname></term>
559
The string <literal>ROW</> or <literal>STATEMENT</> depending on the
560
type of trigger call.
566
<term><varname>$TG_op</varname></term>
569
The string <literal>INSERT</>, <literal>UPDATE</>, or
570
<literal>DELETE</> depending on the type of trigger call.
576
<term><varname>$NEW</varname></term>
579
An associative array containing the values of the new table
580
row for <command>INSERT</> or <command>UPDATE</> actions, or
581
empty for <command>DELETE</>. The array is indexed by column
582
name. Columns that are null will not appear in the array.
588
<term><varname>$OLD</varname></term>
591
An associative array containing the values of the old table
592
row for <command>UPDATE</> or <command>DELETE</> actions, or
593
empty for <command>INSERT</>. The array is indexed by column
594
name. Columns that are null will not appear in the array.
600
<term><varname>$args</varname></term>
603
A Tcl list of the arguments to the procedure as given in the
604
<command>CREATE TRIGGER</command> statement. These arguments are also accessible as
605
<literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal> in the procedure body.
614
The return value from a trigger procedure can be one of the strings
615
<literal>OK</> or <literal>SKIP</>, or a list as returned by the
616
<literal>array get</> Tcl command. If the return value is <literal>OK</>,
617
the operation (<command>INSERT</>/<command>UPDATE</>/<command>DELETE</>) that fired the trigger will proceed
618
normally. <literal>SKIP</> tells the trigger manager to silently suppress
619
the operation for this row. If a list is returned, it tells PL/Tcl to
620
return a modified row to the trigger manager that will be inserted
621
instead of the one given in <varname>$NEW</>. (This works for <command>INSERT</> and <command>UPDATE</>
622
only.) Needless to say that all this is only meaningful when the trigger
623
is <literal>BEFORE</> and <command>FOR EACH ROW</>; otherwise the return value is ignored.
626
Here's a little example trigger procedure that forces an integer value
627
in a table to keep track of the number of updates that are performed on the
628
row. For new rows inserted, the value is initialized to 0 and then
629
incremented on every update operation.
632
CREATE FUNCTION trigfunc_modcount() RETURNS trigger AS $$
645
return [array get NEW]
648
CREATE TABLE mytab (num integer, description text, modcnt integer);
650
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
651
FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');
654
Notice that the trigger procedure itself does not know the column
655
name; that's supplied from the trigger arguments. This lets the
656
trigger procedure be reused with different tables.
660
<sect1 id="pltcl-unknown">
661
<title>Modules and the <function>unknown</> command</title>
663
PL/Tcl has support for autoloading Tcl code when used.
664
It recognizes a special table, <literal>pltcl_modules</>, which
665
is presumed to contain modules of Tcl code. If this table
666
exists, the module <literal>unknown</> is fetched from the table
667
and loaded into the Tcl interpreter immediately after creating
671
While the <literal>unknown</> module could actually contain any
672
initialization script you need, it normally defines a Tcl
673
<function>unknown</> procedure that is invoked whenever Tcl does
674
not recognize an invoked procedure name. <application>PL/Tcl</>'s standard version
675
of this procedure tries to find a module in <literal>pltcl_modules</>
676
that will define the required procedure. If one is found, it is
677
loaded into the interpreter, and then execution is allowed to
678
proceed with the originally attempted procedure call. A
679
secondary table <literal>pltcl_modfuncs</> provides an index of
680
which functions are defined by which modules, so that the lookup
684
The <productname>PostgreSQL</productname> distribution includes
685
support scripts to maintain these tables:
686
<command>pltcl_loadmod</>, <command>pltcl_listmod</>,
687
<command>pltcl_delmod</>, as well as source for the standard
688
<literal>unknown</> module in <filename>share/unknown.pltcl</>. This module
690
into each database initially to support the autoloading mechanism.
693
The tables <literal>pltcl_modules</> and <literal>pltcl_modfuncs</>
694
must be readable by all, but it is wise to make them owned and
695
writable only by the database administrator.
699
<sect1 id="pltcl-procnames">
700
<title>Tcl Procedure Names</title>
703
In <productname>PostgreSQL</productname>, one and the
704
same function name can be used for
705
different functions as long as the number of arguments or their types
706
differ. Tcl, however, requires all procedure names to be distinct.
707
PL/Tcl deals with this by making the internal Tcl procedure names contain
709
ID of the function from the system table <structname>pg_proc</> as part of their name. Thus,
710
<productname>PostgreSQL</productname> functions with the same name
711
and different argument types will be different Tcl procedures, too. This
712
is not normally a concern for a PL/Tcl programmer, but it might be visible
719
<!-- Keep this comment at the end of the file
724
sgml-minimize-attributes:nil
725
sgml-always-quote-attributes:t
728
sgml-parent-document:nil
729
sgml-default-dtd-file:"./reference.ced"
730
sgml-exposed-tags:nil
731
sgml-local-catalogs:("/usr/lib/sgml/catalog")
732
sgml-local-ecat-files:nil