<?php
$MODULE="pmsi";
$TITLE="Consolidation PMSI";
$DFTENDSTATUS="OK";
$ARGS="-raz";
/** Laisser les lignes 2 à 5 sans changer la casse et sans espaces et dans cet ordre
 * car le script est lu et analysé quand il est exécuté via .exe ou Jenkins
 * pour gestion des fichiers .pid dans system\batch\logs
 */

global $ENDSTATUS;
global $iCTI_connexion;
global $ADMPROVIDER;
global $ADMPROVIDER2;
global $ADMPROVIDER_PREFIX;
global $ADMPROVIDER2_PREFIX;
global $ENV_TYPEETS;
global $ENV_ADM_ANNEEDEBUT;
global $nbE;
global $PROPERTY_SENSPARAMETRE_CLASSE;
global $ENV_CONSO_PMSI_ANNEE_DEBUT;

require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/lib/cti/Batch/iCTI_batch_common.php" );
require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/lib/cti/Database/Database2Factory.class.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/lib/cti/Environnement/Environnement.class.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/lib/cti/EnvironmentSettings/EnvironmentDatabaseSettings.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/classSimpleXML.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/outils/php/httpService_cacheManager_cleanCache.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/pmsi/php/EtudeManager.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/pmsi/import_rss_rsf/utils/conso_functions.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/pmsi/import_rss_rsf/utils/import_functions.php");
require_once(dirname(dirname(dirname(__FILE__))) . "/base/php/utils/cti_args_functions.php");

logStartMsg();


if (iCTI_connect()) {

	// création du répertoire utilisé par la fonction base.cti_copy_table(i_fromdblink text, i_fromtable text, i_totable text)
	if (!is_dir('C:/TEMP')) {
		mkdir('C:/TEMP');
	}
	
	consolidation_environnements();

	logInfoMsg("Nettoyage cache");
	cleanAllCache("iCTI_pmsi", TRUE);
		
	iCTI_disconnect();
}



logEndMsg("CONSOLIDATION PMSI");


// récupération historique
function consolidation_environnements() {

	global $iCTI_connexion;
	global $environments_settings;
	global $PROPERTY_SENSPARAMETRE_CLASSE;
	global $ENV_FINESS_PRINCIPAL;
	global $ENV_CONSO_PMSI_ANNEE_DEBUT;
	global $ENV_CONSO_PMSI_DELETE_BEFORE_YEAR;


	//////////////   PARAMETRE DE COMMANDE   /////////////
	// Arguments transmis 
	$cti_args = new CTI_Args_class();

	// -xx || --except-expert
	$expert = get_cti_args_expert($cti_args);

	// -xe || --except-essentiels
	$essentiels = get_cti_args_essentiels($cti_args);

	// -env
	$forced_env = get_cti_args_env($cti_args);

	// --moisforces || -mf
	// --annee-mois-force || -af
	$moisforces = get_cti_args_mois_forces($cti_args);
	if ($moisforces !== "0"){
		$ENV_CONSO_PMSI_ANNEE_DEBUT = find_min_year($moisforces);
	}


	///////////   PARAMETRAGE ENVIRONNEMENT   /////////// 
	$environmentVars=array();
    $environmentVars["EXPERT"] = $expert;
    $environmentVars["ESSENTIELS"] = $essentiels;
	$environmentVars["FINESS_PRINCIPAL"] = $ENV_FINESS_PRINCIPAL;
	$environmentVars["CONSO_PMSI_ANNEE_DEBUT"] = $ENV_CONSO_PMSI_ANNEE_DEBUT;
	$environmentVars["MOISFORCES"] = $moisforces;
		

	///////////   INITIALISTATION : INIT  ///////////
	$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATION_2.XML",$iCTI_connexion,$environmentVars);
	$cti_sqlStatements->executeStatementsNode("INIT");
	
	
	///////////   CONSOLIDATION : GETENV ///////////
	$executed = false;
	foreach ($environments_settings as $environment) {
		$possibilites_env_name = array('',  strtolower($environment["code"]),  strtolower($environment["dbname"]));
		if (in_array($forced_env, $possibilites_env_name)){
			$environmentVars["DBNAME"] = $environment["dbname"];
			$environmentVars["DBPORT"] = $environment["dbport"];
			$environmentVars["DBHOST"] = $environment["dbhost"];
			$environmentVars["DBUSERNAME"] = $environment["dbusername"];
			$environmentVars["DBPASSWORD"] = $environment["dbpassword"];
			$environmentVars["FINESS"] = $environment["finess"];
			$environmentVars["FINESS_TEXTE"] = $environment["texte"];
			$environmentVars["PPX"] = $environment["ppx"];
			$environmentVars["IPX"] = $environment["ppx"]."000000000000";
			$environmentVars["PREFIX"] = $environment["code"];
			$environmentVars["SENSPARAMETRE_CLASSE"] = $PROPERTY_SENSPARAMETRE_CLASSE;
			
			createTempConso($environmentVars);
			
			$cti_sqlStatements_finess = new CTI_SqlStatements_class("iCTI_import_pmsi_CONSOLIDATION_2.XML",$iCTI_connexion,$environmentVars);
			$cti_sqlStatements_finess->executeStatementsNode("GETENV");
			$executed = true;
		}
	}

	if (!$executed) {
		logErrorMsg("Aucun établissement n'a été trouvé dans les settings");
		die_conso();
	}
		
	///////////   POST TRAITEMENT : POST  ///////////

	// Suppression des séjours Et intégrité des la bdd
	nettoyage_sejours_bdd($ENV_CONSO_PMSI_DELETE_BEFORE_YEAR);
	
	$cti_sqlStatements->executeStatementsNode("POST");
	

}



