~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to doc/src/sgml/pltcl.sgml

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!--
 
2
$PostgreSQL: pgsql/doc/src/sgml/pltcl.sgml,v 2.33.4.1 2005-01-22 23:05:48 momjian Exp $
 
3
-->
 
4
 
 
5
 <chapter id="pltcl">
 
6
  <title>PL/Tcl - Tcl Procedural Language</title>
 
7
 
 
8
  <indexterm zone="pltcl">
 
9
   <primary>PL/Tcl</primary>
 
10
  </indexterm>
 
11
 
 
12
  <indexterm zone="pltcl">
 
13
   <primary>Tcl</primary>
 
14
  </indexterm>
 
15
 
 
16
  <para>
 
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
 
21
   trigger procedures.
 
22
  </para>
 
23
 
 
24
  <!-- **** PL/Tcl overview **** -->
 
25
 
 
26
  <sect1 id="pltcl-overview">
 
27
   <title>Overview</title>
 
28
 
 
29
   <para>
 
30
    PL/Tcl offers most of the capabilities a function
 
31
    writer has in the C language, except for some restrictions.
 
32
   </para>
 
33
   <para>
 
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.
 
42
   </para>
 
43
   <para>
 
44
    The other, implementation restriction is that Tcl functions cannot
 
45
    be used to create input/output functions for new data types.
 
46
   </para>
 
47
   <para>
 
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.
 
58
   </para>
 
59
   <para>
 
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>.
 
69
   </para>
 
70
  </sect1>
 
71
 
 
72
  <!-- **** PL/Tcl description **** -->
 
73
 
 
74
   <sect1 id="pltcl-functions">
 
75
    <title>PL/Tcl Functions and Arguments</title>
 
76
 
 
77
    <para>
 
78
     To create a function in the <application>PL/Tcl</> language, use the standard syntax:
 
79
 
 
80
<programlisting>
 
81
CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS $$
 
82
    # PL/Tcl function body
 
83
$$ LANGUAGE pltcl;
 
84
</programlisting>
 
85
 
 
86
     <application>PL/TclU</> is the same, except that the language has to be specified as
 
87
     <literal>pltclu</>.
 
88
    </para>
 
89
 
 
90
    <para>
 
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>
 
96
     statement.
 
97
    </para>
 
98
 
 
99
    <para>
 
100
     For example, a function
 
101
     returning the greater of two integer values could be defined as:
 
102
 
 
103
<programlisting>
 
104
CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS $$
 
105
    if {$1 &gt; $2} {return $1}
 
106
    return $2
 
107
$$ LANGUAGE pltcl STRICT;
 
108
</programlisting>
 
109
 
 
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.
 
114
    </para>
 
115
 
 
116
    <para>
 
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:
 
124
 
 
125
<programlisting>
 
126
CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS $$
 
127
    if {[argisnull 1]} {
 
128
        if {[argisnull 2]} { return_null }
 
129
        return $2
 
130
    }
 
131
    if {[argisnull 2]} { return $1 }
 
132
    if {$1 &gt; $2} {return $1}
 
133
    return $2
 
134
$$ LANGUAGE pltcl;
 
135
</programlisting>
 
136
    </para>
 
137
 
 
138
    <para>
 
139
     As shown above,
 
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.
 
143
    </para>
 
144
 
 
145
    <para>
 
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:
 
150
 
 
151
<programlisting>
 
152
CREATE TABLE employee (
 
153
    name text,
 
154
    salary integer,
 
155
    age integer
 
156
);
 
157
 
 
158
CREATE FUNCTION overpaid(employee) RETURNS boolean AS $$
 
159
    if {200000.0 &lt; $1(salary)} {
 
160
        return "t"
 
161
    }
 
162
    if {$1(age) &lt; 30 && 100000.0 &lt; $1(salary)} {
 
163
        return "t"
 
164
    }
 
165
    return "f"
 
166
$$ LANGUAGE pltcl;
 
167
</programlisting>
 
