简体   繁体   中英

Postgres trigger check amount before delete

I am trying to create a postgres before trigger to check the amount of records that are going to be deleted before it actually does. For example to not delete more than 5 records

You could achieve that with an AFTER DELETE statement-level trigger. Inside the trigger function you can count the number of affected rows and throw an exception if the count is too high. The exception will force a rollback of the transaction that initiated the delete.

create function prevent_delete()
  returns trigger
as
$BODY$ 
declare
  l_count integer;
begin 
  select count(*)
    into l_count
  from old_table;

  if l_count > 5 then 
    raise exception 'Too many rows would be deleted';
  end if; 
  return null;
end; 
$BODY$ 
LANGUAGE plpgsql;

And then create the trigger:

create trigger prevent_mass_delete 
   after delete on the_table
   referencing old table as old_table
   for each statement 
   execute procedure prevent_delete();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM