DROP FUNCTION IF EXISTS public.update_contract (
    INTEGER,
    INTEGER,
    VARCHAR(20),
    VARCHAR(50),
    VARCHAR(100),
    TIMESTAMP
);

CREATE OR REPLACE FUNCTION public.update_contract (
    p_contract_id           INTEGER,                
    p_rate_id               INTEGER,                
    p_contractor_id_number  VARCHAR(20)  DEFAULT NULL,
    p_contractor_name       VARCHAR(50)  DEFAULT NULL,
    p_contractor_surname    VARCHAR(100) DEFAULT NULL,
    p_contract_init_date    TIMESTAMP     DEFAULT NULL
)
RETURNS INTEGER
AS $$
BEGIN
    PERFORM 1
    FROM   public.contracts
    WHERE  id = p_contract_id;
    IF NOT FOUND THEN
        RAISE EXCEPTION
            'No existe ningún contrato con id %', p_contract_id;
    END IF;

    PERFORM 1
    FROM   public.rates
    WHERE  id = p_rate_id;
    IF NOT FOUND THEN
        RAISE EXCEPTION
            'No existe ninguna tarifa con id %', p_rate_id;
    END IF;

    UPDATE public.contracts
    SET
        contractoridnumber = COALESCE(p_contractor_id_number, contractoridnumber),
        contractorname     = COALESCE(p_contractor_name,      contractorname),
        contractorsurname  = COALESCE(p_contractor_surname,   contractorsurname),
        contractinitdate   = COALESCE(p_contract_init_date,   contractinitdate),
        rateid             = p_rate_id
    WHERE id = p_contract_id;

    RETURN p_contract_id;
END;
$$ LANGUAGE plpgsql VOLATILE;