3

Estoy haciendo una tabla de auditoria con triggers en postgresql.

La idea es que cuando en la tabla tb_marca se inserta un registro se inserte el registro en la tabla tb_marca_log. Y si el registro ya existía en la tabla de log que se actualice con la nueva información.

marca es el pk de la tabla tb_marca y tb_marca_log.

Esto es lo que tengo hecho:

CREATE    OR REPLACE FUNCTION coches.fn_marca_audit() RETURNS trigger AS $$ BEGIN
IF (TG_OP = 'INSERT') THEN
  IF not exists (SELECT 1 FROM coches_2.tb_marca_log WHERE new.marca = marca) THEN
   INSERT INTO coches_2.tb_marca_log ("marca", "matricula", "usuario_creador", "updated_date", "action","user_id","action_datetime")
   VALUES (NEW.marca, NEW.matricula, NEW.usuario_creador, NEW.updated_date, 'INSERT', USER, now());
  ELSIF exists (SELECT 1 FROM coches_2.tb_marca_log WHERE new.marca = marca) THEN
   UPDATE coches_2.tb_marca_log SET ("marca", "matricula", "usuario_creador", "updated_date", "action","user_id","action_datetime")
   = (NEW.marca, NEW.matricula, NEW.usuario_creador, NEW.updated_date, 'INSERT', USER, now());
   RETURN NEW;  
  END IF;
  RETURN NULL;
  END IF;
  RETURN  NULL;
END;



$$ LANGUAGE 'plpgsql'; 
ALTER FUNCTION coches.fn_marca_audit() OWNER TO postgres;



CREATE TRIGGER tb_marca_tg_audit AFTER INSERT OR UPDATE OR DELETE
   ON coches.tb_marca FOR EACH ROW
   EXECUTE PROCEDURE coches.fn_marca_audit();

Con esto está haciendo los insert correctamente pero falla cuando hago un update en la tabla original, he probado varias cosas: -Si pongo:

       UPDATE coches_2.tb_marca_log SET ("marca", "matricula", "usuario_creador", "updated_date", "action","user_id","action_datetime")
   = (NEW.marca, NEW.matricula, NEW.usuario_creador, NEW.updated_date, 'INSERT', USER, now());

Me da un error de duplicado de PK.

-Si pongo OLD.marca entonces me dice que no está asignado.

-Si quito ese campo directamente entonces me modifica todos.

0

1 respuesta 1

0

Hay algunos detalles que no entiendo del todo en tu pregunta.

  1. Me parece raro que una auditoría esté dispuesto a perder información de los cambios. Eso de que solamente quieres guardar una copia del último estado de un registro no suena como una buena auditoría.
  2. No queda claro lo que deseas hacer en caso de UPDATE o DELETE. Asumo que quieres seguir el mismo patrón de hacer un insert/update en la tabla tb_marca_log dependiendo de la existencia de un registro con la misma clave primaria.
  3. Espero que has diseñado el campo marca para que no puede ser modificada. Esto te puede causar problemas. Lo ideal es que la clave primaria sea un campo numérico auto-generado que nunca cambia.

En todo caso, poniendo a un lado las dudas que tengo, el problema principal que veo en lo que has intentado es que tu sentencia UPDATE no tiene claúsula WHERE marca = .... Creo que corregir este detalle te va ayudar mucho.

De lo que entiendo, creo que la función debería parecerse a lo siguiente:

CREATE OR REPLACE FUNCTION coches.fn_marca_audit() RETURNS trigger AS $$
BEGIN

  if tg_op in ('INSERT', 'UPDATE') then
    if not exists (select null from coches_2.tb_marca_log where marca = new.marca) then
      insert into coches_2.tb_marca_log (marca, matricula, usuario_creador, updated_date, action, user_id, action_datetime)
      values (new.marca, new.matricula, new.usuario_creador, new.updated_date, tg_op, user, now());
    else
      update coches_2.tb_marca_log
         set matricula = new.matricula,
             usuario_creador = new.usuario_creador,
             updated_date = new.updated_date,
             action = tg_op,
             user_id = user,
             action_datetime = now()
       where marca = new.marca;
    end if;

    return new;
  else -- DELETE
    if not exists (select null from coches_2.tb_marca_log where marca = old.marca) then
      insert into coches_2.tb_marca_log (marca, matricula, usuario_creador, updated_date, action, user_id, action_datetime)
      values (old.marca, old.matricula, old.usuario_creador, old.updated_date, tg_op, user, now());
    else
      update coches_2.tb_marca_log
         set matricula = old.matricula,
             usuario_creador = old.usuario_creador,
             updated_date = old.updated_date,
             action = tg_op,
             user_id = user,
             action_datetime = now()
       where marca = old.marca;
    end if;

    return old;
  end if;
END
$$ LANGUAGE plpgsql;

Demostración en vivo.


Si estás usando PostgreSQL 9.5 o más reciente, te recomiendo de simplificar el patrón if not exists then insert else update end if para mas bien usar la sentencia INSERT ... ON CONFLICT DO UPDATE ... que maneja el INSERT/UPDATE automáticamente de un solo, y maneja mejor situaciones donde hay concurrencia.

Usando este diferente sabor de la sentencia INSERT resultaría en la función siguiente:

CREATE OR REPLACE FUNCTION coches.fn_marca_audit() RETURNS trigger AS $$
BEGIN

  if tg_op in ('INSERT', 'UPDATE') then
    insert into coches_2.tb_marca_log (marca, matricula, usuario_creador, updated_date, action, user_id, action_datetime)
    values (new.marca, new.matricula, new.usuario_creador, new.updated_date, tg_op, user, now())
    on conflict(marca)
    do update
    set matricula = excluded.matricula,
        usuario_creador = excluded.usuario_creador,
        updated_date = excluded.updated_date,
        action = excluded.action,
        user_id = excluded.user_id,
        action_datetime = excluded.action_datetime;

    return new;
  else -- DELETE
    insert into coches_2.tb_marca_log (marca, matricula, usuario_creador, updated_date, action, user_id, action_datetime)
    values (old.marca, old.matricula, old.usuario_creador, old.updated_date, tg_op, user, now())
    on conflict(marca)
    do update
    set matricula = excluded.matricula,
        usuario_creador = excluded.usuario_creador,
        updated_date = excluded.updated_date,
        action = excluded.action,
        user_id = excluded.user_id,
        action_datetime = excluded.action_datetime;

    return old;
  end if;
END
$$ LANGUAGE plpgsql;

Demostración en vivo.

1
  • Muchísimas gracias @sstan me ha servido perfecto. He tenido que hacer dos pequeñísimas adaptaciones y he aprendido mucho. Gracias de nuevo. Saludos ^^
    – Anna_MS
    el 14 dic. 2016 a las 9:29

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.