function iCTI_connect() {


global $iCTI_connexion;
global $PROPERTY_SENSPARAMETRE_CLASSE;
global $environments_settings;
global $ENV_FINESS_PRINCIPAL;
global $ENV_CONSO_PMSI_ANNEE_DEBUT;
global $ENV_CONSO_PMSI_DELETE_BEFORE_YEAR;


    $PROPERTY_SENSPARAMETRE_CLASSE = "M";
	
	
	$iCTI_connexion = FALSE;
	
	$file = "../../../settings/settings.XML";
	$settings_xml = simplexml_load_file($file);
	
	$ENV_CONSOLIDATION = "0";
	// On traite l'année en cours + 2 années par défault 
	$ENV_CONSO_PMSI_ANNEE_DEBUT = transform_AX_in_annee_mois("A2");
	// Supprimer les séjours avant une année AX donnée dans les settings
	$ENV_CONSO_PMSI_DELETE_BEFORE_YEAR= false;

	$properties =  $settings_xml->xpath("/SETTINGS/ENVIRONMENT/PROPERTY");

	foreach ($properties as $propertyNode) {
		if ($propertyNode['name'] == 'CONSOLIDATION') {
			$ENV_CONSOLIDATION = $propertyNode['value'];
		}
		if ($propertyNode['name'] == 'FINESS') {
			$ENV_FINESS_PRINCIPAL = $propertyNode['value'];
		}
		if ($propertyNode['name'] == 'CONSO_PMSI_ANNEE_DEBUT') {
			$ENV_CONSO_PMSI_ANNEE_DEBUT = transform_AX_in_annee_mois($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'CONSO_PMSI_DELETE_BEFORE_YEAR') {
			$year_AX = $propertyNode['value'];
			if (is_year_AX($year_AX)){
				//On garde au moins l'année en cours + 2 ans au cas où
				$year_mini_delete_before = date("Y") - 2;
				$year_delete_before = transform_AX_in_year($year_AX);
				if ($year_delete_before <= $year_mini_delete_before){
					$ENV_CONSO_PMSI_DELETE_BEFORE_YEAR = $year_delete_before;
				}
			}
		}
	}
	
	if ($ENV_CONSOLIDATION != "1") {
		logErrorMsg("Environnement NON CONSOLIDE");
		return FALSE;
	}
	
	$conso_properties=  $settings_xml->xpath("/SETTINGS/CONSOLIDATION/PROPERTY");
	foreach ($conso_properties as $conso_propertyNode) {
		if ($conso_propertyNode['name'] == 'SENSPARAMETRE_CLASSE') {
			$PROPERTY_SENSPARAMETRE_CLASSE = utf8_decode($propertyNode['value']);
		}
	}
	
	$environment_error = FALSE;
	$environments_settings = array();
	$environments =  $settings_xml->xpath("/SETTINGS/CONSOLIDATION/ENVIRONMENT");
	foreach ($environments as $environmentNode) {

		$environment_dir = "";
		$environment_finess = "";
		$environment_texte = "";
		$environment_dbname = "";
		$environment_port = "";
		$environment_username = "";
		$environment_password = "";
		$environment_code = "";
		$environment_oid = "";

		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'ENVIRONMENT') {
				$environment_texte = utf8_decode($propertyNode['value']);
			}
			if ($propertyNode['name'] == 'DIR') {
				$environment_dir = trim($propertyNode['value']);
			}
			if ($propertyNode['name'] == 'PREFIX_CODE') {
				$environment_code = trim($propertyNode['value']);
			}
			if ($propertyNode['name'] == 'PREFIX_OID') {
				$environment_oid = trim($propertyNode['value']);
			}
		}
		
        //Chaine de connexion
        $dbSettings = new EnvironmentDatabaseSettings($environment_dir);
        try {
            $dbSettings->readSettings();
        } catch (Exception $e) {
            logErrorMsg($e->getMessage());
            $environment_error = TRUE;
        }
        
        $environment_host = $dbSettings->getHost();
        $environment_port = $dbSettings->getPort();
        $environment_dbname = $dbSettings->getName();
        $environment_username = $dbSettings->getUsername();
        $environment_password = $dbSettings->getPassword();
		
		if (file_exists($environment_dir . "/settings/settings.xml")) {
			$environment_settings_xml = simplexml_load_file($environment_dir . "/settings/settings.xml");
			if ($environment_settings_xml) {
				foreach ($environment_settings_xml->ENVIRONMENT as $toEnvironmentNode) {
					foreach ($toEnvironmentNode->PROPERTY as $toPropertyNode) {
						if ($toPropertyNode['name'] == 'FINESS') {
							$environment_finess = trim($toPropertyNode['value']);
						}
						if ($toPropertyNode['name'] == 'ENVIRONMENT') {
							$environment_texte = utf8_decode($toPropertyNode['value']);
						}
					}
				}
			}
		}
		else {
			logErrorMsg("iCTI_connect : Fichier settings de l'environnement non trouvé, vérifier le DIR du '$environment_texte' dans les settings du consolidé");
			$environment_error = TRUE;
		}
		
		if ($environment_dbname == "") {
			logErrorMsg("iCTI_connect : Nom de la base de donnée non trouvé");
			$environment_error = TRUE;
		}
		if ($environment_finess == "") {
			logErrorMsg("iCTI_connect : Finess non trouvé");
			$environment_error = TRUE;
		}
		
		if ($environment_error == TRUE) {
			logErrorMsg("iCTI_connect : Environnement '$environment_texte' sur '$environment_dir' inexistant ou mal configuré");
			logErrorMsg("iCTI_connect : Au moins un environnement de la consolidation n'est pas correct");
			return FALSE;
		}


		$environment = array();
		$environment["dir"] = $environment_dir;
		$environment["finess"] = $environment_finess;
		$environment["texte"] = $environment_texte;
		$environment["dbname"] = $environment_dbname;
		$environment["dbport"] = $environment_port;
		$environment["dbhost"] = $environment_host;
		$environment["dbusername"] = $environment_username;
		$environment["dbpassword"] = $environment_password;		
		$environment["code"] = ($environment_code != '' ? $environment_code : substr($environment_dbname, 5));
		$environment["ppx"] =  ($environment_oid != '' ? $environment_oid : substr($environment_dbname, 5));
		$environments_settings[] = $environment;
	}

	$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
	$ret = $iCTI_connexion->connect();
	if (!$ret) {
		logErrorMsg("La connexion PostgreSQL iCTI a échoué");
		return FALSE;
	}
	
	return $ret;

}


