DROP FUNCTION IF EXISTS mocha_get_next_inst_id;

CREATE FUNCTION mocha_get_next_inst_id
(
    p_class_id INT
)
RETURNS INT
BEGIN
    DECLARE next_inst_id INT;
    SET next_inst_id = (SELECT MAX(inst_id) + 1 FROM mocha_instances WHERE tenant_id = mocha_get_current_tenant() AND class_id = p_class_id);
    IF NOT next_inst_id IS NULL THEN
        RETURN next_inst_id;
    END IF;
    RETURN 1;
END;
