-- update instructions:
-- psql -U davical_dba davical < caldav_functions-fix.sql
DROP TRIGGER collection_modified ON collection CASCADE;
CREATE or REPLACE FUNCTION collection_modified() RETURNS TRIGGER AS $$
DECLARE
BEGIN
  -- in case we trigger on other events in future
  IF TG_OP = 'UPDATE' THEN
    IF NEW.dav_name != OLD.dav_name THEN
      UPDATE caldav_data
        SET dav_name = replace( dav_name, OLD.dav_name, NEW.dav_name),
            user_no = NEW.user_no
      WHERE substring(dav_name from 1 for char_length(OLD.dav_name)) = OLD.dav_name;
    END IF;
    RETURN NEW;
  ELSIF TG_OP = 'DELETE' THEN
    -- On delete we remove all properties for the collection
    DELETE FROM property WHERE dav_name=OLD.dav_name;
    RETURN OLD;
  END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER collection_modified AFTER UPDATE OR DELETE ON collection
    FOR EACH ROW EXECUTE PROCEDURE collection_modified();
