--checagem utilizada pelas ajudas
CREATE OR REPLACE FUNCTION gtcgnccheckhelp() 
RETURNS trigger as $BODY$
DECLARE
    v_result boolean;
BEGIN

    IF ( TG_OP = 'UPDATE' )
    THEN
        IF ( (NEW.form = OLD.form) )
        THEN
            IF ( NEW.subform IS NOT NULL )
            THEN
                IF ( NEW.subform = OLD.subform )
                THEN
                    RETURN NEW;
                END IF;
            ELSE
                RETURN NEW;
            END IF; 
        END IF;
        
        RAISE EXCEPTION 'Não é possível alterar o formulário deste registro.';    
    ELSE
        IF (NEW.subform IS NULL )
        THEN
            SELECT into v_result count(*) = 0
            FROM gtcHelp
            WHERE form = NEW.form
                AND subform IS NULL;
        ELSE
        
            SELECT into v_result count(*) = 0 
            FROM gtcHelp
            WHERE form = NEW.form
                AND subform = NEW.subform;
        END IF;
        
        IF ( v_result )
        THEN
            RETURN NEW;
        END IF;
        
        RAISE EXCEPTION 'Já existe um registo para este formulário.';
    END IF;
    
    RETURN NULL;    

END;
$BODY$ language plpgsql;