168
    </para>
 
169
 
 
170
    <para>
 
171
     There is currently no support for returning a composite-type
 
172
     result value, nor for returning sets.
 
173
    </para>
 
174
 
 
175
    <para>
 
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.
 
182
    </para>
 
183
 
 
184
   </sect1>
 
185
 
 
186
   <sect1 id="pltcl-data">
 
187
    <title>Data Values in PL/Tcl</title>
 
188
 
 
189
    <para>
 
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
 
193
     <literal>return</>
 
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.
 
197
    </para>
 
198
 
 
199
   </sect1>
 
200
 
 
201
   <sect1 id="pltcl-global">
 
202
    <title>Global Data in PL/Tcl</title>
 
203
 
 
204
    <indexterm zone="pltcl-global">
 
205
     <primary>global data</primary>
 
206
     <secondary>in PL/Tcl</secondary>
 
207
    </indexterm>
 
208
 
 
209
    <para>
 
210
     Sometimes it
 
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.)
 
220
    </para>
 
221
    <para>
 
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
 
230
     multiple functions.
 
231
    </para>
 
232
 
 
233
    <para>
 
234
     An example of using <literal>GD</> appears in the
 
235
     <function>spi_execp</function> example below.
 
236
    </para>
 
237
   </sect1>
 
238
 
 
239
   <sect1 id="pltcl-dbaccess">
 
240
    <title>Database Access from PL/Tcl</title>
 
241
 
 
242
    <para>
 
243
     The following commands are available to access the database from
 
244
     the body of a PL/Tcl function:
 
245
 
 
246
    <variablelist>
 
247
 
 
248
     <varlistentry>
 
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>
 
250
      <listitem>
 
251
       <para>
 
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
 
258
        described below.
 
259
       </para>
 
260
       <para>
 
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</></>.
 
265
       </para>
 
266
       <para>
 
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.
 
272
       </para>
 
273
       <para>
 
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
 
277
        if the 
 
278
        query returns no rows.  (This case can be detected by checking the
 
279
        result of <function>spi_exec</function>.)  For example,
 
280
 
 
281
<programlisting>
 
282
spi_exec "SELECT count(*) AS cnt FROM pg_proc"
 
283
</programlisting>
 
284
 
 
285
        will set the Tcl variable <literal>$cnt</> to the number of rows in
 
286
        the <structname>pg_proc</> system catalog.
 
287
       </para>
 
288
       <para>
 
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,
 
294
 
 
295
<programlisting>
 
296
spi_exec -array C "SELECT * FROM pg_class" {
 
297
    elog DEBUG "have table $C(relname)"
 
298
}
 
299
</programlisting>
 
300
 
 
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.
 
305
       </para>
 
306
       <para>
 
307
        If a column of a query result is null, the target
 
308
        variable for it is <quote>unset</> rather than being set.
 
309
       </para>
 
310
      </listitem>
 
311
     </varlistentry>
 
312
 
 
313
     <varlistentry>
 
314
      <term><function>spi_prepare</function> <replaceable>query</replaceable> <replaceable>typelist</replaceable></term>
 
315
      <listitem>
 
316
       <para>
 
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
 
320
        PL/Tcl</></>
 
321
       </para>
 
322
       <para>
 
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
 
332
        <literal>integer</>.
 
333
       </para>
 
334
       <para>
 
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.
 
338
       </para>
 
339
      </listitem>
 
340
     </varlistentry>
 
341
 
 
342
     <varlistentry>
 
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>
 
344
      <listitem>
 
345
       <para>
 
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.
 
354
       </para>
 
355
       <para>
 
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.
 
361
       </para>
 
362
       <para>
 
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.
 
368
       </para>
 
369
       <para>
 
370
        Here's an example of a PL/Tcl function using a prepared plan:
 
371
 
 
372
<programlisting>
 
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 &gt;= \$1 AND num &lt;= \$2" \
 
378
                [ list int4 int4 ] ]
 
379
    }
 