function createTempConso($environment) {
    global $iCTI_connexion;
	global $MODULE;
	
	$copyCmd = "SELECT base.cti_copy_table(''dbname=" . $environment['DBNAME'] . " port=" . $environment['DBPORT'] . " host=" . $environment['DBHOST'] . " user=" . $environment['DBUSERNAME'] . " password=" . $environment['DBPASSWORD'] . "'', ''
					SELECT * FROM %s WHERE 1=1 %s'', ''temp tmp_push'');";
	$tmpParamSql = "
    DROP TABLE IF EXISTS fp
    ;
    CREATE TABLE fp AS
    VALUES
        ('idx'::text, '".$environment['PPX']."000000000000'::text),
		('idc'::text, '".$environment['PREFIX']."'::text),
		('pas'::text, '999999999999'::text),
	    ('finess'::text, '".$environment['FINESS']."'::text)
	;
    
	DROP FUNCTION IF EXISTS fp(text)
	;
	CREATE FUNCTION fp(text)
		RETURNS text AS
		\$BODY\$
			SELECT column2 FROM fp WHERE column1 = \$1
			;
		\$BODY\$
	LANGUAGE 'sql' VOLATILE
	;

	DROP FUNCTION IF EXISTS fp_in(text)
	;
	CREATE FUNCTION fp_in(text)
		RETURNS setof text AS
		\$BODY\$
			SELECT column2 FROM fp WHERE column1 = \$1
			;
		\$BODY\$
	LANGUAGE 'sql' VOLATILE
	;
	
	-- Retourne l'oid 0 (non renseigne) meme si la plage d'ids prestataire est differente. 
	DROP FUNCTION IF EXISTS getOid(bigint)
    ;
	CREATE FUNCTION getOid(bigint)
		RETURNS bigint AS
		\$BODY\$
			SELECT case when \$1 = 0 then 0::bigint else \$1 + fp('idx')::bigint end
			;
		\$BODY\$
	LANGUAGE 'sql' VOLATILE
	;
   
	
	DROP TABLE IF EXISTS w_cor_col;
	CREATE TABLE w_cor_col AS
	SELECT column_name, COALESCE(table_name_1, table_name_2) || '_cor' AS cor_table
	FROM (
		SELECT column_name, regexp_replace(regexp_replace(column_name,'_id_.*',''),'_id$','') as target FROM information_schema.columns
		WHERE (column_name ~'_id$' or column_name ~ '_id_') AND table_schema = '" . $MODULE . "'  AND table_schema = '" . $MODULE . "'  and column_name not like '%section%' and table_name not like 'v%') col
	LEFT JOIN (
		SELECT table_name AS table_name_1, regexp_replace(regexp_replace(RIGHT(table_name,-2),'([^s])s$','\\1'),'s_','_') as table_root
		FROM information_schema.tables WHERE  (table_schema = '" . $MODULE . "'  OR table_schema = 'base') and table_name not like 'v%'
	) tab on table_root = target
	LEFT JOIN (
		SELECT table_name as table_name_2
		FROM information_schema.tables WHERE  (table_schema = '" . $MODULE . "'  OR table_schema = 'base') and table_name not like 'v%'
	) tab_2 on CASE 
		WHEN column_name like '%sejour_id' or column_name like '%sej_id' then 'p_sejours'
		WHEN column_name like '%seq_id' then 'p_sequences'
		WHEN column_name like '%rpss_id' then 'p_rpss'
		WHEN column_name like '%postal%_id' then 't_codes_postaux'
		WHEN column_name like '%diagnostic%' then 't_diagnostics'
		WHEN column_name like '%geste_marqueur%' then 't_gestes_marqueurs'
		WHEN column_name like '%type_ucd_id' then 't_type_ucd'
		WHEN column_name like '%ucd_id' then 't_ucd'
		WHEN column_name like '%tarifaire%' then 'p_zone_tarifaire'
		WHEN column_name like '%prestation%_' then 't_prestations'
		WHEN column_name like '%acte%' then 't_actes'
		WHEN column_name like '%import%' then 't_imports'
		WHEN column_name like '%acte_%' then 't_actes'
		WHEN column_name like '%ghm_%' then 't_ghm'
		WHEN column_name like '%ghs_%' then 't_ghs'
		WHEN column_name like '%dp_id' then 't_diagnostics'
		WHEN column_name like 'rss_mere_id' then 'p_rss'
		WHEN column_name like 'medecin_rss_id' then 't_medecins'
		WHEN column_name like 'medecin_rum_id' then 't_medecins'
		WHEN column_name like '%unite_medicale%' then 't_unites_medicales'
		WHEN column_name like '%etablissement%' then 't_etablissements'
		WHEN column_name like '%pec_fj%' then 't_pec_fj'
		WHEN column_name like '%pec%' then 't_pec'
		WHEN column_name like '%regime%' then 't_grands_regimes'
		WHEN column_name like '%mat2a%' then 't_imports_mat2a'
		WHEN column_name like '%comite_medical%' then 't_comites_medicaux'
		WHEN column_name like '%code_geographique%' then 't_codes_geographiques_pmsi'
		WHEN column_name like '%facturation_18%' then 't_facturation_18euros'
		WHEN column_name like '%um_%_id%' then 't_unites_medicales'
		WHEN column_name like '%code_retour%' then 't_codes_retour_groupeur'
		WHEN column_name like '%cas_id' then 't_cas'
		WHEN column_name like '%gm%_id' then 't_gestes_marqueurs'
		WHEN column_name like '%cardio_famille_acte_id' then 't_etude_cardio_familles_actes'
		WHEN column_name like '%cardio_mention_id' then 't_etude_cardio_mentions'
		WHEN column_name like '%cardio_modalite_id' then 't_etude_cardio_modalite'
		END = table_name_2
	GROUP BY 1,2
	ORDER BY 2
	;
	
	-- Retourne l'oid corrigé
	DROP FUNCTION IF EXISTS getCorTable(text)
    ;
	CREATE FUNCTION getCorTable(_col text)
		RETURNS text AS
		\$BODY\$
			SELECT cor_table FROM w_cor_col WHERE column_name = _col
			;
		\$BODY\$
	LANGUAGE 'sql' VOLATILE
	;
	
	-- Ajout des lignes sans decalage general d'oid ni prfixe code/code_original (tables en t_)
	DROP FUNCTION IF EXISTS merge_table(text)
	;
	CREATE FUNCTION merge_table(_table text)
	 RETURNS void AS
		\$BODY\$
		DECLARE  field text;
		DECLARE  I bigint;
		DECLARE _corTable text;
		DECLARE _columns text;
		DECLARE _oid_condition text;
		DECLARE _condition text;
		DECLARE _table_name text;
		BEGIN
		I := fp('idx');
		_table_name = split_part(_table,'.',2);
		EXECUTE format('" .
			$copyCmd  ."
			',	_table, _condition);
		IF (SELECT count(*) > 0 FROM information_schema.columns 
			WHERE table_name = 'tmp_push'
			AND column_name ~ 'id$' AND NOT column_name ~ '^section' and column_name != 'oid') THEN
			FOREACH field IN ARRAY (
				SELECT array_agg(column_name::text) FROM information_schema.columns 
				WHERE table_name = 'tmp_push'
				AND column_name ~ 'id$' AND NOT column_name ~ '^section' and column_name != 'oid')
				LOOP
					RAISE NOTICE 'in %', field;
					EXECUTE format('SELECT getCorTable(''%s'')', field) INTO _corTable;
					IF (SELECT count(*) > 0 FROM information_schema.tables WHERE table_name = _corTable AND table_schema = 'temp') 
					THEN
						EXECUTE format('UPDATE tmp_push SET %s = cible_id FROM temp.%s WHERE %s = source_id', field, _corTable, field);
					END IF;
				END LOOP;
		END IF;
		
		EXECUTE format('SELECT array_to_string(array_agg(column_name::text ORDER BY column_name),'','','''') FROM information_schema.columns WHERE upper(table_schema || ''.'' || table_name) = upper(''%s'') AND column_name != ''oid''',_table) 
		INTO _columns;
		IF (SELECT count(*) > 0 FROM information_schema.columns WHERE column_name = 'oid' AND table_name = 'tmp_push') 
		THEN
			EXECUTE format('DROP TABLE IF EXISTS temp.%s_cor;

			CREATE TABLE temp.%s_cor AS
			SELECT
				source.code AS source_code,
				source.oid AS source_id,
				COALESCE(cible.oid,source.oid + fp(''idx'')::bigint) AS cible_id
			FROM tmp_push AS source 
				LEFT JOIN %s AS cible ON source.code = cible.code
				;
			',_table_name,_table_name,_table);
			
			UPDATE tmp_push SET oid = oid + fp('idx')::bigint;
			_oid_condition = ' AND oid <> 0';
		
			EXECUTE format('INSERT INTO pmsi.p_consolidation_translation(from_code, from_database, from_id, table_code, to_code, to_id )
			SELECT source_code, ''". $environment['DBNAME'] . "'', source_id, t_listes_tables.code, source_code, cible_id FROM temp.%s_cor JOIN pmsi.t_listes_tables ON name = ''%s''', _table_name, _table_name);
		
		END IF;
		
		EXECUTE format('INSERT INTO %s (%s) SELECT %s FROM tmp_push WHERE code NOT IN (SELECT code from %s) AND code::text != '''' AND code::text != '' '' AND code IS NOT NULL %s', _table, _columns, _columns, _table, _oid_condition );
		
		
		
		END;
		\$BODY\$
	LANGUAGE plpgsql VOLATILE
	;
	
	
	 
    -- Synchronise les donnees en décalant oid et code/code_original
	DROP FUNCTION IF EXISTS merge_prod(text,text)
	;
	CREATE FUNCTION merge_prod(_table text, _condition text)
	RETURNS void AS
		\$BODY\$
		DECLARE  field text;
		DECLARE  I bigint;
		DECLARE _corTable text;
		DECLARE _columns text;
		DECLARE _table_name text;
		DECLARE  has_code bool;
		DECLARE  has_code_original bool;
		DECLARE  req text;
		BEGIN
		I := fp('idx');
		_table_name = split_part(_table,'.',2);
		EXECUTE format('" .
			$copyCmd  ."
			',	_table, _condition);
		IF (SELECT count(*) > 0 FROM information_schema.columns 
			WHERE table_name = 'tmp_push'
			AND column_name ~ 'id$' AND NOT column_name ~ '^section' AND column_name != 'oid') THEN
			FOREACH field IN ARRAY (
				SELECT array_agg(column_name::text) FROM information_schema.columns 
				WHERE table_name = 'tmp_push'
				AND (column_name ~ '_id$' OR column_name ~ '_id_') AND NOT column_name ~ '^section' AND column_name != 'oid')
				LOOP
					EXECUTE format('SELECT getCorTable(''%s'')', field) INTO _corTable;
					IF (SELECT count(*) > 0 FROM information_schema.tables WHERE table_name = _corTable AND table_schema = 'temp') 
					THEN
						EXECUTE format('UPDATE tmp_push SET %s = cible_id FROM temp.%s WHERE source_id = %s', field, _corTable,field);
					END IF;
					
				END LOOP;
		END IF;
		
		IF (SELECT '" . $environment['PREFIX'] . "' != '' AND count(*) > 0 FROM information_schema.columns 
			WHERE table_name = 'tmp_push'
			AND column_name = 'code_original')
		THEN
			has_code_original = true;
		END IF;
		IF (SELECT '" . $environment['PREFIX'] . "' != '' AND count(*) > 0 FROM information_schema.columns 
			WHERE table_name = 'tmp_push'
			AND column_name = 'code')
		THEN
			has_code = true;
		END IF;
		
		IF (SELECT count(*) > 0 FROM information_schema.columns 
			WHERE table_name = 'tmp_push'
			AND column_name = 'oid')
		THEN
			EXECUTE format('DROP TABLE IF EXISTS temp.%s_cor;

			CREATE TABLE temp.%s_cor AS
			SELECT
				oid AS source_id,
				oid + fp(''idx'')::bigint AS cible_id
				FROM tmp_push
				;
						   
			CREATE INDEX %s_cor_i_source ON  temp.%s_cor USING btree (source_id);
			CREATE INDEX %s_cor_i_dest ON  temp.%s_cor USING btree (source_id)
			',_table_name,_table_name,_table_name,_table_name,_table_name,_table_name);

			UPDATE tmp_push SET oid = oid + fp('idx')::bigint;

			EXECUTE format('DELETE FROM %s WHERE oid IN (SELECT cible_id FROM temp.%s_cor)', _table, _table_name);
			IF has_code_original THEN 
				UPDATE tmp_push SET code_original = '" . $environment['PREFIX'] . "' || '_' || code_original;
			END IF;
			IF has_code THEN 
				UPDATE tmp_push SET code = '" . $environment['PREFIX'] . "' || '_' || code;
				EXECUTE format('ALTER TABLE temp.%s_cor ADD COLUMN source_code text;
				ALTER TABLE temp.%s_cor ADD COLUMN to_code text;
				UPDATE temp.%s_cor SET source_code = code FROM tmp_push WHERE source_id = oid;
				UPDATE temp.%s_cor SET to_code = code FROM tmp_push WHERE source_id = oid;;
				INSERT INTO pmsi.p_consolidation_translation(from_code, from_database, from_id, table_code, to_code, to_id )
					SELECT source_code, ''". $environment['DBNAME'] . "'', source_id, t_listes_tables.code, source_code, cible_id FROM temp.%s_cor JOIN pmsi.t_listes_tables ON name = ''%s''',_table_name, _table_name, _table_name,_table_name ,_table_name, _table_name);
		
			END IF;
			
		END IF;
		EXECUTE format('SELECT array_to_string(array_agg(column_name::text ORDER BY column_name),'','','''') FROM information_schema.columns WHERE upper(table_schema || ''.'' || table_name) = upper(''%s'')',_table)
		INTO _columns;
		
		EXECUTE format('INSERT INTO %s (%s) SELECT %s FROM tmp_push', _table, _columns, _columns );
		
		END;
		\$BODY\$
	LANGUAGE plpgsql VOLATILE
	";

	$iCTI_connexion->query($tmpParamSql);
}


    
?>