Abaixo está mostrado um exemplo bem simples de uma função de gatilho escrita em C (Podem ser encontrados na documentação das linguagens procedurais exemplos de gatilhos escritos nestas linguagens procedurais).
A função trigf informa o número de linhas na tabela ttest, e salta a operação se o comando tentar inserir um valor nulo na coluna x (Portanto, o gatilho age como uma restrição de não nulo, mas não interrompe a transação).
Primeiro, a definição da tabela:
CREATE TABLE ttest (
x integer
);
A seguir se encontra o código fonte da função de gatilho:
#include "postgres.h"
#include "executor/spi.h" /* necessário para trabalhar com SPI */
#include "commands/trigger.h" /* ... e gatilhos */
extern Datum trigf(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(trigf);
Datum
trigf(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
TupleDesc tupdesc;
HeapTuple rettuple;
char *when;
bool checknull = false;
bool isnull;
int ret, i;
/* certificar-se que foi chamado como um gatilho */
if (!CALLED_AS_TRIGGER(fcinfo))
elog(ERROR, "trigf: não foi chamada por um gerenciador de gatilho");
/* tupla a ser retornada para o executor */
if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
rettuple = trigdata->tg_newtuple;
else
rettuple = trigdata->tg_trigtuple;
/* verificar valores nulos */
if (!TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)
&& TRIGGER_FIRED_BEFORE(trigdata->tg_event))
checknull = true;
if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
when = "antes ";
else
when = "depois";
tupdesc = trigdata->tg_relation->rd_att;
/* conectar ao gerenciador de SPI */
if ((ret = SPI_connect()) < 0)
elog(INFO, "trigf (disparado %s): SPI_connect returned %d", when, ret);
/* obter o número de linhas na tabela */
ret = SPI_exec("SELECT count(*) FROM ttest", 0);
if (ret < 0)
elog(NOTICE, "trigf (disparado %s): SPI_exec retornou %d", when, ret);
/* count(*) retorna int8, deve-se ter cuidado ao converter */
i = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0],
SPI_tuptable->tupdesc,
1,
&isnull));
elog (INFO, "trigf (disparado %s): existem %d linhas em ttest", when, i);
SPI_finish();
if (checknull)
{
SPI_getbinval(rettuple, tupdesc, 1, &isnull);
if (isnull)
rettuple = NULL;
}
return PointerGetDatum(rettuple);
}
Após compilar o código fonte, a função e o gatilho são declarados:
CREATE FUNCTION trigf() RETURNS trigger
AS 'nome_do_arquivo'
LANGUAGE C;
CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest
FOR EACH ROW EXECUTE PROCEDURE trigf();
CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest
FOR EACH ROW EXECUTE PROCEDURE trigf();
Agora pode ser testada a operação do gatilho:
=> INSERT INTO ttest VALUES (NULL);
INFO: trigf (disparado antes): existem 0 linhas em ttest
INSERT 0 0
-- Inserção saltada e gatilho AFTER não é disparado
=> SELECT * FROM ttest;
x
---
(0 linhas)
=> INSERT INTO ttest VALUES (1);
INFO: trigf (disparado antes ): existem 0 linhas em ttest
INFO: trigf (disparado depois): existem 1 linhas em ttest
^^^^^^^^
lembre-se do que foi dito sobre visibilidade.
INSERT 167793 1
vac=> SELECT * FROM ttest;
x
---
1
(1 linha)
=> INSERT INTO ttest SELECT x * 2 FROM ttest;
INFO: trigf (disparado antes ): existem 1 linhas em ttest
INFO: trigf (disparado depois): existem 2 linhas em ttest
^^^^^^^^
lembre-se do que foi dito sobre visibilidade.
INSERT 167794 1
=> SELECT * FROM ttest;
x
---
1
2
(2 linhas)
=> UPDATE ttest SET x = NULL WHERE x = 2;
INFO: trigf (disparado antes ): existem 2 linhas em ttest
UPDATE 0
=> UPDATE ttest SET x = 4 WHERE x = 2;
INFO: trigf (disparado antes ): existem 2 linhas em ttest
INFO: trigf (disparado depois): existem 2 linhas em ttest
UPDATE 1
vac=> SELECT * FROM ttest;
x
---
1
4
(2 linhas)
=> DELETE FROM ttest;
INFO: trigf (disparado antes ): existem 2 linhas em ttest
INFO: trigf (disparado depois): existem 1 linhas em ttest
INFO: trigf (disparado antes ): existem 1 linhas em ttest
INFO: trigf (disparado depois): existem 0 linhas em ttest
^^^^^^^^
lembre-se do que foi dito sobre visibilidade.
DELETE 2
=> SELECT * FROM ttest;
x
---
(0 linhas)
Existem exemplos mais complexos no arquivo src/test/regress/regress.c e no diretório contrib/spi.