380
    spi_execp -count 1 $GD(plan) [ list $1 $2 ]
 
381
    return $cnt
 
382
$$ LANGUAGE pltcl;
 
383
</programlisting>
 
384
 
 
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.
 
390
 
 
391
       </para>
 
392
      </listitem>
 
393
     </varlistentry>
 
394
 
 
395
     <varlistentry>
 
396
      <indexterm>
 
397
       <primary>spi_lastoid</primary>
 
398
      </indexterm>
 
399
      <term><function>spi_lastoid</></term>
 
400
      <listitem>
 
401
       <para>
 
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.)
 
405
       </para>
 
406
      </listitem>
 
407
     </varlistentry>
 
408
 
 
409
     <varlistentry>
 
410
      <term><function>quote</> <replaceable>string</replaceable></term>
 
411
      <listitem>
 
412
       <para>
 
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
 
419
 
 
420
<programlisting>
 
421
"SELECT '$val' AS ret"
 
422
</programlisting>
 
423
 
 
424
        where the Tcl variable <literal>val</> actually contains
 
425
        <literal>doesn't</literal>. This would result
 
426
        in the final command string
 
427
 
 
428
<programlisting>
 
429
SELECT 'doesn't' AS ret
 
430
</programlisting>
 
431
 
 
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
 
436
 
 
437
<programlisting>
 
438
SELECT 'doesn''t' AS ret
 
439
</programlisting>
 
440
 
 
441
        which can be formed in PL/Tcl using
 
442
 
 
443
<programlisting>
 
444
"SELECT '[ quote $val ]' AS ret"
 
445
</programlisting>
 
446
 
 
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.
 
450
       </para>
 
451
      </listitem>
 
452
     </varlistentry>
 
453
 
 
454
     <varlistentry>
 
455
      <indexterm>
 
456
       <primary>elog</primary>
 
457
       <secondary>in PL/Tcl</secondary>
 
458
      </indexterm>
 
459
      <term><function>elog</> <replaceable>level</replaceable> <replaceable>msg</replaceable></term>
 
460
      <listitem>
 
461
       <para>
 
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
 
474
        priority levels.
 
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
 
480
        information.
 
481
       </para>
 
482
      </listitem>
 
483
     </varlistentry>
 
484
 
 
485
    </variablelist>
 
486
    </para>
 
487
 
 
488
   </sect1>
 
489
 
 
490
   <sect1 id="pltcl-trigger">
 
491
    <title>Trigger Procedures in PL/Tcl</title>
 
492
 
 
493
    <indexterm>
 
494
     <primary>trigger</primary>
 
495
     <secondary>in PL/Tcl</secondary>
 
496
    </indexterm>
 
497
 
 
498
    <para>
 
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</>.
 
503
    </para>
 
504
    <para>
 
505
     The information from the trigger manager is passed to the procedure body
 
506
     in the following variables:
 
507
 
 
508
     <variablelist>
 
509
 
 
510
      <varlistentry>
 
511
       <term><varname>$TG_name</varname></term>
 
512
       <listitem>
 
513
        <para>
 
514
         The name of the trigger from the <command>CREATE TRIGGER</command> statement.
 
515
        </para>
 
516
       </listitem>
 
517
      </varlistentry>
 
518
 
 
519
      <varlistentry>
 
520
       <term><varname>$TG_relid</varname></term>
 
521
       <listitem>
 
522
        <para>
 
523
         The object ID of the table that caused the trigger procedure
 
524
         to be invoked.
 
525
        </para>
 
526
       </listitem>
 
527
      </varlistentry>
 
528
 
 
529
      <varlistentry>
 
530
       <term><varname>$TG_relatts</varname></term>
 
531
       <listitem>
 
532
        <para>
 
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
 
540
         to their right.)
 
541
        </para>
 
542
       </listitem>
 
543
      </varlistentry>
 
544
 
 
545
      <varlistentry>
 
546
       <term><varname>$TG_when</varname></term>
 
547
       <listitem>
 
