return: text
lang: plpgsql
src: |
  DECLARE	
  	f_finess_oid integer;
  	f_finess_code TEXT;
  	f_dbhost TEXT;
  	f_dbname TEXT;
  	f_dbport TEXT;
  	x_credentials base.user_credentials;
  	x_link_cstring TEXT;
  	view_def TEXT;
  	first_db TEXT;
  
  	oidField TEXT;
  	oidFieldComplete TEXT;
  	oidFieldText TEXT;
  	ch TEXT;
  	table_name TEXT;
  	sumField TEXT;
  	selectCmd TEXT;
  	selectCmdBase TEXT;
  	temp_cursor refcursor;
  	oids_array TEXT;
  	oids_array_bis TEXT;
  	oids_array_toapply TEXT;
  	oids_array_bis_toapply TEXT;
  	onmaxpercent integer;
  	onmaxnumber integer;
  	winteger integer;
  	select_percent integer;
  	other_percent integer;
  	onfield_text TEXT;
  	rec RECORD;
  BEGIN
  
  	-- Informations de connexion communes
    SELECT * INTO x_credentials FROM base.cti_user_credentials();
  
  	view_def = 'DROP VIEW IF EXISTS pmsi.v_consolidation_imports_controles_1;  CREATE OR REPLACE VIEW pmsi.v_consolidation_imports_controles_1 AS ';
  	first_db = '1';
  	selectCmd = 'SELECT DISTINCT t_finess.oid, t_finess.code, t_finess_database.dbhost, t_finess_database.dbname, t_finess_database.dbport
  			FROM base.t_finess, base.t_finess_database 
  			WHERE t_finess.oid = t_finess_database.finess_id AND t_finess_database.dbname != ''''
  			ORDER BY t_finess_database.dbname';
  	OPEN temp_cursor FOR 
  	EXECUTE selectCmd;  
  	FETCH temp_cursor INTO f_finess_oid, f_finess_code, f_dbhost, f_dbname, f_dbport;
  	WHILE FOUND LOOP
  		IF (first_db != '1') THEN
  			view_def = view_def || ' UNION ALL ';
  		END IF;
  		first_db = '0';
  
  		x_link_cstring = format('host=%s port=%s dbname=%s user=%s password=%s',
  			f_dbhost,
  			f_dbport,
  			f_dbname,
  			x_credentials.login,
  			x_credentials.password
  		);
  
  		view_def = view_def || format('(SELECT %s AS finess_id, %L::text AS finess_code, p_imports_controles.* FROM dblink(%L, %L, true) AS %s)',
  	  		f_finess_oid,
  		    f_finess_code,
  		    x_link_cstring,
  		    'SELECT import_id, data_type, no_ligne, ligne, erreur, gravite, champ, commentaire, position, longueur FROM pmsi.p_imports_controles',
  		    'p_imports_controles(import_id bigint, data_type text, no_ligne numeric, ligne text, erreur text, gravite numeric, champ text, commentaire text, position numeric, longueur numeric)'
  		);
  
  		FETCH temp_cursor INTO f_finess_oid, f_finess_code, f_dbhost, f_dbname, f_dbport;
  	END LOOP;
  	CLOSE temp_cursor;
  
  	-- Fermeture de la boucle, fin de la requête générée, complétée par affectation du propriétaire
  	view_def = view_def || ';';
  	view_def = view_def || 'ALTER TABLE pmsi.v_consolidation_imports_controles_1 OWNER TO ' || x_credentials.login;
  
  	EXECUTE view_def;
  	RETURN view_def;
  END;