Untitled

mail@pastecode.io avatar
unknown
pgsql
2 years ago
490 B
4
Indexable
execute <<-SQL
  CREATE FUNCTION facility_bookings_count_trg() RETURNS TRIGGER AS
  $$
  BEGIN
    IF TG_OP IN ('UPDATE', 'DELETE') THEN
      UPDATE facilities SET bookings_count = bookings_count - 1 WHERE id = old.temp_fid AND old.status = 'completed';
    END IF;
    IF TG_OP IN ('INSERT', 'UPDATE') THEN
      UPDATE facilities SET bookings_count = bookings_count + 1 WHERE id = new.temp_fid AND new.status = 'completed';
    END IF;
    RETURN NULL;
  END
  $$
  LANGUAGE plpgsql;
SQL