548
        <para>
 
549
         The string <literal>BEFORE</> or <literal>AFTER</> depending on the
 
550
         type of trigger call.
 
551
        </para>
 
552
       </listitem>
 
553
      </varlistentry>
 
554
 
 
555
      <varlistentry>
 
556
       <term><varname>$TG_level</varname></term>
 
557
       <listitem>
 
558
        <para>
 
559
         The string <literal>ROW</> or <literal>STATEMENT</> depending on the
 
560
         type of trigger call.
 
561
        </para>
 
562
       </listitem>
 
563
      </varlistentry>
 
564
 
 
565
      <varlistentry>
 
566
       <term><varname>$TG_op</varname></term>
 
567
       <listitem>
 
568
        <para>
 
569
         The string <literal>INSERT</>, <literal>UPDATE</>, or
 
570
         <literal>DELETE</> depending on the type of trigger call.
 
571
        </para>
 
572
       </listitem>
 
573
      </varlistentry>
 
574
 
 
575
      <varlistentry>
 
576
       <term><varname>$NEW</varname></term>
 
577
       <listitem>
 
578
        <para>
 
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.
 
583
        </para>
 
584
       </listitem>
 
585
      </varlistentry>
 
586
 
 
587
      <varlistentry>
 
588
       <term><varname>$OLD</varname></term>
 
589
       <listitem>
 
590
        <para>
 
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.
 
595
        </para>
 
596
       </listitem>
 
597
      </varlistentry>
 
598
 
 
599
      <varlistentry>
 
600
       <term><varname>$args</varname></term>
 
601
       <listitem>
 
602
        <para>
 
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.
 
606
        </para>
 
607
       </listitem>
 
608
      </varlistentry>
 
609
 
 
610
     </variablelist>
 
611
    </para>
 
612
 
 
613
    <para>
 
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.
 
624
    </para>
 
625
    <para>
 
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.
 
630
 
 
631
<programlisting>
 
632
CREATE FUNCTION trigfunc_modcount() RETURNS trigger AS $$
 
633
    switch $TG_op {
 
634
        INSERT {
 
635
            set NEW($1) 0
 
636
        }
 
637
        UPDATE {
 
638
            set NEW($1) $OLD($1)
 
639
            incr NEW($1)
 
640
        }
 
641
        default {
 
642
            return OK
 
643
        }
 
644
    }
 
645
    return [array get NEW]
 
646
$$ LANGUAGE pltcl;
 
647
 
 
648
CREATE TABLE mytab (num integer, description text, modcnt integer);
 
649
 
 
650
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
 
651
    FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');
 
652
</programlisting>
 
653
 
 
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.
 
657
    </para>
 
658
   </sect1>
 
659
 
 
660
   <sect1 id="pltcl-unknown">
 
661
       <title>Modules and the <function>unknown</> command</title>
 
662
       <para>
 
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
 
668
        the interpreter.
 
669
       </para>
 
670
       <para>
 
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
 
681
        is reasonably quick.
 
682
       </para>
 
683
       <para>
 
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
 
689
        must be loaded
 
690
        into each database initially to support the autoloading mechanism.
 
691
       </para>
 
692
       <para>
 
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.
 
696
       </para>
 
697
   </sect1>
 
698
 
 
699
   <sect1 id="pltcl-procnames">
 
700
    <title>Tcl Procedure Names</title>
 
701
 
 
702
    <para>
 
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
 
708
     the object 
 
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
 
713
     when debugging.
 
714
    </para>
 
715
 
 
716
   </sect1>
 
717
 </chapter>
 
718
 
 
719
<!-- Keep this comment at the end of the file
 
720
Local variables:
 
721
mode:sgml
 
722
sgml-omittag:nil
 
723
sgml-shorttag:t
 
724
sgml-minimize-attributes:nil
 
725
sgml-always-quote-attributes:t
 
726
sgml-indent-step:1
 
727
sgml-indent-data: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
 
733
End:
 
734
-->