1<!-- doc/src/sgml/trigger.sgml --> 2 3 <chapter id="triggers"> 4 <title>Triggers</title> 5 6 <indexterm zone="triggers"> 7 <primary>trigger</primary> 8 </indexterm> 9 10 <para> 11 This chapter provides general information about writing trigger functions. 12 Trigger functions can be written in most of the available procedural 13 languages, including 14 <application>PL/pgSQL</application> (<xref linkend="plpgsql"/>), 15 <application>PL/Tcl</application> (<xref linkend="pltcl"/>), 16 <application>PL/Perl</application> (<xref linkend="plperl"/>), and 17 <application>PL/Python</application> (<xref linkend="plpython"/>). 18 After reading this chapter, you should consult the chapter for 19 your favorite procedural language to find out the language-specific 20 details of writing a trigger in it. 21 </para> 22 23 <para> 24 It is also possible to write a trigger function in C, although 25 most people find it easier to use one of the procedural languages. 26 It is not currently possible to write a trigger function in the 27 plain SQL function language. 28 </para> 29 30 <sect1 id="trigger-definition"> 31 <title>Overview of Trigger Behavior</title> 32 33 <para> 34 A trigger is a specification that the database should automatically 35 execute a particular function whenever a certain type of operation is 36 performed. Triggers can be attached to tables (partitioned or not), 37 views, and foreign tables. 38 </para> 39 40 <para> 41 On tables and foreign tables, triggers can be defined to execute either 42 before or after any <command>INSERT</command>, <command>UPDATE</command>, 43 or <command>DELETE</command> operation, either once per modified row, 44 or once per <acronym>SQL</acronym> statement. 45 <command>UPDATE</command> triggers can moreover be set to fire only if 46 certain columns are mentioned in the <literal>SET</literal> clause of 47 the <command>UPDATE</command> statement. Triggers can also fire 48 for <command>TRUNCATE</command> statements. If a trigger event occurs, 49 the trigger's function is called at the appropriate time to handle the 50 event. 51 </para> 52 53 <para> 54 On views, triggers can be defined to execute instead of 55 <command>INSERT</command>, <command>UPDATE</command>, or 56 <command>DELETE</command> operations. 57 Such <literal>INSTEAD OF</literal> triggers 58 are fired once for each row that needs to be modified in the view. 59 It is the responsibility of the 60 trigger's function to perform the necessary modifications to the view's 61 underlying base table(s) and, where appropriate, return the modified 62 row as it will appear in the view. Triggers on views can also be defined 63 to execute once per <acronym>SQL</acronym> statement, before or after 64 <command>INSERT</command>, <command>UPDATE</command>, or 65 <command>DELETE</command> operations. 66 However, such triggers are fired only if there is also 67 an <literal>INSTEAD OF</literal> trigger on the view. Otherwise, 68 any statement targeting the view must be rewritten into a statement 69 affecting its underlying base table(s), and then the triggers 70 that will be fired are the ones attached to the base table(s). 71 </para> 72 73 <para> 74 The trigger function must be defined before the trigger itself can be 75 created. The trigger function must be declared as a 76 function taking no arguments and returning type <literal>trigger</literal>. 77 (The trigger function receives its input through a specially-passed 78 <structname>TriggerData</structname> structure, not in the form of ordinary function 79 arguments.) 80 </para> 81 82 <para> 83 Once a suitable trigger function has been created, the trigger is 84 established with 85 <xref linkend="sql-createtrigger"/>. 86 The same trigger function can be used for multiple triggers. 87 </para> 88 89 <para> 90 <productname>PostgreSQL</productname> offers both <firstterm>per-row</firstterm> 91 triggers and <firstterm>per-statement</firstterm> triggers. With a per-row 92 trigger, the trigger function 93 is invoked once for each row that is affected by the statement 94 that fired the trigger. In contrast, a per-statement trigger is 95 invoked only once when an appropriate statement is executed, 96 regardless of the number of rows affected by that statement. In 97 particular, a statement that affects zero rows will still result 98 in the execution of any applicable per-statement triggers. These 99 two types of triggers are sometimes called <firstterm>row-level</firstterm> 100 triggers and <firstterm>statement-level</firstterm> triggers, 101 respectively. Triggers on <command>TRUNCATE</command> may only be 102 defined at statement level, not per-row. 103 </para> 104 105 <para> 106 Triggers are also classified according to whether they fire 107 <firstterm>before</firstterm>, <firstterm>after</firstterm>, or 108 <firstterm>instead of</firstterm> the operation. These are referred to 109 as <literal>BEFORE</literal> triggers, <literal>AFTER</literal> triggers, and 110 <literal>INSTEAD OF</literal> triggers respectively. 111 Statement-level <literal>BEFORE</literal> triggers naturally fire before the 112 statement starts to do anything, while statement-level <literal>AFTER</literal> 113 triggers fire at the very end of the statement. These types of 114 triggers may be defined on tables, views, or foreign tables. Row-level 115 <literal>BEFORE</literal> triggers fire immediately before a particular row is 116 operated on, while row-level <literal>AFTER</literal> triggers fire at the end of 117 the statement (but before any statement-level <literal>AFTER</literal> triggers). 118 These types of triggers may only be defined on tables and 119 foreign tables, not views. 120 <literal>INSTEAD OF</literal> triggers may only be 121 defined on views, and only at row level; they fire immediately as each 122 row in the view is identified as needing to be operated on. 123 </para> 124 125 <para> 126 A statement that targets a parent table in an inheritance or partitioning 127 hierarchy does not cause the statement-level triggers of affected child 128 tables to be fired; only the parent table's statement-level triggers are 129 fired. However, row-level triggers of any affected child tables will be 130 fired. 131 </para> 132 133 <para> 134 If an <command>INSERT</command> contains an <literal>ON CONFLICT 135 DO UPDATE</literal> clause, it is possible that the effects of 136 row-level <literal>BEFORE</literal> <command>INSERT</command> triggers and 137 row-level <literal>BEFORE</literal> <command>UPDATE</command> triggers can 138 both be applied in a way that is apparent from the final state of 139 the updated row, if an <varname>EXCLUDED</varname> column is referenced. 140 There need not be an <varname>EXCLUDED</varname> column reference for 141 both sets of row-level <literal>BEFORE</literal> triggers to execute, 142 though. The 143 possibility of surprising outcomes should be considered when there 144 are both <literal>BEFORE</literal> <command>INSERT</command> and 145 <literal>BEFORE</literal> <command>UPDATE</command> row-level triggers 146 that change a row being inserted/updated (this can be 147 problematic even if the modifications are more or less equivalent, if 148 they're not also idempotent). Note that statement-level 149 <command>UPDATE</command> triggers are executed when <literal>ON 150 CONFLICT DO UPDATE</literal> is specified, regardless of whether or not 151 any rows were affected by the <command>UPDATE</command> (and 152 regardless of whether the alternative <command>UPDATE</command> 153 path was ever taken). An <command>INSERT</command> with an 154 <literal>ON CONFLICT DO UPDATE</literal> clause will execute 155 statement-level <literal>BEFORE</literal> <command>INSERT</command> 156 triggers first, then statement-level <literal>BEFORE</literal> 157 <command>UPDATE</command> triggers, followed by statement-level 158 <literal>AFTER</literal> <command>UPDATE</command> triggers and finally 159 statement-level <literal>AFTER</literal> <command>INSERT</command> 160 triggers. 161 </para> 162 163 <para> 164 If an <command>UPDATE</command> on a partitioned table causes a row to move 165 to another partition, it will be performed as a <command>DELETE</command> 166 from the original partition followed by an <command>INSERT</command> into 167 the new partition. In this case, all row-level <literal>BEFORE</literal> 168 <command>UPDATE</command> triggers and all row-level 169 <literal>BEFORE</literal> <command>DELETE</command> triggers are fired on 170 the original partition. Then all row-level <literal>BEFORE</literal> 171 <command>INSERT</command> triggers are fired on the destination partition. 172 The possibility of surprising outcomes should be considered when all these 173 triggers affect the row being moved. As far as <literal>AFTER ROW</literal> 174 triggers are concerned, <literal>AFTER</literal> <command>DELETE</command> 175 and <literal>AFTER</literal> <command>INSERT</command> triggers are 176 applied; but <literal>AFTER</literal> <command>UPDATE</command> triggers 177 are not applied because the <command>UPDATE</command> has been converted to 178 a <command>DELETE</command> and an <command>INSERT</command>. As far as 179 statement-level triggers are concerned, none of the 180 <command>DELETE</command> or <command>INSERT</command> triggers are fired, 181 even if row movement occurs; only the <command>UPDATE</command> triggers 182 defined on the target table used in the <command>UPDATE</command> statement 183 will be fired. 184 </para> 185 186 <para> 187 Trigger functions invoked by per-statement triggers should always 188 return <symbol>NULL</symbol>. Trigger functions invoked by per-row 189 triggers can return a table row (a value of 190 type <structname>HeapTuple</structname>) to the calling executor, 191 if they choose. A row-level trigger fired before an operation has 192 the following choices: 193 194 <itemizedlist> 195 <listitem> 196 <para> 197 It can return <symbol>NULL</symbol> to skip the operation for the 198 current row. This instructs the executor to not perform the 199 row-level operation that invoked the trigger (the insertion, 200 modification, or deletion of a particular table row). 201 </para> 202 </listitem> 203 204 <listitem> 205 <para> 206 For row-level <command>INSERT</command> 207 and <command>UPDATE</command> triggers only, the returned row 208 becomes the row that will be inserted or will replace the row 209 being updated. This allows the trigger function to modify the 210 row being inserted or updated. 211 </para> 212 </listitem> 213 </itemizedlist> 214 215 A row-level <literal>BEFORE</literal> trigger that does not intend to cause 216 either of these behaviors must be careful to return as its result the same 217 row that was passed in (that is, the <varname>NEW</varname> row 218 for <command>INSERT</command> and <command>UPDATE</command> 219 triggers, the <varname>OLD</varname> row for 220 <command>DELETE</command> triggers). 221 </para> 222 223 <para> 224 A row-level <literal>INSTEAD OF</literal> trigger should either return 225 <symbol>NULL</symbol> to indicate that it did not modify any data from 226 the view's underlying base tables, or it should return the view 227 row that was passed in (the <varname>NEW</varname> row 228 for <command>INSERT</command> and <command>UPDATE</command> 229 operations, or the <varname>OLD</varname> row for 230 <command>DELETE</command> operations). A nonnull return value is 231 used to signal that the trigger performed the necessary data 232 modifications in the view. This will cause the count of the number 233 of rows affected by the command to be incremented. For 234 <command>INSERT</command> and <command>UPDATE</command> operations only, the trigger 235 may modify the <varname>NEW</varname> row before returning it. This will 236 change the data returned by 237 <command>INSERT RETURNING</command> or <command>UPDATE RETURNING</command>, 238 and is useful when the view will not show exactly the same data 239 that was provided. 240 </para> 241 242 <para> 243 The return value is ignored for row-level triggers fired after an 244 operation, and so they can return <symbol>NULL</symbol>. 245 </para> 246 247 <para> 248 Some considerations apply for generated 249 columns.<indexterm><primary>generated column</primary><secondary>in 250 triggers</secondary></indexterm> Stored generated columns are computed after 251 <literal>BEFORE</literal> triggers and before <literal>AFTER</literal> 252 triggers. Therefore, the generated value can be inspected in 253 <literal>AFTER</literal> triggers. In <literal>BEFORE</literal> triggers, 254 the <literal>OLD</literal> row contains the old generated value, as one 255 would expect, but the <literal>NEW</literal> row does not yet contain the 256 new generated value and should not be accessed. In the C language 257 interface, the content of the column is undefined at this point; a 258 higher-level programming language should prevent access to a stored 259 generated column in the <literal>NEW</literal> row in a 260 <literal>BEFORE</literal> trigger. Changes to the value of a generated 261 column in a <literal>BEFORE</literal> trigger are ignored and will be 262 overwritten. 263 </para> 264 265 <para> 266 If more than one trigger is defined for the same event on the same 267 relation, the triggers will be fired in alphabetical order by 268 trigger name. In the case of <literal>BEFORE</literal> and 269 <literal>INSTEAD OF</literal> triggers, the possibly-modified row returned by 270 each trigger becomes the input to the next trigger. If any 271 <literal>BEFORE</literal> or <literal>INSTEAD OF</literal> trigger returns 272 <symbol>NULL</symbol>, the operation is abandoned for that row and subsequent 273 triggers are not fired (for that row). 274 </para> 275 276 <para> 277 A trigger definition can also specify a Boolean <literal>WHEN</literal> 278 condition, which will be tested to see whether the trigger should 279 be fired. In row-level triggers the <literal>WHEN</literal> condition can 280 examine the old and/or new values of columns of the row. (Statement-level 281 triggers can also have <literal>WHEN</literal> conditions, although the feature 282 is not so useful for them.) In a <literal>BEFORE</literal> trigger, the 283 <literal>WHEN</literal> 284 condition is evaluated just before the function is or would be executed, 285 so using <literal>WHEN</literal> is not materially different from testing the 286 same condition at the beginning of the trigger function. However, in 287 an <literal>AFTER</literal> trigger, the <literal>WHEN</literal> condition is evaluated 288 just after the row update occurs, and it determines whether an event is 289 queued to fire the trigger at the end of statement. So when an 290 <literal>AFTER</literal> trigger's 291 <literal>WHEN</literal> condition does not return true, it is not necessary 292 to queue an event nor to re-fetch the row at end of statement. This 293 can result in significant speedups in statements that modify many 294 rows, if the trigger only needs to be fired for a few of the rows. 295 <literal>INSTEAD OF</literal> triggers do not support 296 <literal>WHEN</literal> conditions. 297 </para> 298 299 <para> 300 Typically, row-level <literal>BEFORE</literal> triggers are used for checking or 301 modifying the data that will be inserted or updated. For example, 302 a <literal>BEFORE</literal> trigger might be used to insert the current time into a 303 <type>timestamp</type> column, or to check that two elements of the row are 304 consistent. Row-level <literal>AFTER</literal> triggers are most sensibly 305 used to propagate the updates to other tables, or make consistency 306 checks against other tables. The reason for this division of labor is 307 that an <literal>AFTER</literal> trigger can be certain it is seeing the final 308 value of the row, while a <literal>BEFORE</literal> trigger cannot; there might 309 be other <literal>BEFORE</literal> triggers firing after it. If you have no 310 specific reason to make a trigger <literal>BEFORE</literal> or 311 <literal>AFTER</literal>, the <literal>BEFORE</literal> case is more efficient, since 312 the information about 313 the operation doesn't have to be saved until end of statement. 314 </para> 315 316 <para> 317 If a trigger function executes SQL commands then these 318 commands might fire triggers again. This is known as cascading 319 triggers. There is no direct limitation on the number of cascade 320 levels. It is possible for cascades to cause a recursive invocation 321 of the same trigger; for example, an <command>INSERT</command> 322 trigger might execute a command that inserts an additional row 323 into the same table, causing the <command>INSERT</command> trigger 324 to be fired again. It is the trigger programmer's responsibility 325 to avoid infinite recursion in such scenarios. 326 </para> 327 328 <para> 329 <indexterm> 330 <primary>trigger</primary> 331 <secondary>arguments for trigger functions</secondary> 332 </indexterm> 333 When a trigger is being defined, arguments can be specified for 334 it. The purpose of including arguments in the 335 trigger definition is to allow different triggers with similar 336 requirements to call the same function. As an example, there 337 could be a generalized trigger function that takes as its 338 arguments two column names and puts the current user in one and 339 the current time stamp in the other. Properly written, this 340 trigger function would be independent of the specific table it is 341 triggering on. So the same function could be used for 342 <command>INSERT</command> events on any table with suitable 343 columns, to automatically track creation of records in a 344 transaction table for example. It could also be used to track 345 last-update events if defined as an <command>UPDATE</command> 346 trigger. 347 </para> 348 349 <para> 350 Each programming language that supports triggers has its own method 351 for making the trigger input data available to the trigger function. 352 This input data includes the type of trigger event (e.g., 353 <command>INSERT</command> or <command>UPDATE</command>) as well as any 354 arguments that were listed in <command>CREATE TRIGGER</command>. 355 For a row-level trigger, the input data also includes the 356 <varname>NEW</varname> row for <command>INSERT</command> and 357 <command>UPDATE</command> triggers, and/or the <varname>OLD</varname> row 358 for <command>UPDATE</command> and <command>DELETE</command> triggers. 359 </para> 360 361 <para> 362 By default, statement-level triggers do not have any way to examine the 363 individual row(s) modified by the statement. But an <literal>AFTER 364 STATEMENT</literal> trigger can request that <firstterm>transition tables</firstterm> 365 be created to make the sets of affected rows available to the trigger. 366 <literal>AFTER ROW</literal> triggers can also request transition tables, so 367 that they can see the total changes in the table as well as the change in 368 the individual row they are currently being fired for. The method for 369 examining the transition tables again depends on the programming language 370 that is being used, but the typical approach is to make the transition 371 tables act like read-only temporary tables that can be accessed by SQL 372 commands issued within the trigger function. 373 </para> 374 375 </sect1> 376 377 <sect1 id="trigger-datachanges"> 378 <title>Visibility of Data Changes</title> 379 380 <para> 381 If you execute SQL commands in your trigger function, and these 382 commands access the table that the trigger is for, then 383 you need to be aware of the data visibility rules, because they determine 384 whether these SQL commands will see the data change that the trigger 385 is fired for. Briefly: 386 387 <itemizedlist> 388 389 <listitem> 390 <para> 391 Statement-level triggers follow simple visibility rules: none of 392 the changes made by a statement are visible to statement-level 393 <literal>BEFORE</literal> triggers, whereas all 394 modifications are visible to statement-level <literal>AFTER</literal> 395 triggers. 396 </para> 397 </listitem> 398 399 <listitem> 400 <para> 401 The data change (insertion, update, or deletion) causing the 402 trigger to fire is naturally <emphasis>not</emphasis> visible 403 to SQL commands executed in a row-level <literal>BEFORE</literal> trigger, 404 because it hasn't happened yet. 405 </para> 406 </listitem> 407 408 <listitem> 409 <para> 410 However, SQL commands executed in a row-level <literal>BEFORE</literal> 411 trigger <emphasis>will</emphasis> see the effects of data 412 changes for rows previously processed in the same outer 413 command. This requires caution, since the ordering of these 414 change events is not in general predictable; a SQL command that 415 affects multiple rows can visit the rows in any order. 416 </para> 417 </listitem> 418 419 <listitem> 420 <para> 421 Similarly, a row-level <literal>INSTEAD OF</literal> trigger will see the 422 effects of data changes made by previous firings of <literal>INSTEAD 423 OF</literal> triggers in the same outer command. 424 </para> 425 </listitem> 426 427 <listitem> 428 <para> 429 When a row-level <literal>AFTER</literal> trigger is fired, all data 430 changes made 431 by the outer command are already complete, and are visible to 432 the invoked trigger function. 433 </para> 434 </listitem> 435 </itemizedlist> 436 </para> 437 438 <para> 439 If your trigger function is written in any of the standard procedural 440 languages, then the above statements apply only if the function is 441 declared <literal>VOLATILE</literal>. Functions that are declared 442 <literal>STABLE</literal> or <literal>IMMUTABLE</literal> will not see changes made by 443 the calling command in any case. 444 </para> 445 446 <para> 447 Further information about data visibility rules can be found in 448 <xref linkend="spi-visibility"/>. The example in <xref 449 linkend="trigger-example"/> contains a demonstration of these rules. 450 </para> 451 </sect1> 452 453 <sect1 id="trigger-interface"> 454 <title>Writing Trigger Functions in C</title> 455 456 <indexterm zone="trigger-interface"> 457 <primary>trigger</primary> 458 <secondary>in C</secondary> 459 </indexterm> 460 461 <indexterm> 462 <primary>transition tables</primary> 463 <secondary>referencing from C trigger</secondary> 464 </indexterm> 465 466 <para> 467 This section describes the low-level details of the interface to a 468 trigger function. This information is only needed when writing 469 trigger functions in C. If you are using a higher-level language then 470 these details are handled for you. In most cases you should consider 471 using a procedural language before writing your triggers in C. The 472 documentation of each procedural language explains how to write a 473 trigger in that language. 474 </para> 475 476 <para> 477 Trigger functions must use the <quote>version 1</quote> function manager 478 interface. 479 </para> 480 481 <para> 482 When a function is called by the trigger manager, it is not passed 483 any normal arguments, but it is passed a <quote>context</quote> 484 pointer pointing to a <structname>TriggerData</structname> structure. C 485 functions can check whether they were called from the trigger 486 manager or not by executing the macro: 487<programlisting> 488CALLED_AS_TRIGGER(fcinfo) 489</programlisting> 490 which expands to: 491<programlisting> 492((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData)) 493</programlisting> 494 If this returns true, then it is safe to cast 495 <literal>fcinfo->context</literal> to type <literal>TriggerData 496 *</literal> and make use of the pointed-to 497 <structname>TriggerData</structname> structure. The function must 498 <emphasis>not</emphasis> alter the <structname>TriggerData</structname> 499 structure or any of the data it points to. 500 </para> 501 502 <para> 503 <structname>struct TriggerData</structname> is defined in 504 <filename>commands/trigger.h</filename>: 505 506<programlisting> 507typedef struct TriggerData 508{ 509 NodeTag type; 510 TriggerEvent tg_event; 511 Relation tg_relation; 512 HeapTuple tg_trigtuple; 513 HeapTuple tg_newtuple; 514 Trigger *tg_trigger; 515 TupleTableSlot *tg_trigslot; 516 TupleTableSlot *tg_newslot; 517 Tuplestorestate *tg_oldtable; 518 Tuplestorestate *tg_newtable; 519 const Bitmapset *tg_updatedcols; 520} TriggerData; 521</programlisting> 522 523 where the members are defined as follows: 524 525 <variablelist> 526 <varlistentry> 527 <term><structfield>type</structfield></term> 528 <listitem> 529 <para> 530 Always <literal>T_TriggerData</literal>. 531 </para> 532 </listitem> 533 </varlistentry> 534 535 <varlistentry> 536 <term><structfield>tg_event</structfield></term> 537 <listitem> 538 <para> 539 Describes the event for which the function is called. You can use the 540 following macros to examine <literal>tg_event</literal>: 541 542 <variablelist> 543 <varlistentry> 544 <term><literal>TRIGGER_FIRED_BEFORE(tg_event)</literal></term> 545 <listitem> 546 <para> 547 Returns true if the trigger fired before the operation. 548 </para> 549 </listitem> 550 </varlistentry> 551 552 <varlistentry> 553 <term><literal>TRIGGER_FIRED_AFTER(tg_event)</literal></term> 554 <listitem> 555 <para> 556 Returns true if the trigger fired after the operation. 557 </para> 558 </listitem> 559 </varlistentry> 560 561 <varlistentry> 562 <term><literal>TRIGGER_FIRED_INSTEAD(tg_event)</literal></term> 563 <listitem> 564 <para> 565 Returns true if the trigger fired instead of the operation. 566 </para> 567 </listitem> 568 </varlistentry> 569 570 <varlistentry> 571 <term><literal>TRIGGER_FIRED_FOR_ROW(tg_event)</literal></term> 572 <listitem> 573 <para> 574 Returns true if the trigger fired for a row-level event. 575 </para> 576 </listitem> 577 </varlistentry> 578 579 <varlistentry> 580 <term><literal>TRIGGER_FIRED_FOR_STATEMENT(tg_event)</literal></term> 581 <listitem> 582 <para> 583 Returns true if the trigger fired for a statement-level event. 584 </para> 585 </listitem> 586 </varlistentry> 587 588 <varlistentry> 589 <term><literal>TRIGGER_FIRED_BY_INSERT(tg_event)</literal></term> 590 <listitem> 591 <para> 592 Returns true if the trigger was fired by an <command>INSERT</command> command. 593 </para> 594 </listitem> 595 </varlistentry> 596 597 <varlistentry> 598 <term><literal>TRIGGER_FIRED_BY_UPDATE(tg_event)</literal></term> 599 <listitem> 600 <para> 601 Returns true if the trigger was fired by an <command>UPDATE</command> command. 602 </para> 603 </listitem> 604 </varlistentry> 605 606 <varlistentry> 607 <term><literal>TRIGGER_FIRED_BY_DELETE(tg_event)</literal></term> 608 <listitem> 609 <para> 610 Returns true if the trigger was fired by a <command>DELETE</command> command. 611 </para> 612 </listitem> 613 </varlistentry> 614 615 <varlistentry> 616 <term><literal>TRIGGER_FIRED_BY_TRUNCATE(tg_event)</literal></term> 617 <listitem> 618 <para> 619 Returns true if the trigger was fired by a <command>TRUNCATE</command> command. 620 </para> 621 </listitem> 622 </varlistentry> 623 </variablelist> 624 </para> 625 </listitem> 626 </varlistentry> 627 628 <varlistentry> 629 <term><structfield>tg_relation</structfield></term> 630 <listitem> 631 <para> 632 A pointer to a structure describing the relation that the trigger fired for. 633 Look at <filename>utils/rel.h</filename> for details about 634 this structure. The most interesting things are 635 <literal>tg_relation->rd_att</literal> (descriptor of the relation 636 tuples) and <literal>tg_relation->rd_rel->relname</literal> 637 (relation name; the type is not <type>char*</type> but 638 <type>NameData</type>; use 639 <literal>SPI_getrelname(tg_relation)</literal> to get a <type>char*</type> if you 640 need a copy of the name). 641 </para> 642 </listitem> 643 </varlistentry> 644 645 <varlistentry> 646 <term><structfield>tg_trigtuple</structfield></term> 647 <listitem> 648 <para> 649 A pointer to the row for which the trigger was fired. This is 650 the row being inserted, updated, or deleted. If this trigger 651 was fired for an <command>INSERT</command> or 652 <command>DELETE</command> then this is what you should return 653 from the function if you don't want to replace the row with 654 a different one (in the case of <command>INSERT</command>) or 655 skip the operation. For triggers on foreign tables, values of system 656 columns herein are unspecified. 657 </para> 658 </listitem> 659 </varlistentry> 660 661 <varlistentry> 662 <term><structfield>tg_newtuple</structfield></term> 663 <listitem> 664 <para> 665 A pointer to the new version of the row, if the trigger was 666 fired for an <command>UPDATE</command>, and <symbol>NULL</symbol> if 667 it is for an <command>INSERT</command> or a 668 <command>DELETE</command>. This is what you have to return 669 from the function if the event is an <command>UPDATE</command> 670 and you don't want to replace this row by a different one or 671 skip the operation. For triggers on foreign tables, values of system 672 columns herein are unspecified. 673 </para> 674 </listitem> 675 </varlistentry> 676 677 <varlistentry> 678 <term><structfield>tg_trigger</structfield></term> 679 <listitem> 680 <para> 681 A pointer to a structure of type <structname>Trigger</structname>, 682 defined in <filename>utils/reltrigger.h</filename>: 683 684<programlisting> 685typedef struct Trigger 686{ 687 Oid tgoid; 688 char *tgname; 689 Oid tgfoid; 690 int16 tgtype; 691 char tgenabled; 692 bool tgisinternal; 693 Oid tgconstrrelid; 694 Oid tgconstrindid; 695 Oid tgconstraint; 696 bool tgdeferrable; 697 bool tginitdeferred; 698 int16 tgnargs; 699 int16 tgnattr; 700 int16 *tgattr; 701 char **tgargs; 702 char *tgqual; 703 char *tgoldtable; 704 char *tgnewtable; 705} Trigger; 706</programlisting> 707 708 where <structfield>tgname</structfield> is the trigger's name, 709 <structfield>tgnargs</structfield> is the number of arguments in 710 <structfield>tgargs</structfield>, and <structfield>tgargs</structfield> is an array of 711 pointers to the arguments specified in the <command>CREATE 712 TRIGGER</command> statement. The other members are for internal use 713 only. 714 </para> 715 </listitem> 716 </varlistentry> 717 718 <varlistentry> 719 <term><structfield>tg_trigslot</structfield></term> 720 <listitem> 721 <para> 722 The slot containing <structfield>tg_trigtuple</structfield>, 723 or a <symbol>NULL</symbol> pointer if there is no such tuple. 724 </para> 725 </listitem> 726 </varlistentry> 727 728 <varlistentry> 729 <term><structfield>tg_newslot</structfield></term> 730 <listitem> 731 <para> 732 The slot containing <structfield>tg_newtuple</structfield>, 733 or a <symbol>NULL</symbol> pointer if there is no such tuple. 734 </para> 735 </listitem> 736 </varlistentry> 737 738 <varlistentry> 739 <term><structfield>tg_oldtable</structfield></term> 740 <listitem> 741 <para> 742 A pointer to a structure of type <structname>Tuplestorestate</structname> 743 containing zero or more rows in the format specified by 744 <structfield>tg_relation</structfield>, or a <symbol>NULL</symbol> pointer 745 if there is no <literal>OLD TABLE</literal> transition relation. 746 </para> 747 </listitem> 748 </varlistentry> 749 750 <varlistentry> 751 <term><structfield>tg_newtable</structfield></term> 752 <listitem> 753 <para> 754 A pointer to a structure of type <structname>Tuplestorestate</structname> 755 containing zero or more rows in the format specified by 756 <structfield>tg_relation</structfield>, or a <symbol>NULL</symbol> pointer 757 if there is no <literal>NEW TABLE</literal> transition relation. 758 </para> 759 </listitem> 760 </varlistentry> 761 762 <varlistentry> 763 <term><structfield>tg_updatedcols</structfield></term> 764 <listitem> 765 <para> 766 For <literal>UPDATE</literal> triggers, a bitmap set indicating the 767 columns that were updated by the triggering command. Generic trigger 768 functions can use this to optimize actions by not having to deal with 769 columns that were not changed. 770 </para> 771 772 <para> 773 As an example, to determine whether a column with attribute number 774 <varname>attnum</varname> (1-based) is a member of this bitmap set, 775 call <literal>bms_is_member(attnum - 776 FirstLowInvalidHeapAttributeNumber, 777 trigdata->tg_updatedcols))</literal>. 778 </para> 779 780 <para> 781 For triggers other than <literal>UPDATE</literal> triggers, this will 782 be <symbol>NULL</symbol>. 783 </para> 784 </listitem> 785 </varlistentry> 786 </variablelist> 787 </para> 788 789 <para> 790 To allow queries issued through SPI to reference transition tables, see 791 <xref linkend="spi-spi-register-trigger-data"/>. 792 </para> 793 794 <para> 795 A trigger function must return either a 796 <structname>HeapTuple</structname> pointer or a <symbol>NULL</symbol> pointer 797 (<emphasis>not</emphasis> an SQL null value, that is, do not set <parameter>isNull</parameter> true). 798 Be careful to return either 799 <structfield>tg_trigtuple</structfield> or <structfield>tg_newtuple</structfield>, 800 as appropriate, if you don't want to modify the row being operated on. 801 </para> 802 </sect1> 803 804 <sect1 id="trigger-example"> 805 <title>A Complete Trigger Example</title> 806 807 <para> 808 Here is a very simple example of a trigger function written in C. 809 (Examples of triggers written in procedural languages can be found 810 in the documentation of the procedural languages.) 811 </para> 812 813 <para> 814 The function <function>trigf</function> reports the number of rows in the 815 table <structname>ttest</structname> and skips the actual operation if the 816 command attempts to insert a null value into the column 817 <structfield>x</structfield>. (So the trigger acts as a not-null constraint but 818 doesn't abort the transaction.) 819 </para> 820 821 <para> 822 First, the table definition: 823<programlisting> 824CREATE TABLE ttest ( 825 x integer 826); 827</programlisting> 828 </para> 829 830 <para> 831 This is the source code of the trigger function: 832<programlisting><![CDATA[ 833#include "postgres.h" 834#include "fmgr.h" 835#include "executor/spi.h" /* this is what you need to work with SPI */ 836#include "commands/trigger.h" /* ... triggers ... */ 837#include "utils/rel.h" /* ... and relations */ 838 839PG_MODULE_MAGIC; 840 841PG_FUNCTION_INFO_V1(trigf); 842 843Datum 844trigf(PG_FUNCTION_ARGS) 845{ 846 TriggerData *trigdata = (TriggerData *) fcinfo->context; 847 TupleDesc tupdesc; 848 HeapTuple rettuple; 849 char *when; 850 bool checknull = false; 851 bool isnull; 852 int ret, i; 853 854 /* make sure it's called as a trigger at all */ 855 if (!CALLED_AS_TRIGGER(fcinfo)) 856 elog(ERROR, "trigf: not called by trigger manager"); 857 858 /* tuple to return to executor */ 859 if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event)) 860 rettuple = trigdata->tg_newtuple; 861 else 862 rettuple = trigdata->tg_trigtuple; 863 864 /* check for null values */ 865 if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event) 866 && TRIGGER_FIRED_BEFORE(trigdata->tg_event)) 867 checknull = true; 868 869 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event)) 870 when = "before"; 871 else 872 when = "after "; 873 874 tupdesc = trigdata->tg_relation->rd_att; 875 876 /* connect to SPI manager */ 877 if ((ret = SPI_connect()) < 0) 878 elog(ERROR, "trigf (fired %s): SPI_connect returned %d", when, ret); 879 880 /* get number of rows in table */ 881 ret = SPI_exec("SELECT count(*) FROM ttest", 0); 882 883 if (ret < 0) 884 elog(ERROR, "trigf (fired %s): SPI_exec returned %d", when, ret); 885 886 /* count(*) returns int8, so be careful to convert */ 887 i = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], 888 SPI_tuptable->tupdesc, 889 1, 890 &isnull)); 891 892 elog (INFO, "trigf (fired %s): there are %d rows in ttest", when, i); 893 894 SPI_finish(); 895 896 if (checknull) 897 { 898 SPI_getbinval(rettuple, tupdesc, 1, &isnull); 899 if (isnull) 900 rettuple = NULL; 901 } 902 903 return PointerGetDatum(rettuple); 904} 905]]> 906</programlisting> 907 </para> 908 909 <para> 910 After you have compiled the source code (see <xref 911 linkend="dfunc"/>), declare the function and the triggers: 912<programlisting> 913CREATE FUNCTION trigf() RETURNS trigger 914 AS '<replaceable>filename</replaceable>' 915 LANGUAGE C; 916 917CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest 918 FOR EACH ROW EXECUTE FUNCTION trigf(); 919 920CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest 921 FOR EACH ROW EXECUTE FUNCTION trigf(); 922</programlisting> 923 </para> 924 925 <para> 926 Now you can test the operation of the trigger: 927<screen> 928=> INSERT INTO ttest VALUES (NULL); 929INFO: trigf (fired before): there are 0 rows in ttest 930INSERT 0 0 931 932-- Insertion skipped and AFTER trigger is not fired 933 934=> SELECT * FROM ttest; 935 x 936--- 937(0 rows) 938 939=> INSERT INTO ttest VALUES (1); 940INFO: trigf (fired before): there are 0 rows in ttest 941INFO: trigf (fired after ): there are 1 rows in ttest 942 ^^^^^^^^ 943 remember what we said about visibility. 944INSERT 167793 1 945vac=> SELECT * FROM ttest; 946 x 947--- 948 1 949(1 row) 950 951=> INSERT INTO ttest SELECT x * 2 FROM ttest; 952INFO: trigf (fired before): there are 1 rows in ttest 953INFO: trigf (fired after ): there are 2 rows in ttest 954 ^^^^^^ 955 remember what we said about visibility. 956INSERT 167794 1 957=> SELECT * FROM ttest; 958 x 959--- 960 1 961 2 962(2 rows) 963 964=> UPDATE ttest SET x = NULL WHERE x = 2; 965INFO: trigf (fired before): there are 2 rows in ttest 966UPDATE 0 967=> UPDATE ttest SET x = 4 WHERE x = 2; 968INFO: trigf (fired before): there are 2 rows in ttest 969INFO: trigf (fired after ): there are 2 rows in ttest 970UPDATE 1 971vac=> SELECT * FROM ttest; 972 x 973--- 974 1 975 4 976(2 rows) 977 978=> DELETE FROM ttest; 979INFO: trigf (fired before): there are 2 rows in ttest 980INFO: trigf (fired before): there are 1 rows in ttest 981INFO: trigf (fired after ): there are 0 rows in ttest 982INFO: trigf (fired after ): there are 0 rows in ttest 983 ^^^^^^ 984 remember what we said about visibility. 985DELETE 2 986=> SELECT * FROM ttest; 987 x 988--- 989(0 rows) 990</screen> 991 992 </para> 993 994 <para> 995 There are more complex examples in 996 <filename>src/test/regress/regress.c</filename> and 997 in <xref linkend="contrib-spi"/>. 998 </para> 999 </sect1> 1000 </chapter> 1001