insert_username.c
上传用户:blenddy
上传日期:2007-01-07
资源大小:6495k
文件大小:2k
源码类别:

数据库系统

开发平台:

Unix_Linux

  1. /*
  2.  * insert_username.c
  3.  * $Modified: Thu Oct 16 08:13:42 1997 by brook $
  4.  *
  5.  * insert user name in response to a trigger
  6.  * usage:  insert_username (column_name)
  7.  */
  8. #include "executor/spi.h" /* this is what you need to work with SPI */
  9. #include "commands/trigger.h" /* -"- and triggers */
  10. #include "miscadmin.h" /* for GetPgUserName() */
  11. HeapTuple insert_username(void);
  12. HeapTuple
  13. insert_username()
  14. {
  15. Trigger    *trigger; /* to get trigger name */
  16. int nargs; /* # of arguments */
  17. Datum newval; /* new value of column */
  18. char   **args; /* arguments */
  19. char    *relname; /* triggered relation name */
  20. Relation rel; /* triggered relation */
  21. HeapTuple rettuple = NULL;
  22. TupleDesc tupdesc; /* tuple description */
  23. int attnum;
  24. /* sanity checks from autoinc.c */
  25. if (!CurrentTriggerData)
  26. elog(ERROR, "insert_username: triggers are not initialized");
  27. if (TRIGGER_FIRED_FOR_STATEMENT(CurrentTriggerData->tg_event))
  28. elog(ERROR, "insert_username: can't process STATEMENT events");
  29. if (TRIGGER_FIRED_AFTER(CurrentTriggerData->tg_event))
  30. elog(ERROR, "insert_username: must be fired before event");
  31. if (TRIGGER_FIRED_BY_INSERT(CurrentTriggerData->tg_event))
  32. rettuple = CurrentTriggerData->tg_trigtuple;
  33. else if (TRIGGER_FIRED_BY_UPDATE(CurrentTriggerData->tg_event))
  34. rettuple = CurrentTriggerData->tg_newtuple;
  35. else
  36. elog(ERROR, "insert_username: can't process DELETE events");
  37. rel = CurrentTriggerData->tg_relation;
  38. relname = SPI_getrelname(rel);
  39. trigger = CurrentTriggerData->tg_trigger;
  40. nargs = trigger->tgnargs;
  41. if (nargs != 1)
  42. elog(ERROR, "insert_username (%s): one argument was expected", relname);
  43. args = trigger->tgargs;
  44. tupdesc = rel->rd_att;
  45. CurrentTriggerData = NULL;
  46. attnum = SPI_fnumber(tupdesc, args[0]);
  47. if (attnum < 0)
  48. elog(ERROR, "insert_username (%s): there is no attribute %s", relname, args[0]);
  49. if (SPI_gettypeid(tupdesc, attnum) != TEXTOID)
  50. elog(ERROR, "insert_username (%s): attribute %s must be of TEXT type",
  51.  relname, args[0]);
  52. /* create fields containing name */
  53. newval = PointerGetDatum(textin(GetPgUserName()));
  54. /* construct new tuple */
  55. rettuple = SPI_modifytuple(rel, rettuple, 1, &attnum, &newval, NULL);
  56. if (rettuple == NULL)
  57. elog(ERROR, "insert_username (%s): %d returned by SPI_modifytuple",
  58.  relname, SPI_result);
  59. pfree(relname);
  60. return (rettuple);
  61. }