create or replace function check_movie_showtime_overlaps()
  returns trigger as $F$
declare
  new_end_time timestamp with time zone;
  conflicting_showtime record;
begin
  new_end_time := NEW.start_time + 
      ((select length_minutes
         from movies
        where id = NEW.movie_id) || ' minutes')::interval;
  select into conflicting_showtime
         ms.*, m.*
    from movie_showtimes ms,
         movies m
  where ms.id != NEW.id
    and ms.theatre_id = NEW.theatre_id
    and ms.room = NEW.room
    and ms.movie_id = m.id
    and do_times_overlap(
          NEW.start_time,
          new_end_time,
          ms.start_time,
          ms.start_time + (m.length_minutes || ' minutes')::interval)
   limit 1;
  if conflicting_showtime is not null then
    raise exception $$Ta emisja nakada si na inn, rozpoczynajc si w tej samej sali 
                    projekcyjnej '%' o godzinie %$$,
    conflicting_showtime.name, conflicting_showtime.start_time;
  else
    return NEW;
  end if;
end
$F$ language plpgsql;

