DROP PROCEDURE IF EXISTS mocha_get_related_instances;

CREATE PROCEDURE mocha_get_related_instances
(
    IN p_src_inst_id INT,
	IN p_rel_inst_id INT,
	IN p_effective_date DATETIME
)
BEGIN
    DECLARE p_tenant_id INT;
    DECLARE z_effective_date DATETIME;

    SET p_tenant_id = mocha_get_current_tenant();

    IF p_effective_date IS NULL THEN
        SET z_effective_date = NOW();
    ELSE
        SET z_effective_date = p_effective_date;
    END IF;


    SELECT mocha_instances.*
    FROM mocha_instances, mocha_relationships
	WHERE mocha_instances.tenant_id = p_tenant_id
	AND mocha_relationships.tenant_id = p_tenant_id
    AND mocha_instances.id = mocha_relationships.destination_inst_id
	AND mocha_relationships.source_inst_id = p_src_inst_id
	AND mocha_relationships.relationship_inst_id = p_rel_inst_id
	AND mocha_relationships.effective_date <= z_effective_date;
	-- ORDER BY mocha_relationships.effective_date ASC;

END;