CREATE FUNCTION busqueda_en_tabla(_esquema character varying, _tabla character varying, _columna character varying[], _tdcolumna character varying[], _valor character varying[], _operador character varying[], _union character varying) RETURNS SETOF record
    LANGUAGE plpgsql
    AS $$
DECLARE
    _consulta TEXT;
    _fconsulta TEXT;
    _columnas VARCHAR(50)[];
    _td_columnas VARCHAR(50)[];
    _rep BOOLEAN;
    _cant INTEGER;
    _rec RECORD;
    _nodo INTEGER; 
BEGIN
    _consulta := E'E\'SELECT * FROM '||_esquema||'.'||_tabla||' WHERE ';

    _cant := (array_length(_columna, 1));
    FOR i IN 1.._cant LOOP
	IF i = 1 THEN
	    _consulta := _consulta||_columna[i]||' '||_operador[i]||E' \\\''||_valor[i]||E'\\\'::'||_tdcolumna[i];
	ELSE
	    _consulta := _consulta||' '||_union||' '||_columna[i]||' '||_operador[i]||E' \\\''||_valor[i]||E'\\\'::'||_tdcolumna[i];
	END IF;
    END LOOP;
    
    _consulta := _consulta||E'\'';
    
    SELECT replicada, columnas, td_columnas INTO _rep, _columnas, _td_columnas FROM ods_cluster.tb_descripcion_tabla WHERE esquema = _esquema AND nombre = _tabla;
	
    IF _rep THEN
    	SELECT nextval INTO _nodo FROM nextval('ods_cluster.round_robin_nodo');
    	_fconsulta := E'SELECT * FROM ods_cluster.fn_consulta_dinamica('||_consulta||E', '||_nodo||') AS t (';
    ELSE
    	_fconsulta := E'SELECT * FROM ods_cluster.fn_consulta_dinamica('||_consulta||E') AS t (';
    END IF;  

    _cant := (array_length(_td_columnas, 1));
    FOR i IN 1.._cant LOOP
	IF i = 1 THEN
	    _fconsulta := _fconsulta||_columnas[i]||' '||_td_columnas[i];
	ELSE
	    _fconsulta := _fconsulta||', '||_columnas[i]||' '||_td_columnas[i];
	END IF;
    END LOOP;
   
    _fconsulta := _fconsulta||')';

    FOR _rec IN EXECUTE _fconsulta
    LOOP
        RETURN NEXT _rec;
    END LOOP;
END;
$$;
