postgresql
Disparadores y funciones de disparador
Buscar..
Introducción
El activador se asociará con la tabla o vista especificada y ejecutará la función function_name especificada cuando se produzcan ciertos eventos.
Observaciones
Utilice el siguiente enlace para obtener una descripción completa de:
- Desencadenadores : https://www.postgresql.org/docs/current/static/sql-createtrigger.html
- Funciones de activación : https://www.postgresql.org/docs/current/static/plpgsql-trigger.html
Función básica de disparo PL / pgSQL
Esta es una función de disparo simple.
CREATE OR REPLACE FUNCTION my_simple_trigger_function()
RETURNS trigger AS
$BODY$
BEGIN
-- TG_TABLE_NAME :name of the table that caused the trigger invocation
IF (TG_TABLE_NAME = 'users') THEN
--TG_OP : operation the trigger was fired
IF (TG_OP = 'INSERT') THEN
--NEW.id is holding the new database row value (in here id is the id column in users table)
--NEW will return null for DELETE operations
INSERT INTO log_table (date_and_time, description) VALUES (now(), 'New user inserted. User ID: '|| NEW.id);
RETURN NEW;
ELSIF (TG_OP = 'DELETE') THEN
--OLD.id is holding the old database row value (in here id is the id column in users table)
--OLD will return null for INSERT operations
INSERT INTO log_table (date_and_time, description) VALUES (now(), 'User deleted.. User ID: ' || OLD.id);
RETURN OLD;
END IF;
RETURN null;
END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
Agregando esta función de disparo a la tabla de users
CREATE TRIGGER my_trigger
AFTER INSERT OR DELETE
ON users
FOR EACH ROW
EXECUTE PROCEDURE my_simple_trigger_function();
Tipo de disparadores
El disparador se puede especificar para disparar:
-
BEFORE
intentar la operación en una fila: insertar, actualizar o eliminar; -
AFTER
la operación haya finalizado: insertar, actualizar o eliminar; -
INSTEAD OF
la operación en el caso de inserciones, actualizaciones o eliminaciones en una vista.
Gatillo que está marcado:
-
FOR EACH ROW
se llama una vez por cada fila que modifica la operación; -
FOR EACH STATEMENT
se llama onde para cualquier operación dada.
Preparando para ejecutar ejemplos.
CREATE TABLE company (
id SERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
created_at TIMESTAMP,
modified_at TIMESTAMP DEFAULT NOW()
)
CREATE TABLE log (
id SERIAL PRIMARY KEY NOT NULL,
table_name TEXT NOT NULL,
table_id TEXT NOT NULL,
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
)
Gatillo de inserción individual
Paso 1: crea tu función
CREATE OR REPLACE FUNCTION add_created_at_function()
RETURNS trigger AS $BODY$
BEGIN
NEW.created_at := NOW();
RETURN NEW;
END $BODY$
LANGUAGE plpgsql;
Paso 2: crea tu disparador
CREATE TRIGGER add_created_at_trigger
BEFORE INSERT
ON company
FOR EACH ROW
EXECUTE PROCEDURE add_created_at_function();
Paso 3: probarlo
INSERT INTO company (name) VALUES ('My company');
SELECT * FROM company;
Trigger para múltiples propósitos
Paso 1: crea tu función
CREATE OR REPLACE FUNCTION add_log_function()
RETURNS trigger AS $BODY$
DECLARE
vDescription TEXT;
vId INT;
vReturn RECORD;
BEGIN
vDescription := TG_TABLE_NAME || ' ';
IF (TG_OP = 'INSERT') THEN
vId := NEW.id;
vDescription := vDescription || 'added. Id: ' || vId;
vReturn := NEW;
ELSIF (TG_OP = 'UPDATE') THEN
vId := NEW.id;
vDescription := vDescription || 'updated. Id: ' || vId;
vReturn := NEW;
ELSIF (TG_OP = 'DELETE') THEN
vId := OLD.id;
vDescription := vDescription || 'deleted. Id: ' || vId;
vReturn := OLD;
END IF;
RAISE NOTICE 'TRIGER called on % - Log: %', TG_TABLE_NAME, vDescription;
INSERT INTO log
(table_name, table_id, description, created_at)
VALUES
(TG_TABLE_NAME, vId, vDescription, NOW());
RETURN vReturn;
END $BODY$
LANGUAGE plpgsql;
Paso 2: crea tu disparador
CREATE TRIGGER add_log_trigger
AFTER INSERT OR UPDATE OR DELETE
ON company
FOR EACH ROW
EXECUTE PROCEDURE add_log_function();
Paso 3: probarlo
INSERT INTO company (name) VALUES ('Company 1');
INSERT INTO company (name) VALUES ('Company 2');
INSERT INTO company (name) VALUES ('Company 3');
UPDATE company SET name='Company new 2' WHERE name='Company 2';
DELETE FROM company WHERE name='Company 1';
SELECT * FROM log;
Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow