 /*!40101 SET NAMES utf8 */;
DELIMITER $$

/* ************************************************************************************************************************************************************************
	XML/Delta
************************************************************************************************************************************************************************ */	
/*
statystyki logu:

call _log_stats('USAGE','','',''); - podaje statystyke logowan userow do systemu w okresie ostatniego m-ca
call _log_stats('USAGE',60,'',''); - podaje statystyke logowan userow do systemu w okresie ostatnich 60 dni
call _log_stats('rejestracje ','','',''); - na potrzeby conrade - rejestracje do systemu

*/



DROP PROCEDURE IF EXISTS `log_XML_convert`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_XML_convert`(
	IN _MODE VARCHAR(38),
	IN _IDN INT,
	IN _STARTTIME VARCHAR(20),
	IN _ENDTIME VARCHAR(20),
	IN _GUIDLINK VARCHAR(38),
	IN _TABLE VARCHAR(38),
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200)

)
/*
	konwersja konkretnego zapisu o idn 123300:
	CALL log_XML_convert('XML2logpo.idn',123300,'','','','','',''); -- tylko zmiany
	CALL log_XML_convert('XML2logpo.idn',123300,'','','','','','all'); -- pelne dane + zmiany
	
	dla zakresu czasów wpisu do logu i opcjonalnie dla konkretnej tabeli
	CALL log_XML_convert('XML2logpo.time',0,'2012-01-01 00:00:00','2012-01-03 00:00:00','','opng','','all');
	
	dla zakresu czasów wpisu do logu i opcjonalnie dla konkretnej tabeli z śledzeniem postępu
	CALL log_XML_convert('XML2logpo.time.verbose',0,'2010-01-01 00:00:00','2016-01-03 00:00:00','','Pracownicy','','');
	
	dla guid_link i tabeli - np dla konkretnej operacji o takim guidzie
	CALL log_XML_convert('XML2logpo.guid',0,'','','{21309120319280912}','opng','','all');
	Aby zrobic select wolaj
	CALL _logpo_tools('select', 488111, '', '');
	
*/
S_log_XML_convert: BEGIN
	DECLARE _XMLM LONGTEXT;
	DECLARE _XMLD LONGTEXT; -- wywalic
	DECLARE _ROWOLD LONGTEXT;
	DECLARE _ROWNEW LONGTEXT;
	DECLARE _I INT;
	DECLARE	_CZAS TIMESTAMP;

	IF (_MODE = 'XML2logpo.idn') THEN
	    SET @start:= now(6);
        SELECT if(compressed,uncompress(info),info),czas INTO _XMLM,_CZAS FROM log WHERE idn=_IDN;

		IF @debugMODE=1 THEN SELECT "A:",timediff(now(6),@start) as czas;SET @start:= now(6);	END IF;
		
		IF LEFT(IFNULL(_XMLM,''),5)<>'<?xml' THEN 
			LEAVE S_log_XML_convert;
		END IF;

	    SET @start:= now(6);
		SET _XMLD=SUBSTRING_INDEX(SUBSTRING_INDEX(_XMLM,'<ROWDATA>',-1),'</ROWDATA>',1);
		SET _XMLM=SUBSTRING_INDEX(SUBSTRING_INDEX(_XMLM,'<METADATA>',-1),'</METADATA>',1);
		SET _ROWNEW='';
		SET _ROWOLD='';
	-- RowState: 4 - insert; 2 - delete; 8 - update - new; 1 - update - old;
		SET @row:=SUBSTRING_INDEX(SUBSTRING_INDEX(_XMLD,'<ROW RowState=',2),'<ROW RowState=',-1);
		IF MID(@row,2,1) in (4,8) THEN SET _ROWNEW=@row; ELSE SET _ROWOLD=@row; END IF;
		SET @row:=SUBSTRING_INDEX(SUBSTRING_INDEX(_XMLD,'<ROW RowState=',3),'<ROW RowState=',-1);
		IF MID(@row,2,1) in (4,8) THEN SET _ROWNEW=@row; ELSE SET _ROWOLD=@row; END IF;

		IF @debugMODE=1 THEN SELECT _IDN,_CZAS ;SELECT "B:",timediff(now(6),@start) as czas;SET @start:= now(6);	END IF;
		
		SELECT ExtractValue(_XMLM,'count(//FIELD)') INTO @ilepol;

		IF @debugMODE=1 THEN SELECT @ilepol; SELECT "C:",timediff(now(6),@start)  as czas;SET @start:= now(6); END IF;
		
		IF IFNULL(@ilepol,0)=0 THEN 
			LEAVE S_log_XML_convert;
		END IF;

		DELETE FROM logpo WHERE idnng=_IDN;

		SET _I = 1;

		IF @debugMODE=1 THEN SELECT "D:",timediff(now(6),@start) as czas;SET @start:= now(6);SET @xmlm:=_XMLM;SET @xmld:=_XMLD ;	END IF;

		SET _I = 1;
		
		REPEAT

--			SELECT ExtractValue(_XMLM,concat('//FIELDS/FIELD[',_I,']/@attrname'))  INTO @poleOLD;
			SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(_XMLM,'<FIELD attrname="',1+_I),'<FIELD attrname="',-1),'" fieldtype=',1) into @pole;
			SET @poleorig:=@pole;
--			IF @poleold<>@pole THEN SELECT @poleold,@pole; END IF;
/*
			IF @pole regexp '^[0-9]' THEN
				IF @debugMODE=1 THEN SELECT "E1:",@pole;	END IF;
				SET @pole=concat('x',@pole);
				SET _XMLD=REPLACE(_XMLD,concat(' ',@poleorig,'='),concat(' ',@pole,'='));
			END IF;
*/
			
	-- RowState: 4 - insert; 2 - delete; 8 - update - new; 1 - update - old;
--			SET @newvalold := ExtractValue(_XMLD,concat('//ROW[@rowstate=8 or @rowstate=4 or @RowState=8 or @RowState=4]/@',@pole));
-- 			SET @oldvalold := ExtractValue(_XMLD,concat('//ROW[@rowstate=1 or @RowState=1]/@',@pole));
			
			SET @pos:=IFNULL(INSTR(_ROWNEW,concat(' ',@poleorig,'=')),0);
			SET @newval:=IF(@pos=0, NULL, SUBSTRING_INDEX(mid(_ROWNEW,@pos+length(@poleorig)+3,1000000),'"',1));
			SET @pos:=IFNULL(INSTR(_ROWOLD,concat(' ',@poleorig,'=')),0);
			SET @oldval:=IF(@pos=0,'',SUBSTRING_INDEX(mid(_ROWOLD,@pos+length(@poleorig)+3,1000000),'"',1));

--			IF @oldval<>@oldvalold THEN SELECT "NIEZGODNE!",@pole,@oldval,@oldvalold; END IF;
--			IF @newval<>@newvalold THEN SELECT "NIEZGODNE!",@pole,@newval,@newvalold; END IF;
			
			IF @debugMODE=2 THEN 
				SELECT @poleorig,@oldval,@newval; 
			END IF;

			-- kolumn typu BLOB nie jestesmy w stanie tutaj poprawnie obsluzyc
			IF (ifnull(@newval,'x') <> 'x') or (@oldval<>'' and _PARAM_B='all') THEN  
				INSERT INTO `logpo` 
					(idnng, fld_name, `old`, `new`) 
				VALUES 
					(_IDN, @poleorig, QUOTE(LEFT(@oldval, 250)), QUOTE(LEFT(@newval, 250)))
				;  -- dajemy 250 a nie 255, aby pomiescic ewent. backslashe wstawione przez QUOTE()
			END IF;
			
			SET _I = _I + 1;

		UNTIL _I > @ilepol
		END REPEAT;
		IF @debugMODE=1 THEN 
			SELECT "E:",timediff(now(6),@start) as czas;SET @start:= now(6); 
		END IF;
		
		-- INSERT IGNORE INTO logpo SELECT * FROM tlp WHERE _PARAM_B='all' OR `new`<>'';
	END IF;


	IF _MODE like 'XML2logpo.guid%' THEN
		BEGIN
			DECLARE aIDN INT;
			DECLARE aTime DATETIME;
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE c_proc CURSOR FOR
			SELECT idn,czas FROM log WHERE guidlink=_GUIDLINK and (_TABLE='' or table_link=_TABLE) order by idn,czas;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			OPEN c_proc;
			  loop1: LOOP
				FETCH c_proc INTO aIDN,aTime;
				IF done THEN
					LEAVE loop1;
				ELSE
					CALL log_XML_convert('XML2logpo.idn',aIDN,'','','','',_PARAM_A,_PARAM_B);
					IF _MODE like 'XML2logpo.guid%' THEN 
						SELECT aIDN,aTime;
					END IF;	
				END IF;
			END LOOP;
			CLOSE c_proc;
		END;
	END IF;

	IF _MODE = 'XML2logpo.time' or _MODE = 'XML2logpo.time.verbose' THEN
		BEGIN		
			DECLARE aIDN INT;
			DECLARE aCount INT;
			DECLARE aCountAll INT;
			DECLARE aStartTime INT;
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE c_proc CURSOR FOR
			SELECT idn FROM log WHERE czas between _STARTTIME AND _ENDTIME and (_TABLE='' or table_link=_TABLE) ORDER by idn;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

            SELECT count(*) into aCountAll FROM log WHERE czas between _STARTTIME AND _ENDTIME and (_TABLE='' or table_link=_TABLE);
			SET aStartTime:=Time_To_Sec(now());
			SELECT "Do przetworzenia:",aCountAll,now() as Start;

			SET aCount:=0;
			OPEN c_proc;
			  loop1: LOOP
				FETCH c_proc INTO aIDN;
				IF done THEN
					LEAVE loop1;
				ELSE
					CALL log_XML_convert('XML2logpo.idn',aIDN,'','','','',_PARAM_A,_PARAM_B);
					SET aCount:=aCount+1;
					IF _MODE = 'XML2logpo.time.verbose' and mod(aCount,100)=0 THEN
					  SELECT aCount,aCountAll,aCount/(Time_To_Sec(now())-aStartTime) as zapisow_na_sek,Sec_To_Time((aCountAll-aCount)/aCount*(Time_To_Sec(now())-aStartTime)) as pozostalo;
					END IF;
					
				END IF;
			END LOOP;
			CLOSE c_proc;
			SELECT "Przetworzono zapisow:",aCount,now() as Stop,(Time_To_Sec(now())-aStartTime) as Sekund,aCount/(Time_To_Sec(now())-aStartTime) as zapisow_na_sek;
		END;
	END IF;

END$$


/* ************************************************************************************************************************************************************************
	Przygotowanie TempTabla z information_schema z danycmi zmienionymi do loga `logpo`
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `_sys_DBSCHEMA_To_LOG`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_DBSCHEMA_To_LOG`(
	IN _MODE VARCHAR(150),
	IN _DBName VARCHAR(50),
	IN _TableName1 VARCHAR(100),	
	IN _TableName2 VARCHAR(100),	
	IN _KeyFieldName VARCHAR(100),	
	IN _Key VARCHAR(100),	
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*

CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '1');
CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t;
UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t WHERE NOT t.IsEqu;
DESC opng '%time%';
SELECT @_SQLText;

CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM t_sys_DBSCHEMA_To_LOG t;

*/
SPROC: BEGIN

	DECLARE _SQLText, _SQLTextUpdateCase, _SQLTextUpdateOR, _SQLTextUpdateCols, _SQLTextUpdate, _SQLFullText TEXT;
	SET 
		_DBName = IF(IFNULL(_DBName, '') = '', DATABASE(), _DBName)
	;
	IF _MODE = 'Prepare.Schema' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
		CREATE TEMPORARY TABLE `t_sys_DBSCHEMA_To_LOG`
			SELECT 
				c.COLUMN_NAME AS fld_name,  
				_VarStr('') AS OLD,
				_VarStr('') AS NEW,
				(1=0) AS IsEqu
			FROM information_schema.`COLUMNS` c
			WHERE 
				TABLE_SCHEMA = _DBName
				AND TABLE_NAME = _TableName1
		;
		ALTER TABLE `t_sys_DBSCHEMA_To_LOG` ADD UNIQUE KEY fld_name (fld_name), ADD KEY IsEqu(IsEqu);
		INSERT IGNORE INTO `t_sys_DBSCHEMA_To_LOG` 
			SELECT 
				c.COLUMN_NAME AS fld_name,  
				_VarStr('') AS OLD,
				_VarStr('') AS NEW,
				(1=0) AS IsEqu
			FROM information_schema.`COLUMNS` c
			WHERE 
				TABLE_SCHEMA = _DBName
				AND TABLE_NAME = _TableName2
		;
		DELETE FROM `t_sys_DBSCHEMA_To_LOG` WHERE fld_name IN ('IDN', 'GUID', 'localtime', 'remotetime', 'tag');
		
		/****************************************************************************************************************************
		Do SQLText daj mi 
			UPDATE `t_sys_DBSCHEMA_To_LOG` t		
		****************************************************************************************************************************/
		SET _SQLTextUpdateCase = '', _SQLTextUpdateOR = '', _SQLTextUpdateCols = '';
		BEGIN
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE _fld_name VARCHAR(250);
			DECLARE c_proc CURSOR FOR
				SELECT
					t.fld_name
				FROM `t_sys_DBSCHEMA_To_LOG` t
				;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			OPEN c_proc;
			loop1: LOOP
				FETCH c_proc INTO _fld_name;
				IF done THEN
					LEAVE loop1;
				END IF;
				SET @X = 'bbb';
				SET _SQLTextUpdateCase = 
					CONCAT(_SQLTextUpdateCase,
						'WHEN "', _fld_name, '" THEN _VarStr(CONCAT(#tx#.',_fld_name, '))',
						'\n'
					)
				;
				SET _SQLTextUpdateOR = 
					_ConcatTxt(_SQLTextUpdateOR,
						CONCAT('!(t1.', _fld_name, ' <=> t2.', _fld_name, ')'),
						'\n OR \n'
					)
				;
			END LOOP;
			CLOSE c_proc;
			DROP TEMPORARY TABLE IF EXISTS `t_FIND_ORIG`;
		END;
		SET _SQLTextUpdate =
		"
UPDATE `t_sys_DBSCHEMA_To_LOG` t, `#_TableName1#` t1, `#_TableName2#` t2 
SET
t.old = 
CASE t.fld_name
#OLD#
END,
t.new = 
CASE t.fld_name
#NEW#
END
WHERE
	t1.#_KeyFieldName# = '#KEY#'
	AND
	t2.#_KeyFieldName# = t1.#_KeyFieldName#
	AND
	(
#OR#
	)
;
		"
		;
	--	Dla #OLD#
		SET _SQLTextUpdateCols = REPLACE(_SQLTextUpdateCase, '#tx#', 't2');
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#OLD#', _SQLTextUpdateCols);
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_TableName1#', _TableName1);

	--	Dla #NEW#
		SET _SQLTextUpdateCols = REPLACE(_SQLTextUpdateCase, '#tx#', 't1');
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#NEW#', _SQLTextUpdateCols);

		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#OR#', _SQLTextUpdateOR);
		
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_TableName2#', _TableName2);
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_KeyFieldName#', _KeyFieldName);
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#KEY#', _Key);
		
		SET _SQLText = _SQLTextUpdate;
		SET @_SQLText = _SQLText;
		CASE _Param_B
		WHEN '' THEN
			CALL _ExecuteCmd(_SQLText, @Error);
			UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
			DELETE FROM `t_sys_DBSCHEMA_To_LOG` WHERE IsEqu;
		WHEN 'Select' THEN
			CALL _ExecuteCmd(_SQLText, @Error);
			UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
			SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t WHERE NOT t.IsEqu;
			DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
		WHEN 'SQL' THEN
			SELECT @_SQLText;
		ELSE
			SELECT @_SQLText;
		END CASE;
	END IF;
				
END$$

DROP PROCEDURE IF EXISTS `_Two_comapare_Rec_TempTables_To_LOG`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_Two_comapare_Rec_TempTables_To_LOG`(
	IN _MODE VARCHAR(150),
	IN _IDN_LOG INTEGER,
	IN _SCHEMA VARCHAR(50),		-- _DBName
	IN _NativeTableName_rec VARCHAR(100),	
	IN _TempTableName_OLD_rec VARCHAR(100),	
	IN _TempTableName_NEW_rec VARCHAR(100),	
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*

CALL _Two_comapare_Rec_TempTables_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', '', '1');
CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t;
UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t WHERE NOT t.IsEqu;
DESC opng '%time%';
SELECT @_SQLText;

CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM t_sys_DBSCHEMA_To_LOG t;

*/
SPROC: BEGIN

	DECLARE _SQLText, _SQLTextUpdateCaseOLD, _SQLTextUpdateCaseNEW, _SQLTextUpdateOR, _SQLTextUpdateCols, _SQLTextUpdate, _SQLFullText TEXT;
	SET 
		_SCHEMA = IF(IFNULL(_SCHEMA, '') = '', SCHEMA(), _SCHEMA)
	;
	IF _MODE = 'Create.`t_FieldNames`' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_FieldNames`;
		-- show CREATE TABLE `t_editable_cols`;
		CREATE TEMPORARY TABLE `t_FieldNames` (
			`FieldName` VARCHAR(250) NOT NULL DEFAULT '',		-- Col_NameAs
			PRIMARY KEY `FieldName`(`FieldName`)
		)
		;
	END IF;
	
	IF _MODE = 'CreateTableCompare' THEN
		SET
		@_IDN_LOG = 1460463;
		SET
		@_TableCompare_OLD = CONCAT('ta_comp_OLD_', _IDN_LOG),
		@_TableCompare_NEW = CONCAT('ta_comp_NEW_', _IDN_LOG),
		@_SQLTextDropTable = 
"
"		
;
		SET @_SQLTextDropTable.OLD = REPLACE(@_SQLTextDropTable, '#TABLE#', @_TableCompare_OLD);
		SET @_SQLTextDropTable.NEW = REPLACE(@_SQLTextDropTable, '#TABLE#', @_TableCompare_NEW);
		CALL _ExecuteCmd(@_SQLTextDropTable.OLD, @Error);
		CALL _ExecuteCmd(@_SQLTextDropTable.NEW, @Error);
		SET
		@_SQLTextCreateTable = 
"
CREATE TABLE `#TABLE#`SELECT * FROM `#_TempTableName_rec#`;
"		
;
		SET @_SQLTextCreateTable.OLD = REPLACE(@_SQLTextCreateTable, '#TABLE#', @_TableCompare_OLD);
		SET @_SQLTextCreateTable.OLD = REPLACE(@_SQLTextCreateTable.OLD, '#_TempTableName_rec#', _TempTableName_OLD_rec);
		SET @_SQLTextCreateTable.NEW = REPLACE(@_SQLTextCreateTable, '#TABLE#', @_TableCompare_NEW);
		SET @_SQLTextCreateTable.NEW = REPLACE(@_SQLTextCreateTable.NEW, '#_TempTableName_rec#', _TempTableName_NEW_rec);
		CALL _ExecuteCmd(@_SQLTextCreateTable.OLD, @Error);
		CALL _ExecuteCmd(@_SQLTextCreateTable.NEW, @Error);
	
	END IF;
	
	IF _MODE LIKE 'Prepare.Schema%' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_fields_DBSCHEMA_To_LOG`;
		CREATE TEMPORARY TABLE `t_fields_DBSCHEMA_To_LOG` (
			`FieldName` VARCHAR(250) NOT NULL DEFAULT '',		-- Col_NameAs
			`OLD_Value` LONGTEXT,						-- Fetch
			`NEW_Value` LONGTEXT,						-- Fetch
			`IsEqu` BOOLEAN,
			`FieldExists` BOOLEAN,
			PRIMARY KEY `FieldName`(`FieldName`)
		)
		;
									-- set @.watch.log.comp = null;
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '1');
		
		INSERT IGNORE INTO `t_fields_DBSCHEMA_To_LOG`
			SELECT 
				c.COLUMN_NAME AS FieldName,  
				_VarStr('') AS OLD,
				_VarStr('') AS NEW,
				FALSE AS IsEqu,
				FALSE AS FieldExists
			FROM information_schema.`COLUMNS` c
			WHERE 
				TABLE_SCHEMA = _SCHEMA
				AND TABLE_NAME = _NativeTableName_rec -- _TempTableName_OLD_rec
		;
		-- ALTER TABLE `t_sys_DBSCHEMA_To_LOG` ADD UNIQUE KEY FieldName (FieldName), ADD KEY IsEqu(IsEqu);
		INSERT IGNORE INTO `t_fields_DBSCHEMA_To_LOG` 
			SELECT 
				c.COLUMN_NAME AS FieldName,  
				_VarStr('') AS OLD,
				_VarStr('') AS NEW,
				FALSE AS IsEqu,
				FALSE AS FieldExists
			FROM information_schema.`COLUMNS` c
			WHERE 
				TABLE_SCHEMA = _SCHEMA
				AND TABLE_NAME = _TempTableName_NEW_rec
		;
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '2');
		-- DELETE FROM `t_sys_DBSCHEMA_To_LOG` WHERE FieldName IN ('IDN', 'GUID', 'localtime', 'remotetime', 'tag');
		IF _MODE = 'Prepare.Schema.with.`t_FieldNames`' THEN
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '2.1');
			UPDATE `t_fields_DBSCHEMA_To_LOG` tf, `t_FieldNames` tfn
			SET
				tf.FieldExists = TRUE
			WHERE
				tfn.FieldName = tf.FieldName
			;
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '2.2');
		ELSE
			UPDATE `t_fields_DBSCHEMA_To_LOG` tf
			SET
				tf.FieldExists = TRUE
			;
		END IF;
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '3');
	--	Teraz jeszce usun nie obslugiwane kolumny NOT FieldExists	
		DELETE FROM `t_fields_DBSCHEMA_To_LOG` WHERE NOT FieldExists;
		
		/****************************************************************************************************************************
		Do SQLText daj mi 
			UPDATE `t_sys_DBSCHEMA_To_LOG` t		
		****************************************************************************************************************************/
		SET _SQLTextUpdateCaseOLD = '', _SQLTextUpdateCaseNEW = '', _SQLTextUpdateOR = '', _SQLTextUpdateCols = '';
		BEGIN
			DECLARE done BOOL DEFAULT FALSE;
			DECLARE _fld_name VARCHAR(250);
			DECLARE c_proc CURSOR FOR
				SELECT
					t.FieldName
				FROM `t_fields_DBSCHEMA_To_LOG` t
				;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
			OPEN c_proc;
			loop1: LOOP
				FETCH c_proc INTO _fld_name;
				IF done THEN
					LEAVE loop1;
				END IF;
				SET @X = 'bbb';
				SET _SQLTextUpdateCaseOLD = 
					CONCAT(_SQLTextUpdateCaseOLD,
						'WHEN "', _fld_name, '" THEN (OLD.',_fld_name, ')',
						'\n'
					)
				;
				SET _SQLTextUpdateCaseNEW = 
					CONCAT(_SQLTextUpdateCaseNEW,
						'WHEN "', _fld_name, '" THEN (NEW.',_fld_name, ')',
						'\n'
					)
				;
				SET _SQLTextUpdateOR = 
					_ConcatTxt(_SQLTextUpdateOR,
						CONCAT('!(t1.', _fld_name, ' <=> t2.', _fld_name, ')'),
						'\n OR \n'
					)
				;
			END LOOP;
			CLOSE c_proc;
			DROP TEMPORARY TABLE IF EXISTS `t_FIND_ORIG`;
		END;
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '4');
		SET _SQLTextUpdate =
		"
UPDATE `t_sys_DBSCHEMA_To_LOG` t, `#_TempTableName_OLD_rec#` OLD, `#_TempTableName_NEW_rec#` NEW 
SET
t.old = 
CASE t.fld_name
#OLD#
END,
t.new = 
CASE t.fld_name
#NEW#
END
WHERE
	TRUE 
	-- t1.#_KeyFieldName# = '#KEY#'
	-- AND
	-- t2.#_KeyFieldName# = t1.#_KeyFieldName#
	-- AND
;
		"
		;
	--	Dla #OLD#
		-- SET _SQLTextUpdateCols = REPLACE(_SQLTextUpdateCase, '#tx#', 't2');
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#OLD#', _SQLTextUpdateCaseOLD);
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_TempTableName_OLD_rec#', _TempTableName_OLD_rec);

	--	Dla #NEW#
		-- SET _SQLTextUpdateCols = REPLACE(_SQLTextUpdateCase, '#tx#', 't1');
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#NEW#', _SQLTextUpdateCaseNEW);

		-- SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#OR#', _SQLTextUpdateOR);
		
		SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_TempTableName_NEW_rec#', _TempTableName_NEW_rec);
		-- SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#_KeyFieldName#', _KeyFieldName);
		-- SET _SQLTextUpdate = REPLACE(_SQLTextUpdate, '#KEY#', _Key);
		
									-- set @.watch.log.comp = concat_ws('/', @.watch.log.comp, '9');
		SET _SQLText = _SQLTextUpdate;
		SET @_SQLText = _SQLText;
		CASE _Param_B
		WHEN '' THEN
			CALL _ExecuteCmd(_SQLText, @Error);
			UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
		LEAVE SPROC;
			DELETE FROM `t_sys_DBSCHEMA_To_LOG` WHERE IsEqu;
		WHEN 'Select' THEN
			CALL _ExecuteCmd(_SQLText, @Error);
			UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
			SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t WHERE NOT t.IsEqu;
			DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
		WHEN 'SQL' THEN
			SELECT @_SQLText;
		ELSE
			SELECT @_SQLText;
		END CASE;
	END IF;
				

END$$

DROP PROCEDURE IF EXISTS `log_Insert_from_ng_e`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_Insert_from_ng_e`(
	IN _MODE VARCHAR(150),
	OUT	_IDN INTEGER,
	IN _IdnUser VARCHAR(150),	
	IN _Miejsce VARCHAR(150),	
	IN _Czynnosc VARCHAR(150),	
	IN _GuidLink VARCHAR(150),	
	IN _IP VARCHAR(150),	
	IN _Info TEXT,
	IN _TableName1 VARCHAR(100),	
	IN _TableName2 VARCHAR(100),	
	IN _KeyFieldName VARCHAR(100),	
	IN _Param_G VARCHAR(50)	
)
/*
		CALL log_Insert_from_ng_e(
				'INSERT', @_IDN,
				@session.Registration.UserLogin, 
				10303, 
				1111, 
				@IdnOper, 
				@session.Registration.IP, 
				'???????????????', 
				'opng_e', 'opng', 'GUID', 
				''
		);		
*/
S_log_Insert_from_ng_e: BEGIN
	CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', _TableName1, _TableName2, _KeyFieldName, _GuidLink, '', '');
    SELECT COUNT(*) INTO @C.t_sys_DBSCHEMA_To_LOG FROM `t_sys_DBSCHEMA_To_LOG`;
	/****************************************************************************************************************
		Gdy wstawiane _Czynnosc = 2 to zawsze wstawiamy do `log` czyli log_Insert() i tylko do nagłówka - na szczescie 
			dla wstawiania @C.t_sys_DBSCHEMA_To_LOG = 0 czyli nie wstawiamy do `logpo`
		ale !!!
		gdy edycja czyli _Czynnosc = 3 to wstawiamy do `logpo` tylko wtedy gdy coś się zmieniło 
			czyli @C.t_sys_DBSCHEMA_To_LOG > 0 !!!
	****************************************************************************************************************/
	IF (@C.t_sys_DBSCHEMA_To_LOG > 0) OR  (_Czynnosc = 2) THEN
		CALL log_Insert(
				'INSERT', _IDN,	_IdnUser, _Miejsce, _Czynnosc, _GuidLink, IF(_IP != '', _IP, @session.Registration.IP), 
				_Info, -- Info
				''
		);		
		INSERT INTO `logpo`
			(idnng, fld_name, `old`, `new`) 
			SELECT 
				_IDN, 
				t.fld_name, 
				-- było 2021-04-23 IFNULL(t.old, '<brak>'), IFNULL(t.new, '<brak>') 
				QUOTE(t.old), QUOTE(t.new) 
			FROM `t_sys_DBSCHEMA_To_LOG` t 
			WHERE 
				NOT t.IsEqu
		;
		
	END IF;
	DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
END$$


DROP PROCEDURE IF EXISTS `log_Insert_from_TE_xxng`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_Insert_from_TE_xxng`(
	IN _MODE VARCHAR(150),
	OUT	_IDN INTEGER,
	IN _OPER VARCHAR(250),
	IN _FROM VARCHAR(250),
	IN _Key VARCHAR(38),	--	IdnOper/IdnNg
	IN _Param_A VARCHAR(250)	
)
/*
		CALL log_Insert_from_TE_xxng(
				'', @_IDN,
				'INSERT', 
				'OP', 
				@IdnOper, 
				''
		);		
*/
S_log_Insert_from_TE_xxng: BEGIN
	DECLARE _SQLText TEXT;
	SET @_OPER = _OPER;

	IF @SYSTEM.Client.Session.log_USER_GUID IS NULL THEN
	--	w razie W pobierz zmienne
		CALL _sessions_APP('SET.VAR', @SYSTEM.Client.Session.GUID, '', '', '', '', '');
	END IF;
	IF _OPER = 'EDIT' THEN
		SET @_World = IF(IFNULL(_Param_A, '') <> '', _Param_A, 'TE');
		SET 
			@TableName.1 = '#xxng#', 
			@TableName.2 = '#xxng#'
		;
		CALL _Cmd_xxNgPo_Tools('SQL', _FROM, @_World, '', '', '', '', '', '', '', @TableName.1);
		CALL _Cmd_xxNgPo_Tools('SQL', _FROM, 'R', '', '', '', '', '', '', '', @TableName.2);
		CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 
			@TableName.1, -- bylo IF(_FROM = 'OP', 'TE_opng', 'TE_zmng'), 
			@TableName.2, -- bylo IF(_FROM = 'OP', 'opng', 'zmng'), 
			'GUID', _Key, '', ''
		);
		
        SELECT COUNT(*) INTO @C.t_sys_DBSCHEMA_To_LOG FROM `t_sys_DBSCHEMA_To_LOG`;
	ELSE
		SET @C.t_sys_DBSCHEMA_To_LOG = 0;
	END IF;

		
	/****************************************************************************************************************
		Gdy wstawiane _Czynnosc = 2 to zawsze wstawiamy do `log` czyli log_Insert() i tylko do nagłówka - na szczescie 
			dla wstawiania @C.t_sys_DBSCHEMA_To_LOG = 0 czyli nie wstawiamy do `logpo`
		ale !!!
		gdy edycja czyli _Czynnosc = 3 to wstawiamy do `logpo` tylko wtedy gdy coś się zmieniło 
			czyli @C.t_sys_DBSCHEMA_To_LOG > 0 !!!
	****************************************************************************************************************/
	SET
		_SQLText = 
		"
		INSERT INTO `log` 
		(useridn, miejsce, czynnosc, guidlink, table_link, ip, info, osobaguid, IDSession)
			SELECT
				@session.INFO.User_Login,
				CASE od.grupa
					WHEN @ht.ZM THEN 4
					WHEN @ht.RO THEN 5
					WHEN @ht.KS THEN 6
					WHEN @ht.BN THEN 7
					ELSE 3
				END AS Miejsce,
				-- IF(IFNULL(_Miejsce, '') != '', _Miejsce, 0),
				IF(@_OPER = 'INSERT', 2, 3) AS Czynnosc, 
				-- IF(IFNULL(_Czynnosc, '') != '', _Czynnosc, -1), 
				IFNULL(n.guid, '') AS guidlink,
				-- IF(@_FROM = 'OP', 'opng', 'zmng') AS table_link,
				'#TE_xxng#' AS table_link,
				IFNULL(@session.INFO.Host_IP, @session.CurrMACAddresses) AS IP,
				-- IFNULL(@_Info,'') AS info,
				CONCAT(
					IF(@_OPER = 'INSERT', 'Wstawianie z ', IF(@_OPER = 'EDIT', 'Zapis po edycji w ', IF(@_OPER = 'DELETE', 'Usuwanie z ', ''))),
					'`#TE_xxng#`'
				) AS info,
				@SYSTEM.Client.Session.log_USER_GUID AS osobaguid,
				@SYSTEM.Client.Session.GUID AS IDSession
				
			FROM `#xxng#` n, `operdoc` od
			WHERE	
				n.GUID = #_IdnOper#
				AND od.Rodzaj = n.Rodzaj
		;
	"
	;
	CALL _ExecuteCmd_xxNgPo('', _FROM, '', _Key, '', '', '', '', '', _SQLText);
	-- bylo CALL _ExecuteCmd_NgPo('', _FROM, '', _Key, '', '', '', '', '', _SQLText);
	SET @_SQLText.C_HT_TE_EXECUTE.LOG = @_SQLText.C_HT_TE_EXECUTE;
	
	/*
	to tylko test ... usun to
		INSERT INTO `log` 
		(useridn, miejsce, czynnosc, guidlink, table_link, ip, info, IDSession)
		select
			@session.INFO.User_Login,
			0,
			IF(IFNULL(@_OPER, '') = 'INSERT', 2, 3) AS Czynnosc, 
			_Key AS guidlink,
			'???' AS table_link,
			IFNULL(@session.INFO.Host_IP, @session.CurrMACAddresses) AS IP,
			CONCAT(
				'Wstawianie - @_OPER: ', IFNULL(@_OPER, 'is Null'),
				'\n SQL: \n',
				@_SQLText.C_HT_TE_EXECUTE.LOG
			) AS info,
			@SYSTEM.Client.Session.GUID AS IDSession
		;
	*/
	
	SET _IDN = LAST_INSERT_ID(), @session.connection.ID := CONNECTION_ID();
	
	IF (@C.t_sys_DBSCHEMA_To_LOG > 0) THEN
		INSERT INTO `logpo`
			(idnng, fld_name, `old`, `new`) 
			SELECT 
				_IDN, t.fld_name, 
				-- było 2021-04-23 IFNULL(t.old, '<brak>'), IFNULL(t.new, '<brak>') 
				QUOTE(t.old), QUOTE(t.new) 
			FROM `t_sys_DBSCHEMA_To_LOG` t 
			WHERE 
				NOT t.IsEqu
		;
		
	END IF;
	DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
END$$

/* ************************************************************************************************************************************************************************
	Ogólne
************************************************************************************************************************************************************************ */	

					/*
					Kiedys w pliku sys_log_insert 
					*/
					DROP PROCEDURE IF EXISTS `sys_log_insert`$$
					CREATE DEFINER=`root`@`localhost` PROCEDURE `sys_log_insert`(
						IN _miejsce INT,
						IN _czynnosc INT,
						IN _guidlink VARCHAR(50),
						IN _info TEXT
					)
						MODIFIES SQL DATA
					BEGIN
						-- DECLARE _userlogin VARCHAR(255) DEFAULT NULL;
						-- SET _userlogin = @session.CheckLogonUserLogin;

					--	jmamm  21 VII 2024 dopisał ...
						SET 
							@session.CheckLogonUserLogin = 
								IFNULL(@session.Registration.UserLogin, IFNULL(@SYSTEM.Client.Session.log_USER, '<system>'))
						;
						CALL log_Insert('INSERT', 
							@Idn, 
							@session.CheckLogonUserLogin, 
							_miejsce,
							_czynnosc,
							_guidlink, 
							'',  -- IP
							_info, 
							'.'
							);	
					END$$


DROP PROCEDURE IF EXISTS `log_Insert`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_Insert`(
	IN _MODE VARCHAR(150),
	OUT	_IDN INTEGER,
	IN _IdnUser VARCHAR(150),	
	IN _Miejsce VARCHAR(150),	
	IN _Czynnosc VARCHAR(150),	
	IN _GuidLink VARCHAR(150),	
	IN _IP VARCHAR(150),	
	IN _Info TEXT,
	IN _Table VARCHAR(50)	
)
S_log_Insert: BEGIN
	IF @SYSTEM.Client.Session.log_USER_GUID IS NULL THEN
	--	w razie W pobierz zmienne
		CALL _sessions_APP('SET.VAR', @SYSTEM.Client.Session.GUID, '', '', '', '', '');
	END IF;
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'INSERT'
		Logowanie via `login`
		Parametry
			_IdnUser	Login osoby
			_Miejsce	miejsce
			_Czynnosc	czynnosc
			_GuidLink	guidlink
			_IP	ip
			_Info	info
			_Param_G	
		CALL log_Insert('INSERT', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
		CALL log_Insert('INSERT', @Idn, _IdnUser, _Miejsce, _Czynnosc, '{GUID}', _IP, 'infotext', 'opng');
		CALL log_Insert('INSERT.Rozlicz', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
		CALL log_Insert('INSERT.Odrozlicz', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
		CALL log_Insert('INS.IdnUser', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
		CALL log_Insert('INS.OsobaGUID', @Idn, 'USERGUID', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
		CALL log_Insert('INS.Session', @Idn, 'SESJA', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'INSERT' THEN
-- set @X = concat_WS('.', @X, 'Log.1');	
-- set @X = concat_WS('.', @X, 'Log.2');	
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_log_guids` (guid varchar(38),info varchar(255));
        SELECT count(*) INTO @t_log_guids.ile FROM `t_log_guids`;
		IF @t_log_guids.ile=0 THEN
		    INSERT INTO t_log_guids VALUES (_GUIDLink,NULL);
		END IF;
		SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, @session.Registration.HostName); 
		SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, @SYSTEM.Client.Session.log_Host); 
		SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, 'local'); 
		
		
		SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, @session.Registration.IP);
		SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, @SYSTEM.Client.Session.log_Host);	--	w @SYSTEM.Client.Session.log_Host mamy IP
		SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, ''); 

		SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @session.Registration.MCAddress);
		SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @SYSTEM.Client.Session.log_MACAddress);
		SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, ''); 
		
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @session.Registration.UserLogin); 
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @SYSTEM.Client.Session.log_USER); 
		SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, '<by procedure call>'); 
	--	jmamm  21 VII 2024 dopisał ...
		SET 
			@session.CheckLogonUserLogin = 
				IFNULL(@session.Registration.UserLogin, IFNULL(@SYSTEM.Client.Session.log_USER, '<system>'))
		;

		SET _IP = IF(IFNULL(_IP, '') != '', _IP, IFNULL(@session.INFO.INSERT.LOG.ip, ''));
		SET _IdnUser = IF(IFNULL(_IdnUser, '') != '', _IdnUser, IFNULL(@session.INFO.User_Login, ''));
		
set @X = concat_WS('.', @X, 'Log.4');	
		INSERT INTO `log` (useridn, miejsce, czynnosc, guidlink, table_link, ip, info, osobaguid, IDSession)
		SELECT
			IF(IFNULL(_IdnUser, '') != '', _IdnUser, @session.CheckLogonUserLogin),
			IF(IFNULL(_Miejsce, '') != '', _Miejsce, 0),
			IF(IFNULL(_Czynnosc, '') != '', _Czynnosc, -1), 
			IFNULL(t.guid, ''),
			IFNULL(_Table, ''),
			IF(IFNULL(_IP, '') != '', _IP, Concat(@session.CurrMyCompNameStr, ' ', @session.CurrMyIPOnly, ' ', @session.CurrMACAddresses)),
			IFNULL(t.Info, IFNULL(_Info,'')),
			@SYSTEM.Client.Session.log_USER_GUID AS osobaguid,
			@SYSTEM.Client.Session.GUID
			
		FROM `t_log_guids` t;
		SET _IDN = LAST_INSERT_ID(),@session.connection.ID := CONNECTION_ID();
		DROP TEMPORARY TABLE IF EXISTS `t_log_guids`;
	END IF;	--	IF _MODE = 'INSERT'
-- TODO: uzupelnienie pola log.table_link (opng, zmng, kontrah itp)

	IF _MODE IN ('INSERT.Rozlicz','INSERT.Odrozlicz') THEN
		SET @opis:=IF(_MODE = 'INSERT.Rozlicz','Rozliczenie','Odrozliczenie');
		CREATE TEMPORARY TABLE IF NOT EXISTS t_log_guids (guid varchar(38),info varchar(255));
		INSERT INTO t_log_guids SELECT _GUIDLink,@opis;
		INSERT INTO t_log_guids SELECT idnoper2,@opis FROM rozrach WHERE idnoper=_GUIDLink;
		CALL log_Insert('INSERT', @Idn, _IdnUser, _Miejsce, _Czynnosc, '', _IP, '', 'opng');
		DROP TEMPORARY TABLE IF EXISTS t_log_guids;
	END IF;	--	IF _MODE = 'INSERT.Rozlicz'

	IF _MODE LIKE 'INS.%' THEN
-- set @X = concat_WS('.', @X, 'Log.1');	
-- set @X = concat_WS('.', @X, 'Log.2');	
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_log_guids` (guid varchar(38), info TEXT);
        SELECT count(*) INTO @t_log_guids.ile FROM `t_log_guids`;
		IF @t_log_guids.ile=0 THEN
		    INSERT INTO t_log_guids VALUES (_GUIDLink, _Info);
		END IF;
		
		IF _MODE IN ('INS.IdnUser', 'INS.OsobaGUID') THEN
		/*****************************
			NOWOSC
			CALL log_Insert('INS.IdnUser', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
			w _IdnUser jest rzeczywiście _IdnUser ale w 
			CALL log_Insert('INS.OsobaGUID', @Idn, 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
			w _IdnUser jest log_USER_GUID
		*****************************/
			SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, @session.Registration.HostName); 
			SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, @SYSTEM.Client.Session.log_Host); 
			SET @session.CurrMyCompNameStr = IFNULL(@session.CurrMyCompNameStr, 'local'); 
			
			
			SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, @session.Registration.IP);
			SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, @SYSTEM.Client.Session.log_Host);	--	w @SYSTEM.Client.Session.log_Host mamy IP
			SET @session.CurrMyIPOnly = IFNULL(@session.CurrMyIPOnly, ''); 

			SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @session.Registration.MCAddress);
			SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, @SYSTEM.Client.Session.log_MACAddress);
			SET @session.CurrMACAddresses = IFNULL(@session.CurrMACAddresses, ''); 
			
			SET _IP = IF(IFNULL(_IP, '') != '', _IP, IFNULL(@session.INFO.INSERT.LOG.ip, ''));
		--	teraz inicjalnie ustaw _IdnUser na null gdy ""
			SET _IdnUser = NULLIF(_IdnUser, '');
			IF _MODE = 'INS.IdnUser' THEN
			--	typowy historyczny tryb
				SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @session.Registration.UserLogin); 
				SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, @SYSTEM.Client.Session.log_USER); 
				SET @session.CheckLogonUserLogin = IFNULL(@session.CheckLogonUserLogin, '<by procedure call>'); 
			--	jmamm  21 VII 2024 dopisał ...
				SET 
					@session.CheckLogonUserLogin = 
						IFNULL(@session.Registration.UserLogin, IFNULL(@SYSTEM.Client.Session.log_USER, '<system>'))
				;
				SET _IdnUser = 
					IFNULL(_IdnUser, 
						IFNULL(@session.INFO.User_Login, @session.CheckLogonUserLogin)
					);
			ELSEIF _MODE = 'INS.OsobaGUID' THEN
			--	w _IdnUser jest OsobaGUID
				SET _IdnUser = 
					IFNULL(_IdnUser, 
						IFNULL(@SYSTEM.Client.Session.log_USER_GUID, 
							IFNULL(@session.Registration.UserGUID, 
								IFNULL(@session.user.UserGUID, ''
								)
							)
						)
					)
				;
			END IF;
			
	set @X = concat_WS('.', @X, 'Log.4');	
 			INSERT INTO `log` 
 			(useridn, miejsce, czynnosc, guidlink, table_link, ip, info, IDSession, OsobaGUID)
			SELECT
				ua.Login AS useridn,
				IFNULL(NULLIF(_Miejsce, ''), 0) AS miejsce,
				IFNULL(NULLIF(_Czynnosc, ''), 0) AS czynnosc, 
				IFNULL(t.guid, '') AS guidlink,
				IFNULL(_Table, '') AS table_link,
				IF(IFNULL(_IP, '') != '', _IP, Concat(@session.CurrMyCompNameStr, ' ', @session.CurrMyIPOnly, ' ', @session.CurrMACAddresses)) AS IP,
				IFNULL(t.Info, '') AS info,
				@SYSTEM.Client.Session.GUID AS IDSession,
				ua.OsobaGUID AS OsobaGUID
				
			FROM `t_log_guids` t, `_user_accounts` ua
			WHERE
				IF(_MODE = 'INS.IdnUser', 
					ua.Login = _IdnUser,
					ua.OsobaGUID = _IdnUser
				)
			;
		ELSE
		/*****************************
			NOWOSC
			CALL log_Insert('INS.Session', @Idn, 'Sesja', '100', '200', 'GUID', '127.0.0.1', 'INFO', '');
			w _IdnUser jest SESJA!!!!
		*****************************/
			IF _MODE = 'INS.Session' THEN
				SET @.IDSession = IFNULL(NULLIF(_IdnUser, ''), @SYSTEM.Client.Session.GUID);
			ELSE
			--	typowy historyczny tryb
				SET @.IDSession = @SYSTEM.Client.Session.GUID;
			END IF;
		--	w @.IDSession jest sesja
			INSERT INTO `log` 
			(useridn, miejsce, czynnosc, guidlink, table_link, ip, info, Info_View, IDSession, OsobaGUID)
			SELECT
				sl.log_USER AS useridn,
				IFNULL(NULLIF(_Miejsce, ''), 0) AS miejsce,
				IFNULL(NULLIF(_Czynnosc, ''), 0) AS czynnosc, 
				IFNULL(t.guid, '') AS guidlink,
				IFNULL(_Table, '') AS table_link,
				CONCAT_WS(' ', sl.log_Host, sl.log_Host_Name, sl.log_MACADDRESS,'') AS IP,
				-- IF(IFNULL(_IP, '') != '', _IP, Concat(@session.CurrMyCompNameStr, ' ', @session.CurrMyIPOnly, ' ', @session.CurrMACAddresses)) as ip,
				IFNULL(t.Info, '') AS info,
				IFNULL(t.Info, '') AS Info_View,
				sl.GUID AS IDSession,
				sl.log_USER_GUID AS OsobaGUID
				-- , sl.*
			FROM `t_log_guids` t, `_sys_db_logons` sl
			WHERE
				sl.GUID = @.IDSession
			;
			
		END IF;
		
		SET _IDN = LAST_INSERT_ID(),@session.connection.ID := CONNECTION_ID();
		DROP TEMPORARY TABLE IF EXISTS `t_log_guids`;
	END IF;	--	IF _MODE = 'INSERT'

	IF _MODE IN ('INSERT.tb_opng') THEN -- TODO - uogolnic
		CREATE TEMPORARY TABLE IF NOT EXISTS t_log_guids (guid varchar(38),info varchar(255));
		INSERT INTO t_log_guids SELECT t.GUID,_Info FROM tb_opng t;
		CALL log_Insert('INSERT', @Idn, _IdnUser, _Miejsce, _Czynnosc, '', _IP, '', 'opng');
		DROP TEMPORARY TABLE IF EXISTS t_log_guids;
	END IF;

	
END$$


DROP PROCEDURE IF EXISTS `_log_tools_new`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_log_tools_new`(
	IN _MODE VARCHAR(150),
	OUT	_IDN INTEGER,
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50),	
	IN _Param_C VARCHAR(50),	
	IN _Param_D VARCHAR(50),	
	IN _Param_E VARCHAR(50),	
	IN _Param_F TEXT,
	IN _Param_G VARCHAR(50)	
)
S_log_tools_new: BEGIN
	DECLARE _SQLText TEXT;
	DECLARE _OPER, _FROM, _Key, _WORLD VARCHAR(250);
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'INSERT'
		Logowanie via `login`
		Parametry
			_Param_A	Login osoby
			_Param_B	miejsce
			_Param_C	czynnosc
			_Param_D	guidlink
			_Param_E	ip
			_Param_F	info
			_Param_G	tabela
		CALL _log_tools('INSERT', 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', 'opng');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'INSERT' THEN
		CALL log_Insert('INSERT', @_IDN, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F, _Param_G);
	END IF;	--	IF _MODE = 'INSERT'


	IF _MODE IN ('log_Insert_from_TE_M_xxng') THEN
	/*************************************************************************************************************************************************
		CALL _log_tools_new('log_Insert_from_TE_M_xxng', @_IDN, 'jmam', @.OPZM.OPER, 'OP', @_IdnOper, 'TE', '', '');		
		
		CALL log_Insert_from_TE_xxng('', @_IDN, @.OPZM.OPER, _FROM, _IdnOper, _WORLD);		
		IN _MODE VARCHAR(150),
		OUT	_IDN INTEGER,
		IN _OPER VARCHAR(250),		B
		IN _FROM VARCHAR(250),		C
		IN _Key VARCHAR(38),	--	IdnOper/IdnNg DANGLING
		IN _Param_A VARCHAR(250)	param E
	*************************************************************************************************************************************************/
		SET
			_OPER = _Param_B,
			_FROM = _Param_C,
			_Key = _Param_D,	--	IdnOper/IdnNg
			_WORLD = IF(IFNULL(_Param_E, '') <> '', _Param_E, 'TE')
		;
		IF @SYSTEM.Client.Session.log_USER_GUID IS NULL THEN
		--	w razie W pobierz zmienne
			CALL _sessions_APP('SET.VAR', @SYSTEM.Client.Session.GUID, '', '', '', '', '');
		END IF;
		SET @_OPER = _OPER;
			SET @_World = _WORLD;
	
		IF _OPER = 'INSERT' THEN
			IF (@session.globals.Owner IN ('xxxxKONKOL')) THEN	-- na razie sie wstrzymaj
				LEAVE S_log_tools_new;
			END IF;
		END IF;

		IF _OPER = 'EDIT' THEN
			SET 
				@TableName.1 = '#xxng#', 
				@TableName.2 = '#xxng#'
			;
			CALL _Cmd_xxNgPo_Tools('SQL', _FROM, @_World, '', '', '', '', '', '', '', @TableName.1);
			CALL _Cmd_xxNgPo_Tools('SQL', _FROM, 'R', '', '', '', '', '', '', '', @TableName.2);
			CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 
				@TableName.1, -- bylo IF(_FROM = 'OP', 'TE_opng', 'TE_zmng'), 
				@TableName.2, -- bylo IF(_FROM = 'OP', 'opng', 'zmng'), 
				'GUID', _Key, '', ''
			);
			
            SELECT COUNT(*) INTO @C.t_sys_DBSCHEMA_To_LOG FROM `t_sys_DBSCHEMA_To_LOG`;
		ELSE
			SET @C.t_sys_DBSCHEMA_To_LOG = 0;
		END IF;

			
		/****************************************************************************************************************
			Gdy wstawiane _Czynnosc = 2 to zawsze wstawiamy do `log` czyli log_Insert() i tylko do nagłówka - na szczescie 
				dla wstawiania @C.t_sys_DBSCHEMA_To_LOG = 0 czyli nie wstawiamy do `logpo`
			ale !!!
			gdy edycja czyli _Czynnosc = 3 to wstawiamy do `logpo` tylko wtedy gdy coś się zmieniło 
				czyli @C.t_sys_DBSCHEMA_To_LOG > 0 !!!
		****************************************************************************************************************/
		SET
			_SQLText = 
			"
			INSERT INTO `log` 
			(useridn, miejsce, czynnosc, guidlink, table_link, ip, info, osobaguid, IDSession)
				SELECT
					@session.INFO.User_Login,
					CASE od.grupa
						WHEN @ht.ZM THEN 4
						WHEN @ht.RO THEN 5
						WHEN @ht.KS THEN 6
						WHEN @ht.BN THEN 7
						ELSE 3
					END AS Miejsce,
					-- IF(IFNULL(_Miejsce, '') != '', _Miejsce, 0),
					IF(@_OPER = 'INSERT', 2, 3) AS Czynnosc, 
					-- IF(IFNULL(_Czynnosc, '') != '', _Czynnosc, -1), 
					IFNULL(n.guid, '') AS guidlink,
					-- IF(@_FROM = 'OP', 'opng', 'zmng') AS table_link,
					'#xxng#' AS table_link,
					IFNULL(@session.INFO.Host_IP, @session.CurrMACAddresses) AS IP,
					-- IFNULL(@_Info,'') AS info,
					CONCAT(
						IF(@_OPER = 'INSERT', 'NOWE Wstawianie z ', IF(@_OPER = 'EDIT', 'Zapis po edycji w ', IF(@_OPER = 'DELETE', 'Usuwanie z ', ''))),
						'`#xxng#`'
					) AS info,
					@SYSTEM.Client.Session.log_USER_GUID AS osobaguid,
					@SYSTEM.Client.Session.GUID AS IDSession
					
				FROM `#xxng#` n, `operdoc` od
				WHERE	
					n.GUID = #_IdnOper#
					AND od.Rodzaj = n.Rodzaj
			;
		"
		;
		CALL _ExecuteCmd_xxNgPo('', _FROM, @_World, _Key, '', '', '', '', '', _SQLText);
		-- bylo CALL _ExecuteCmd_NgPo('', _FROM, '', _Key, '', '', '', '', '', _SQLText);
		SET @_SQLText.C_HT_TE_EXECUTE.LOG = @_SQLText.C_HT_TE_EXECUTE;
		
		SET _IDN = LAST_INSERT_ID(), @session.connection.ID := CONNECTION_ID();
		
		IF (@C.t_sys_DBSCHEMA_To_LOG > 0) THEN
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`) 
				SELECT 
					_IDN, t.fld_name, 
					-- było 2021-04-23 IFNULL(t.old, '<brak>'), IFNULL(t.new, '<brak>') 
					QUOTE(t.old), QUOTE(t.new) 
				FROM `t_sys_DBSCHEMA_To_LOG` t 
				WHERE 
					NOT t.IsEqu
			;
			
		END IF;
		DROP TEMPORARY TABLE IF EXISTS `t_sys_DBSCHEMA_To_LOG`;
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_log_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_log_tools`(
	IN _MODE VARCHAR(150),
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50),	
	IN _Param_C VARCHAR(50),	
	IN _Param_D VARCHAR(50),	
	IN _Param_E VARCHAR(50),	
	IN _Param_F TEXT,
	IN _Param_G VARCHAR(50)	
)
S_log_tools: BEGIN
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'INSERT'
		Logowanie via `login`
		Parametry
			_Param_A	Login osoby
			_Param_B	miejsce
			_Param_C	czynnosc
			_Param_D	guidlink
			_Param_E	ip
			_Param_F	info
			_Param_G	tabela
		CALL _log_tools('INSERT', 'jmam', '100', '200', 'GUID', '127.0.0.1', 'INFO', 'opng');		
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/	
	IF _MODE = 'INSERT' THEN
		CALL log_Insert('INSERT', @_IDN, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E, _Param_F, _Param_G);
		
	END IF;	--	IF _MODE = 'INSERT'

END$$


DROP PROCEDURE IF EXISTS `_logpo_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_logpo_tools`(
	IN _MODE VARCHAR(38),
	IN _IDNNg INT,
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200)

)
/*
	CALL _logpo_tools('select', 274728, '', '');
*/
S_logpo_tools: BEGIN
	IF _MODE IN ('', 'select') THEN
		IF NOT EXISTS (SELECT idn FROM `logpo` WHERE idnng = _IDNNg) THEN
			-- CALL log_XML_convert('XML2logpo.idn', _IDNNg, '', '', '', '', '', 'all'); -- 'ALL' pełne dane + zmiany
			CALL log_XML_convert('XML2logpo.idn', _IDNNg, '', '', '', '', '', ''); 
		END IF;
		SELECT
			IF(IFNULL(p.fld_DisplayLabel, '') != p.fld_name,
				_ConcatStr(IFNULL(p.fld_DisplayLabel, ''), CONCAT('`', p.fld_name,'`'), ',  '),
				p.fld_name
			) AS fld_DisplayLabel,
			p.idn,p.idnng,fld_name,p.old,p.new
		FROM `logpo` p
		WHERE 
			idnng = _IDNNg
		;
		
	END IF;
END$$

DROP PROCEDURE IF EXISTS `_log_select_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_log_select_tools`(
	IN _MODE VARCHAR(38),
	IN _Key VARCHAR(200),	--	klucz rekordu lub IDN `log` itp
	IN _IDN_IDNNg INT,
	IN _GuidLink VARCHAR(150),	
	IN _Table_Link VARCHAR(50),
	IN _LogPo_Present VARCHAR(200),	--	różne trybu 1 lub N i dodatkowo 1.MEMO lub N.MEMO
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200)

)
/*
	CALL _logpo_tools('select', 274728, '', '');
*/
S_logpo_tools: BEGIN
	DECLARE _SQLText TEXT;
	IF _MODE LIKE 'SELECT.`log`.%' THEN
		IF _MODE LIKE 'SELECT.`log`.1.IDN' THEN
			SELECT 
				REPLACE(REPLACE(_Fmt_DateTime(l.czas, 'D MMM YYYY HH:NN:SS @Y@D'), '   ', ' '), '  ', ' ') AS Kiedy,
				CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr,
				l.*,
				s.*
			FROM `log` l
			LEFT JOIN `osoby` o ON o.GUID = l.OsobaGUID 
			LEFT JOIN `_sys_db_logons` s ON s.GUID = IDSEssion
			WHERE 
				l.IDN = _IDN_IDNNg
			;
		END IF;
		
		IF _MODE LIKE 'SELECT.`log`.N.KEY' THEN
			SELECT 
				REPLACE(REPLACE(_Fmt_DateTime(l.czas, 'D MMM YYYY HH:NN:SS @Y@D'), '   ', ' '), '  ', ' ') AS Kiedy,
				CONCAT(o.Nazwisko, ' ', o.Imiona) AS OsobaStr,
				l.*,
				s.*
			FROM `log` l
			LEFT JOIN `osoby` o ON o.GUID = l.OsobaGUID 
			LEFT JOIN `_sys_db_logons` s ON s.GUID = IDSEssion
			WHERE 
				l.GuidLink = _GuidLink 
				AND l.table_link = _Table_Link
			ORDER BY l.czas
			;
		END IF;
	END IF;
	
	IF _MODE LIKE 'SELECT.`logpo`.%' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_logpo_sel`;
		-- CREATE TEMPORARY TABLE `t_logpo_sel` LIKE `logpo`;
		CREATE TEMPORARY TABLE `t_logpo_sel` (
		  `idn` INT(11) NOT NULL AUTO_INCREMENT,
		  `idnng` INT(11) NOT NULL DEFAULT '0',
		  `fld_name` VARCHAR(50) NOT NULL DEFAULT '',
		  `fld_DisplayLabel` VARCHAR(255) DEFAULT NULL,
		  `old` VARCHAR(255) NOT NULL DEFAULT '',
		  `new` VARCHAR(255) NOT NULL DEFAULT '',
		  `Changes_Memo` TEXT,
		  PRIMARY KEY (`idn`),
		  KEY `idnng` (`idnng`)
		)
		;
		
	--	z logpo dla 
		SET _SQLText = 
		"
		INSERT INTO `t_logpo_sel` 
		SELECT 
			p.*,
			CONCAT_WS('',
				CONCAT(
					'**** Zmiana pola: ',
					IF(IFNULL(NULLIF(p.fld_DisplayLabel, ''), p.fld_name) != p.fld_name,
						CONCAT_WS(' ', NULLIF(p.fld_DisplayLabel, ''), NULLIF(CONCAT('(`', p.fld_name,'`)'), '')),
						p.fld_name
					)
				),
				' **************************************************',
				'#n#',
				'Było: ----------------------------------------------------------------',
				'#n#',
				p.old,
				'#n#',
				-- p.idn,p.idnng,
				'Jest: ----------------------------------------------------------------',
				'#n#',
				p.new
			) AS Changes_Memo
		FROM #FROM#
		WHERE #WHERE#
		;
		"
		;
	
		SET @_SQLText = _SQLText;
		SET @_IDN_IDNNg = _IDN_IDNNg;
		IF _MODE = 'SELECT.`logpo`.1.IDN' THEN
			SET _SQLText = REPLACE(REPLACE(_SQLText, '#FROM#', '`logpo` p'), '#WHERE#', 'p.idn = #_IDN_IDNNg#');
		END IF;
		IF _MODE = 'SELECT.`logpo`.N.IDNNg' THEN
			IF NOT EXISTS (SELECT idn FROM `logpo` WHERE idnng = _IDN_IDNNg) THEN
				CALL log_XML_convert('XML2logpo.idn', _IDN_IDNNg, '', '', '', '', '', ''); 
			END IF;
			SET _SQLText = REPLACE(REPLACE(_SQLText, '#FROM#', '`logpo` p'), '#WHERE#', 'p.idnng = #_IDN_IDNNg#');
			
		END IF;
		IF _MODE = 'SELECT.`logpo`.N.KEY' THEN
			SET _SQLText = REPLACE(REPLACE(_SQLText, '#FROM#', '`log` l, `logpo` p'), '#WHERE#', 'l.GuidLink = #_GuidLink# AND l.table_link = #_Table_Link# AND p.idnng = l.Idn');
			CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
		
		SET _SQLText = REPLACE(_SQLText, '#_IDN_IDNNg#', _IDN_IDNNg);
		SET _SQLText = REPLACE(_SQLText, '#_GuidLink#', QUOTE(_GuidLink));
		SET _SQLText = REPLACE(_SQLText, '#_Table_Link#', QUOTE(_Table_Link));
		SET _SQLText = REPLACE(_SQLText, '#n#', '\\n');
		SET @_SQLText.P = _SQLText;
	--	Wstawianie	
		CALL _ExecuteCmd(_SQLText, @Error);
		
		IF _LogPo_Present LIKE '%MEMO' THEN
		--	różne tryby 1 lub N i dodatkowo 1.MEMO lub N.MEMO
			SET _SQLText = 
			"
			SELECT
				p.idnng,
				GROUP_CONCAT(
					p.Changes_Memo
				SEPARATOR '#n#'
				) AS Changes_Memo
			FROM `t_logpo_sel` p
			WHERE 
				TRUE
			#GROUP BY#
			;
			"
			;
			SET @_SQLText = _SQLText;
			SET _SQLText = REPLACE(_SQLText, '#GROUP BY#', IF(_LogPo_Present LIKE 'N.%', 'GROUP BY p.IDN', 'GROUP BY p.IDNNg'));
			SET _SQLText = REPLACE(_SQLText, '#n#', '\\n');
			SET @_SQLText.S = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
	END IF;
	
	IF _MODE IN ('', 'select') THEN
		IF NOT EXISTS (SELECT idn FROM `logpo` WHERE idnng = _IDN_IDNNg) THEN
			-- CALL log_XML_convert('XML2logpo.idn', _IDNNg, '', '', '', '', '', 'all'); -- 'ALL' pełne dane + zmiany
			CALL log_XML_convert('XML2logpo.idn', _IDN_IDNNg, '', '', '', '', '', ''); 
		END IF;
		SELECT
			IF(IFNULL(p.fld_DisplayLabel, '') != p.fld_name,
				_ConcatStr(IFNULL(p.fld_DisplayLabel, ''), CONCAT('`', p.fld_name,'`'), ',  '),
				p.fld_name
			) AS fld_DisplayLabel,
			p.idn,p.idnng,fld_name,p.old,p.new
		FROM `logpo` p
		WHERE 
			idnng = _IDN_IDNNg
		;
		
	END IF;
	
END$$

DROP PROCEDURE IF EXISTS `_log_stats`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_log_stats`(
	IN _MODE VARCHAR(38),
	IN _PARAM_A VARCHAR(200),
	IN _PARAM_B VARCHAR(200),
	IN _PARAM_c VARCHAR(200)

)
BEGIN
	DECLARE _DAYS INT;
	DECLARE _INFO_LEN INT;
	DECLARE _SQLText TEXT;
	IF _MODE IN ('Users.Aktywnosc', 'Users.Aktywnosc.2') THEN
	/************************************************************************************************************************************************
		-- po staremu ...
		CALL _log_stats('USAGE',60,'','');
		-- po nowemu 
		-- Lista aktywności dopasowane do Centrum IntNet
		-- w _PARAM_A - parametry (P1=xx&P2=xx&...)
		-- Przykłady:
		-- wszystkie z ost 6 m-cy (domyslnie)
		CALL _log_stats('Users.Aktywnosc', '', '', '');
		-- wszystkie z pocz. od 1 II do 8 III 2021
		CALL _log_stats('Users.Aktywnosc', 'from=2021-02-01&to=2021-03-08', '', '');
		-- wszystkie z ost. 2 m-cy
		CALL _log_stats('Users.Aktywnosc', 'from=2M&', '', '');
		-- wszystkie z aktuanego m-ca
		CALL _log_stats('Users.Aktywnosc', 'from=CM&', '', '');
		-- wszystkie z aktuanego roku
		CALL _log_stats('Users.Aktywnosc', 'from=CY&', '', '');
		-- wszystkie z ost. 40 dni
		CALL _log_stats('Users.Aktywnosc', 'from=40D&', '', '');
		-- wszystkie z ost. 4 tyg.
		CALL _log_stats('Users.Aktywnosc', 'from=4W&', '', '');
		-- wszystkie z pocz. od 10 IV 2021 dla usera agnieszkah
		CALL _log_stats('Users.Aktywnosc', 'login=agnieszkah&from=2021-03-10&', '', '');
		-- wszystkie z ost 6 m-cy dla usera "agnieszkah"
		CALL _log_stats('Users.Aktywnosc', 'login=agnieszkah&', '', '');
		-- wszystkie z ost 6 m-cy dla usera o nazwisku like  "%Kocerba%"
		CALL _log_stats('Users.Aktywnosc', 'nazwisko=Kocerba&', '', '');
		-- wszystkie z ost 6 m-cy dla usera GUID = "a2846016bc535968acb061fff86429d2"
		CALL _log_stats('Users.Aktywnosc', 'userguid=a2846016bc535968acb061fff86429d2&', '', '');
		-- wszystkie z ost 6 m-cy dla aplikacji o nazwie like  "%Porta%"
		CALL _log_stats('Users.Aktywnosc', 'appname=Porta&', '', '');

	************************************************************************************************************************************************/
		SET
			@.log.stat.Login = NULLIF(_Params2('_FetchParams', @._ModeParam, _PARAM_A, 'login', ''), ''),
			@.log.stat.UserGUID = NULLIF(_Params2('_FetchParams', @._ModeParam, _PARAM_A, 'userguid', ''), ''),
			@.log.stat.Nazwisko = CONCAT('%', NULLIF(_Params2('_FetchParams', @._ModeParam, _PARAM_A, 'nazwisko', ''), ''), '%'),
			@.log.stat.log_APPName = CONCAT('%', NULLIF(_Params2('_FetchParams', @._ModeParam, _PARAM_A, 'appname', ''), ''), '%'),
			@.log.stat.FROM = NULLIF(_Params2('_FetchParams', @._ModeParam := '', _PARAM_A, 'from', ''), ''),
			@.log.stat.TO = NULLIF(_Params2('_FetchParams', @._ModeParam, _PARAM_A, 'to', ''), '')
		;
		-- IF @.log.stat.UserGUID IS NOT NULL OR @.log.stat.Login IS NOT NULL
		-- IF @.log.stat.Login = IFNULL(@.log.stat.Login, 
		IF @.log.stat.FROM IS NOT NULL THEN
			SET
				@.log.stat.FROM = DATE(
				CASE
					-- WHEN @.log.stat.FROM LIKE '%CM'  THEN _FirstDayM(CURRENT_DATE())
					-- WHEN @.log.stat.FROM LIKE '%CY'  THEN _FirstDayY(CURRENT_DATE())
					WHEN @.log.stat.FROM LIKE '%CM'  THEN DATE(_FirstDayM(CURRENT_DATE()))
					WHEN @.log.stat.FROM LIKE '%CY'  THEN DATE(_FirstDayY(CURRENT_DATE()))
					WHEN @.log.stat.FROM LIKE '%D'  THEN CURRENT_DATE() - INTERVAL REPLACE(@.log.stat.FROM, 'D', '') DAY
					WHEN @.log.stat.FROM LIKE '%W'  THEN CURRENT_DATE() - INTERVAL REPLACE(@.log.stat.FROM, 'W', '') WEEK
					WHEN @.log.stat.FROM LIKE '%M'  THEN CURRENT_DATE() - INTERVAL REPLACE(@.log.stat.FROM, 'M', '') MONTH
					ELSE
						@.log.stat.FROM
				END
				)
			;
		END IF;
		SET
			@.log.stat.FROM = DATE(IFNULL(@.log.stat.FROM, CURRENT_DATE() - INTERVAL 6 MONTH)),
			@.log.stat.TO = DATE(IFNULL(@.log.stat.TO, CURRENT_DATE()))
		;
		IF _MODE IN ('Users.Aktywnosc.2') THEN
			SET 
			_SQLText = 
			"
			SELECT
				-- COUNT(*) AS log_CC,
				CONCAT_WS(' ', NULLIF(o.Imie1, ''), NULLIF(o.Nazwisko, ''), _Brackets('(', ua.Login, ')'), IF(ua.Admin, 'ADMIN', NULL)
				) AS User_Name,
				CONCAT_WS(' ',
					_Brackets('Aktywn.: ', SUM(ak.Log_TimeWORK), ' h'),
					_ConcatPre('sesji: ', SUM(ak.log_CC)),
					_Format_DT_Range_Mask(MIN(Log_Od), MAX(Log_Do), '%D %mmm %YYYY[DZ];%D %mmm %YYYY[DZ];', '([od][#from#][do][#to#])')
					
				) AS Log_Inf,
				CONCAT_WS(', ',
					_ConcatPre('Prób: ', SUM(ak.log_CC)),
					_ConcatPre('OK: ', SUM(ak.Log_OK_CC)),
					_ConcatPre('Err: ', NULLIF(SUM(ak.Log_ERR_CC), 0))
					
				) AS Log_CC_Inf,
				GROUP_CONCAT(
					CONCAT_WS(' ',
						ak.Log_APP,
						-- ak.log_CC,
						_ConcatPre('- prób: ', (ak.log_CC)),
						IF(ak.log_CC = ak.Log_OK_CC,
							NULL,
							_Brackets('(', 
								CONCAT_WS('/', ak.Log_OK_CC, NULLIF(ak.Log_ERR_CC, 0)),
							')')
						),
						_Brackets('(', ak.Log_TimeWORK, ' h)'),
						NULL
					) SEPARATOR ', '
				) AS Log_APPs_Inf,
				CONCAT_WS(', ', 
					IF(ua.Admin, 'ADMIN', NULL),
					Get_Status_For_From_To_Str('GET.Info.Konto.Full', CURRENT_DATE(), ua.date_from, ua.date_to, '', ua.Status, '', '')
				) AS Konto_Inf,
				ak.log_USER_GUID,
				ua.Login,
				GROUP_CONCAT(ak.Log_APP) AS Log_APPs,
				MIN(Log_Od) AS Log_Od,
				MAX(Log_Do) AS Log_Do,
				SUM(ak.log_CC) AS log_CC,
				SUM(ak.Log_OK_CC) AS Log_OK_CC,
				SUM(ak.Log_ERR_CC) AS Log_ERR_CC,
				ak.*
			FROM
			(
				SELECT
					sdl.log_USER_GUID,
					IFNULL(sc.Caption, IFNULL(sdl.log_APPName, '???')) AS Log_APP,
					DATE(MIN(sdl.CONNECT_AT)) AS Log_Od,
					DATE(MAX(sdl.CONNECT_AT)) AS Log_Do,
					COUNT(*) AS log_CC,
					SUM(IF(sdl.INFO LIKE '%ERR%', 0, 1)) AS Log_OK_CC,
					SUM(IF(sdl.INFO LIKE '%ERR%', 1, 0)) AS Log_ERR_CC,
					-- IFNULL(sdl.log_APP_ID, sdl.log_APPName) AS Log_APP,
					-- COUNT(DISTINCT IFNULL(sdl.log_APP_ID, sdl.log_APPName)) AS log_APP_ID_CC,
					GROUP_CONCAT(sdl.Info SEPARATOR '\n=================\n'),
					SUM(TIMESTAMPDIFF(HOUR, sdl.CONNECT_AT, GREATEST(GREATEST(sdl.CLOSE_AT, sdl.LAST_USED_AT), sdl.PING_AT))) AS Log_TimeWORK
					-- sdl.*
				FROM `_sys_db_logons` sdl
				LEFT JOIN `_user_accounts` ua ON ua.osobaGUID = sdl.log_USER_GUID
				LEFT JOIN `osoby` o ON o.GUID = sdl.log_USER_GUID
				LEFT JOIN `sys_core` sc ON sc.GUID = sdl.`log_APP_ID`
				WHERE
					TRUE
					AND sdl.log_USER_GUID IS NOT NULL
					AND DATE(sdl.CONNECT_AT) BETWEEN @.log.stat.FROM AND @.log.stat.TO
								-- AND sdl.log_USER_GUID = '4dcf1752-0e2f-11eb-9832-000c2981645e*'
					-- AND IFNULL(sdl.log_USER_GUID = @.log.stat.UserGUID, TRUE)
					AND #WHERE.log_USER_GUID#
					-- AND IFNULL(ua.login = @.log.stat.Login, TRUE)
					AND #WHERE.Login#
					-- AND IFNULL(o.Nazwisko LIKE @.log.stat.Nazwisko, TRUE)
					AND #WHERE.Nazwisko#
					-- AND IFNULL(sc.Caption LIKE @.log.stat.log_APPName, IFNULL(sdl.log_APPName LIKE @.log.stat.log_APPName, TRUE))
					AND #WHERE.log_APPName#

				GROUP BY
					sdl.log_USER_GUID,
					Log_APP -- IFNULL(sdl.log_APP_ID, sdl.log_APPName)
			) AS ak
			LEFT JOIN `osoby` o ON o.GUID = log_USER_GUID
			LEFT JOIN `_user_accounts` ua ON ua.osobaGUID = log_USER_GUID
			GROUP BY log_USER_GUID
			;
			"
			;
			SET _SQLText = REPLACE(_SQLText, '#WHERE.log_USER_GUID#', IF(@.log.stat.UserGUID IS NULL, 'TRUE', 'sdl.log_USER_GUID = @.log.stat.UserGUID'));
			SET _SQLText = REPLACE(_SQLText, '#WHERE.Login#', IF(@.log.stat.Login IS NULL, 'TRUE', 'sdl.Login = @.log.stat.Login'));
			SET _SQLText = REPLACE(_SQLText, '#WHERE.Nazwisko#', IF(@.log.stat.Nazwisko IS NULL, 'TRUE', 'o.Nazwisko LIKE @.log.stat.Nazwisko'));
			SET _SQLText = REPLACE(_SQLText, '#WHERE.log_APPName#', IF(@.log.stat.log_APPName IS NULL, 'TRUE', 'IFNULL(sc.Caption, sdl.log_APPName) LIKE @.log.stat.log_APPName'));
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
		
			SELECT
				-- COUNT(*) AS log_CC,
				CONCAT_WS(' ', NULLIF(o.Imie1, ''), NULLIF(o.Nazwisko, ''), _Brackets('(', ua.Login, ')'), IF(ua.Admin, 'ADMIN', NULL)
				) AS User_Name,
				CONCAT_WS(' ',
					_Brackets('Aktywn.: ', SUM(ak.Log_TimeWORK), ' h'),
					_ConcatPre('sesji: ', SUM(ak.log_CC)),
					_Format_DT_Range_Mask(MIN(Log_Od), MAX(Log_Do), '%D %mmm %YYYY[DZ];%D %mmm %YYYY[DZ];', '([od][#from#][do][#to#])')
					
				) AS Log_Inf,
				CONCAT_WS(', ',
					_ConcatPre('Prób: ', SUM(ak.log_CC)),
					_ConcatPre('OK: ', SUM(ak.Log_OK_CC)),
					_ConcatPre('Err: ', NULLIF(SUM(ak.Log_ERR_CC), 0))
					
				) AS Log_CC_Inf,
				GROUP_CONCAT(
					CONCAT_WS(' ',
						ak.Log_APP,
						-- ak.log_CC,
						_ConcatPre('- prób: ', (ak.log_CC)),
						IF(ak.log_CC = ak.Log_OK_CC,
							NULL,
							_Brackets('(', 
								CONCAT_WS('/', ak.Log_OK_CC, NULLIF(ak.Log_ERR_CC, 0)),
							')')
						),
						_Brackets('(', ak.Log_TimeWORK, ' h)'),
						NULL
					) SEPARATOR ', '
				) AS Log_APPs_Inf,
				CONCAT_WS(', ', 
					IF(ua.Admin, 'ADMIN', NULL),
					Get_Status_For_From_To_Str('GET.Info.Konto.Full', CURRENT_DATE(), ua.date_from, ua.date_to, '', ua.Status, '', '')
				) AS Konto_Inf,
				ak.log_USER_GUID,
				ua.Login,
				GROUP_CONCAT(ak.Log_APP) AS Log_APPs,
				MIN(Log_Od) AS Log_Od,
				MAX(Log_Do) AS Log_Do,
				SUM(ak.log_CC) AS log_CC,
				SUM(ak.Log_OK_CC) AS Log_OK_CC,
				SUM(ak.Log_ERR_CC) AS Log_ERR_CC,
				ak.*
			FROM
			(
				SELECT
					sdl.log_USER_GUID,
					IFNULL(sc.Caption, IFNULL(sdl.log_APPName, '???')) AS Log_APP,
					DATE(MIN(sdl.CONNECT_AT)) AS Log_Od,
					DATE(MAX(sdl.CONNECT_AT)) AS Log_Do,
					COUNT(*) AS log_CC,
					SUM(IF(sdl.INFO LIKE '%ERR%', 0, 1)) AS Log_OK_CC,
					SUM(IF(sdl.INFO LIKE '%ERR%', 1, 0)) AS Log_ERR_CC,
					-- IFNULL(sdl.log_APP_ID, sdl.log_APPName) AS Log_APP,
					-- COUNT(DISTINCT IFNULL(sdl.log_APP_ID, sdl.log_APPName)) AS log_APP_ID_CC,
					GROUP_CONCAT(sdl.Info SEPARATOR '\n=================\n'),
					SUM(TIMESTAMPDIFF(HOUR, sdl.CONNECT_AT, GREATEST(GREATEST(sdl.CLOSE_AT, sdl.LAST_USED_AT), sdl.PING_AT))) AS Log_TimeWORK
					-- sdl.*
				FROM `_sys_db_logons` sdl
				LEFT JOIN `_user_accounts` ua ON ua.osobaGUID = sdl.log_USER_GUID
				LEFT JOIN `osoby` o ON o.GUID = sdl.log_USER_GUID
				LEFT JOIN `sys_core` sc ON sc.GUID = sdl.`log_APP_ID`
				WHERE
					TRUE
					AND sdl.log_USER_GUID IS NOT NULL
					AND DATE(sdl.CONNECT_AT) BETWEEN @.log.stat.FROM AND @.log.stat.TO
					-- AND sdl.log_USER_GUID = '4dcf1752-0e2f-11eb-9832-000c2981645e*'
					AND IFNULL(sdl.log_USER_GUID = @.log.stat.UserGUID, TRUE)
					AND IFNULL(o.Nazwisko LIKE @.log.stat.Nazwisko, TRUE)
					AND IFNULL(ua.login = @.log.stat.Login, TRUE)
					AND IFNULL(sc.Caption LIKE @.log.stat.log_APPName, IFNULL(sdl.log_APPName LIKE @.log.stat.log_APPName, TRUE))

				GROUP BY
					sdl.log_USER_GUID,
					Log_APP -- IFNULL(sdl.log_APP_ID, sdl.log_APPName)
			) AS ak
			LEFT JOIN `osoby` o ON o.GUID = log_USER_GUID
			LEFT JOIN `_user_accounts` ua ON ua.osobaGUID = log_USER_GUID
			GROUP BY log_USER_GUID
			;
		END IF;
		
	END IF;
	
	IF _MODE IN ('USAGE') THEN
		IF _PARAM_A='' THEN
			SET _DAYS=31;
		ELSE
			SET _DAYS=_VarInt(_PARAM_A);
		END IF;
		IF _PARAM_B='' THEN
			SET _INFO_LEN=100;
		ELSE
			SET _INFO_LEN=_VarInt(_PARAM_B);
		END IF;
		SELECT 
			useridn,count(DISTINCT DATE(czas)) as ile_dni,
			MID(REPLACE(IF(compressed,UNCOMPRESS(info),info),char(10),';'),1,_INFO_LEN) as info 
		FROM log 
		WHERE czynnosc=-1 AND czas>date_sub(current_date,interval _DAYS day) AND 
			NOT (	IF(compressed,uncompress(info),info) LIKE "%niezna%" OR 
				IF(compressed,uncompress(info),info) LIKE "%iepopr%" OR 
				IF(compressed,uncompress(info),info) LIKE "%programist%"
			) AND useridn<>'jmam'
		GROUP BY useridn 
		ORDER BY ile_dni DESC
		;	
	END IF;	
	IF _MODE IN ('rejestracje') THEN
			DROP TEMPORARY TABLE IF EXISTS log_rejestracje ;
			DROP TEMPORARY TABLE IF EXISTS oststnie_zdarzenia;

			CREATE TEMPORARY TABLE log_rejestracje (
			sesja INT,
			login VARCHAR(50),
			imie_nazwisko VARCHAR (100),
			czas_rejestracji DATETIME DEFAULT NULL,
			czas_wyrejestrowania VARCHAR (100) DEFAULT NULL,
			ostatnie_zdarzenie DATETIME DEFAULT NULL,
			lokalizacja VARCHAR (150));

			INSERT INTO log_rejestracje (sesja,login,imie_nazwisko,czas_rejestracji,lokalizacja)
				SELECT l.sessionid AS sesja,u.login,CONCAT (o.imie1,' ',o.nazwisko) AS imie_nazwisko, 
				l.czas AS czas_rejestracji,
				l.ip AS lokalizacja
				FROM `log` l
				LEFT JOIN _user_accounts u ON l.useridn=u.login LEFT JOIN osoby o ON o.guid=u.osobaguid  
				WHERE l.czynnosc IN ('-1') AND (l.info LIKE 'Rejest%') AND DATE(l.czas) = _PARAM_A;



			CREATE TEMPORARY TABLE oststnie_zdarzenia
				SELECT MAX(idn)AS idn ,sessionid FROM `log` l INNER JOIN log_rejestracje r ON l.sessionid=r.sesja WHERE r.ostatnie_zdarzenie IS NULL GROUP BY sessionid;
				
			UPDATE log_rejestracje r, `log` l  SET r.czas_wyrejestrowania = l.czas,r.ostatnie_zdarzenie = l.czas WHERE r.sesja=l.sessionid AND  l.czynnosc IN ('-2') AND (l.info LIKE 'Wyrej%') AND r.czas_rejestracji<l.czas AND r.login=l.useridn;
			UPDATE log_rejestracje r, `log` l  SET r.czas_wyrejestrowania = 'brak wyrejestrowania' WHERE r.czas_wyrejestrowania IS NULL;
			UPDATE log_rejestracje r,oststnie_zdarzenia o, `log` l  SET r.ostatnie_zdarzenie= l.czas WHERE r.ostatnie_zdarzenie IS NULL AND r.sesja=o.sessionid AND l.idn=o.idn;

			SELECT * FROM log_rejestracje WHERE sesja IS NOT NULL ORDER BY login,czas_rejestracji;
				
			
	END IF;
END$$

DROP PROCEDURE IF EXISTS `log_Ins`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `log_Ins`(
	IN _MODE VARCHAR(150),
	INOUT _IDN_Log INTEGER,
	IN _Miejsce VARCHAR(150),	
	IN _Czynnosc VARCHAR(150),	
	IN _GuidLink VARCHAR(150),	
	IN _TableName VARCHAR(50),	
	-- IN _IP VARCHAR(150),	
	IN _Info TEXT,
	-- IN _IdnUser VARCHAR(150),	
	IN _lp_FieldName VARCHAR(250),
	IN _lp_Displaylabel VARCHAR(250),
	IN _OldValue VARCHAR(250),
	IN _NewValue VARCHAR(250),
	IN _PARAM_A VARCHAR(200),	--	GUIDLink2 w 'LOG.INSERT'
	IN _PARAM_B VARCHAR(200)	--	RecipGUID
)
/*
	log_Ins
	_MODE:
		'Ins.'
	CALL log_Ins('INS', @_Idn, @.account.Log.Miejsce, @.account.Log.Czynnosc, 'guid', 'tabela', 'info', 'FieldName', 'Displaylabel', 'OldValue', '_NewValue', '', '');

*/

S_log_Ins: BEGIN
	/*
	IF _MODE LIKE 'INS%' THEN
		IF NOT (_MODE LIKE '%.logpo%') THEN
		--	Dla zwykłych insertów - NIE dla seryjnie dodawanych logpo!!! - ustaw _IDN_Log na null
			SET _IDN_Log = NULL; -- b. ważne - bo tylko dla NULL wstawiamy
		END IF;
SET @._Info = _Info;		
		IF _MODE LIKE '%.logpo.Diff%' AND (_OldValue <=> _NewValue) THEN
		--	Dla wpisu INS.logpo.Diff - wychodz gdy _NewValue nie rozni sie od _OldValue
			LEAVE S_log_Ins;
		END IF;
		IF NULLIF(_IDN_Log, 0) IS NULL THEN
		--	Wstawiamy rekord
			CREATE TEMPORARY TABLE IF NOT EXISTS `t_log_guids` (guid VARCHAR(38), info TEXT);
			SELECT COUNT(*) FROM  `t_log_guids` INTO @t_log_guids.ile;
			IF @t_log_guids.ile = 0 THEN
			--	Pusta czyli żaden proces zewn. nie uzupełnił tej tabeli - zatem wstawiamy tu swoje dane
				INSERT INTO `t_log_guids` VALUES (_GUIDLink, _Info);
			END IF;

			SET @.IDSession = @SYSTEM.Client.Session.GUID;
		--	w @.IDSession jest sesja
			INSERT INTO `log` 
			(useridn, OsobaGUID, miejsce, czynnosc, guidlink, table_link, ip, info, Info_View, IDSession)
				SELECT
				IFNULL(sdl.log_USER, IFNULL(@SYSTEM.Client.Session.log_USER, IFNULL(@session.INFO.User_Login, @session.Registration.UserLogin))) AS useridn,
				IFNULL(sdl.log_USER_GUID , IFNULL(@SYSTEM.Client.Session.log_USER_GUID, IFNULL(@session.INFO.User_GUID, @session.Registration.UserGUID))) AS OsobaGUID,
				IFNULL(NULLIF(_Miejsce, ''), 0) AS miejsce,
				IFNULL(NULLIF(_Czynnosc, ''), 0) AS czynnosc, 
				IFNULL(t.guid, '') AS guidlink,
				IFNULL(NULLIF(_TableName, ''), IFNULL(lm.Tabela, '')) AS table_link,
				IF(sdl.GUID IS NOT NULL,
					CONCAT_WS(' - ', sdl.log_HOST_Name, CONCAT_WS(', ', CONCAT('IP: ', sdl.log_HOST), CONCAT('MCA: ', sdl.log_MACADDRESS))),
					IFNULL(@session.INFO.Host_IP, IFNULL(@session.Registration.IP, @session.CurrMyIPOnly))
				) AS IP,
				-- CONCAT_WS(' ', NULLIF(, ''), sdl.log_Host, sdl.log_Host_Name, sdl.log_MACADDRESS,'') AS IP,
				-- IF(IFNULL(_IP, '') != '', _IP, Concat(@session.CurrMyCompNameStr, ' ', @session.CurrMyIPOnly, ' ', @session.CurrMACAddresses)) as ip,
				-- na razie nie REPLACE(CONVERT(IFNULL(t.Info, '') USING utf8), '#ContextName#', @.LOG.ContextName) AS info,
				CONVERT(IFNULL(t.Info, '') USING utf8) AS info,
				-- na razie nie REPLACE(IFNULL(t.Info, ''), '#ContextName#', @.LOG.ContextName) AS Info_View,
				IFNULL(t.Info, '') AS Info_View,
				sdl.GUID AS IDSession
				-- , sl.*
			FROM `t_log_guids` t
			LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = @.IDSession
			LEFT JOIN `log_miejsca` lm ON lm.Idn = _Miejsce
			LEFT JOIN `log_czynnosci` lc ON lc.Idn = _Czynnosc
			WHERE
				TRUE -- sl.GUID = @.IDSession
			;
			SET _IDN_Log = LAST_INSERT_ID();
			DROP TEMPORARY TABLE IF EXISTS `t_log_guids`;
		END IF;
		
		IF _MODE LIKE '%.logpo%' THEN
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`) 
			VALUES
				(_IDN_Log, _lp_FieldName, QUOTE(_OldValue), QUOTE(_NewValue))
			;
			
		END IF;
	END IF;
	*/

	IF _MODE LIKE 'Spec.Prog.Log%' AND NULLIF(_IDN_Log, 0) IS NULL THEN
--	Dla wszystkich programów - logowanie i wylogowanie do/z systemu 	
		SET
		--	UWAGA!!!!!! zmieniamy _MODE aby poszedł dalej i wstawił do loga
			_Miejsce = (@.AUTH.LOG._Miejsce := 10001), 	-- 11001 Logowanie do systemu
			_Czynnosc = (@.AUTH.LOG._Czynnosc := 
			--	Rejestracja w systemie 
				/*	było
				IF(_MODE LIKE 'Spec.Prog.LogIn', 
					-1, 	-- -1 logowanie i wylogowanie z systemu,
					-2		-- -2 Wyrejestrowanie z systemiu
				)
				*/
				IF(NOT (_MODE LIKE 'Spec.Prog.LogIn'), 
					-2,		-- -2 Wyrejestrowanie z systemiu
					-1 		-- -1 logowanie i wylogowanie z systemu,
				)
			),	
			_GuidLink = (@.AUTH.LOG._GuidLink := @SYSTEM.Client.Session.GUID),
			_TableName = '_sys_db_logons',
			@._Info = (@.AUTH.LOG.LogOpis := 
				IFNULL(
					NULLIF(_Info, ''), 
					IF(_MODE LIKE 'Spec.Prog.LogIn%',
						(
						SELECT 
							CONCAT_WS('',
								IF(_MODE LIKE 'Spec.Prog.LogIn.ERR',
									'Błąd autoryzacji ',
									'Rejestracja do systemu '
								),
								CONCAT(' prog.: ', NULLIF(sdl.log_APPNAME, '?')),
								CONCAT(' (', NULLIF(sdl.log_APP_ID, '?'), ')'),
								-- programem C:\INT\HT2003.exe (HT2003_S wersja z dnia: 02.08.2016 15:19:04 /NU [SLON]) [AZO]
								/*
								apro nie chce tu dod. inf. ma byc human readable
								CONCAT(
									'\n', 
									CONCAT_WS(', ',
										CONCAT('Host: ', sdl.log_HOST), 
										NULLIF(sdl.log_HOST_Name, ''),
										NULLIF(sdl.log_DEV_ID, ''),
										CONCAT('ConID: ', sdl.Con_ID, ' baza: ', sdl.Con_DB, '')
									)
								),
								*/
								NULL
							)
						FROM `_sys_db_logons` sdl
						WHERE
							sdl.GUID = @SYSTEM.Client.Session.GUID
						),
						'Wyrejestrowanie z systemu'
					)
				
				)
			)
		;
		SET
			_Info = _VarStr(@.AUTH.LOG.LogOpis := 
				IFNULL(
					NULLIF(_Info, ''), 
					(
					SELECT 
						CONCAT_WS('',
							REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(rs.T,
								'#Kind#', IF(sdl.Kind = 'EXE', _VarStr('prog.'), _VarStr('aplik.'))),
								'#APPNAME#', IFNULL(NULLIF(sdl.log_APPNAME, '?'), '???')),
								'#APP_ID#', IFNULL(NULLIF(sdl.log_APP_ID, '?'), '')),
								'()', ''),
								' .', '.'),
							NULL,
							NULL
						)
					FROM `_sys_db_logons` sdl
					LEFT JOIN `_res_strings` rs ON rs.ID = 
						IF(_MODE LIKE 'Spec.Prog.LogIn.ERR', 'LOG.session.LOG.ERR',
							IF(_MODE LIKE 'Spec.Prog.LogIn', 'LOG.session.LOG.OK',
								IF(_MODE LIKE 'Spec.Prog.LogOut', 'LOG.session.LOG.OFF', 'LOG.session.LOG.ERR')
							)
						)
					WHERE
						sdl.GUID = @SYSTEM.Client.Session.GUID
					)
				)
			)
		;
		SET
			_MODE = 'LOG.INSERT'	-- zmieniamy _MODE
		;
	END IF;
	
	IF _MODE LIKE 'LOG.session.%' AND NULLIF(_IDN_Log, 0) IS NULL THEN
--	Dla wszystkich programów - logowanie i wylogowanie do/z systemu 	
		SET
		--	UWAGA!!!!!! poniżej zmieniamy _MODE aby poszedł dalej i wstawił do loga
			_Miejsce = (@.AUTH.LOG._Miejsce := 10001), 	-- 11001 Logowanie do systemu
			_Czynnosc = (@.AUTH.LOG._Czynnosc := 
			--	Rejestracja w systemie 
				IF(NOT (_MODE LIKE 'LOG.session.LOG.OK%'), 
					-2,		-- -2 Wyrejestrowanie z systemiu
					-1 		-- -1 logowanie i wylogowanie z systemu,
				)
			),	
			_GuidLink = (@.AUTH.LOG._GuidLink := @SYSTEM.Client.Session.GUID),
			_TableName = '_sys_db_logons',
			_Info = _VarStr(@.AUTH.LOG.LogOpis := 
				IFNULL(
					NULLIF(_Info, ''), 
					(
					SELECT 
						CONCAT_WS('',
							REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(rs.T,
								'#Kind#', IF(sdl.Kind = 'EXE', _VarStr('prog.'), _VarStr('aplik.'))),
								'#APPNAME#', IFNULL(NULLIF(sdl.log_APPNAME, '?'), '???')),
								'#APP_ID#', IFNULL(NULLIF(sdl.log_APP_ID, '?'), '')),
								'()', ''),
								' .', '.'),
							NULL,
							NULL
						)
					FROM `_sys_db_logons` sdl
					LEFT JOIN `_res_strings` rs ON rs.ID = _MODE
					WHERE
						sdl.GUID = @SYSTEM.Client.Session.GUID
					)
				)
			)
		;
		SET
		--	UWAGA!!!!!!  zmieniamy _MODE aby poszedł dalej i wstawił do loga
			_MODE = 'LOG.INSERT'	-- zmieniamy _MODE
		;
	END IF;
	
	IF _MODE LIKE 'LOG.INSERT' AND NULLIF(_IDN_Log, 0) IS NULL THEN
	--	Wstawiamy rekord
		SET @.IDSession = @SYSTEM.Client.Session.GUID;
	--	w @.IDSession jest sesja		sessionid
		INSERT INTO `log` 
		(useridn, OsobaGUID, miejsce, czynnosc, GUIDLink, GUIDLink2, RecipGUID, table_link, ip, info, Info_View, IDSession, sessionid)
			SELECT
			IFNULL(sdl.log_USER, IFNULL(@SYSTEM.Client.Session.log_USER, IFNULL(@session.INFO.User_Login, @session.Registration.UserLogin))) AS useridn,
			IFNULL(sdl.log_USER_GUID , IFNULL(@SYSTEM.Client.Session.log_USER_GUID, IFNULL(@session.INFO.User_GUID, @session.Registration.UserGUID))) AS OsobaGUID,
			IFNULL(NULLIF(_Miejsce, ''), 0) AS miejsce,
			IFNULL(NULLIF(_Czynnosc, ''), 0) AS czynnosc, 
			t.GUIDLink,
			t.GUIDLink2,
			t.RecipGUID,
			IFNULL(NULLIF(_TableName, ''), IFNULL(lm.Tabela, '')) AS table_link,
			IF(sdl.GUID IS NOT NULL,
				CONCAT_WS(' - ', 
					sdl.log_HOST_Name, 
					CONCAT_WS(', ', 
						CONCAT('IP: ', sdl.log_HOST_Name), 
						NULLIF(sdl.log_DEV_ID, ''),
						CONCAT('Host: ', sdl.log_HOST), 
						-- apro nie chce CONCAT('MCA: ', sdl.log_MACADDRESS),
						NULL
					)
					/*
					CONCAT_WS(', ',
						CONCAT('Host: ', sdl.log_HOST), 
						NULLIF(sdl.log_HOST_Name, ''),
						NULLIF(sdl.log_DEV_ID, ''),
						CONCAT('ConID: ', sdl.Con_ID, ' baza: ', sdl.Con_DB, '')
					)
					*/
					
				),
				IFNULL(@session.INFO.Host_IP, IFNULL(@session.Registration.IP, @session.CurrMyIPOnly))
			) AS IP,
			-- CONCAT_WS(' ', NULLIF(, ''), sdl.log_Host, sdl.log_Host_Name, sdl.log_MACADDRESS,'') AS IP,
			-- IF(IFNULL(_IP, '') != '', _IP, Concat(@session.CurrMyCompNameStr, ' ', @session.CurrMyIPOnly, ' ', @session.CurrMACAddresses)) as ip,
			-- na razie nie REPLACE(CONVERT(IFNULL(t.Info, '') USING utf8), '#ContextName#', @.LOG.ContextName) AS info,
			-- CONVERT(IFNULL(t.Info, '') USING utf8) AS info,
			IFNULL(t.Info, '') AS info,
			-- na razie nie REPLACE(IFNULL(t.Info, ''), '#ContextName#', @.LOG.ContextName) AS Info_View,
			IFNULL(t.Info, '') AS Info_View,
			sdl.GUID AS IDSession
			, CONNECTION_ID() AS sessionid
			-- , sl.*
		-- FROM `t_log_guids` t
		FROM 
		(
			SELECT _GuidLink AS GUIDLink, _PARAM_A AS GUIDLink2, _PARAM_B AS RecipGUID, _Info AS Info
		) AS t -- `t_log_guids` t
		LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = @.IDSession
		LEFT JOIN `log_miejsca` lm ON lm.Idn = _Miejsce
		LEFT JOIN `log_czynnosci` lc ON lc.Idn = _Czynnosc
		WHERE
			TRUE -- sl.GUID = @.IDSession
		;
		SET _IDN_Log = LAST_INSERT_ID();
	END IF;
	
	IF _MODE LIKE 'Trigger.logpo.%' THEN
	/********************************************************************************
		Wołane z _sys_db_logons_ai, _sys_db_logons_au, _sys_db_logons_ad
	********************************************************************************/
		IF _MODE LIKE 'Trigger.logpo.Prepare.Clear%' THEN
			SET
				_IDN_Log = NULL,		-- czyscimy IDN log - wstawimy jak coś bedzie
				@.Trigger.logpo._Miejsce = _Miejsce,	
				@.Trigger.logpo._Czynnosc = _Czynnosc,	
				@.Trigger.logpo.GUIDLink = _GUIDLink,	
				@.Trigger.logpo.GUIDLink2 = _PARAM_A,
				@.Trigger.logpo.RecipGUID = _PARAM_B,
				@.Trigger.logpo._TableName = _TableName,	
				@.Trigger.logpo._Info = _Info
			;	
		END IF;
		
		IF _MODE LIKE 'Trigger.logpo.INSERT%' THEN
		--	Nie robimy niczego gdy _NewValue nie rozni sie od _OldValue
		--	Najpierw INSERT naglowka - UWAGA call nie wstawi niczego gdy _IDN_Log nie jest NULL
			CALL log_Ins('LOG.INSERT', _IDN_Log, @.Trigger.logpo._Miejsce, @.Trigger.logpo._Czynnosc, @.Trigger.logpo.GuidLink, @.Trigger.logpo._TableName, @.Trigger.logpo._Info, NULL, NULL, NULL, NULL, @.Trigger.logpo.GUIDLink2, @.Trigger.logpo.RecipGUID);
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`, `what`) 
			VALUES
				(_IDN_Log, _lp_FieldName, QUOTE(NULL), QUOTE(_NewValue), 'INS')
			;
		ELSEIF _MODE LIKE 'Trigger.logpo.UPDATE%' AND !(_OldValue <=> _NewValue) THEN
		--	Nie robimy niczego gdy _NewValue nie rozni sie od _OldValue
		--	Najpierw INSERT naglowka - UWAGA call nie wstawi niczego gdy _IDN_Log nie jest NULL
			CALL log_Ins('LOG.INSERT', _IDN_Log, @.Trigger.logpo._Miejsce, @.Trigger.logpo._Czynnosc, @.Trigger.logpo.GuidLink, @.Trigger.logpo._TableName, @.Trigger.logpo._Info, NULL, NULL, NULL, NULL, @.Trigger.logpo.GUIDLink2, @.Trigger.logpo.RecipGUID);
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`, `what`) 
			VALUES
				(_IDN_Log, _lp_FieldName, QUOTE(_OldValue), QUOTE(_NewValue), 'MOD')
			;
		ELSEIF _MODE LIKE 'Trigger.logpo.INF%' AND _NewValue IS NOT NULL THEN
		--	Tutaj jest tylko New bez Old
		--	Najpierw INSERT naglowka - UWAGA call nie wstawi niczego gdy _IDN_Log nie jest NULL
			CALL log_Ins('LOG.INSERT', _IDN_Log, @.Trigger.logpo._Miejsce, @.Trigger.logpo._Czynnosc, @.Trigger.logpo.GuidLink, @.Trigger.logpo._TableName, @.Trigger.logpo._Info, NULL, NULL, NULL, NULL, @.Trigger.logpo.GUIDLink2, @.Trigger.logpo.RecipGUID);
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`, `what`) 
			VALUES
				(_IDN_Log, _lp_FieldName, '', _NewValue, 'INS')
			;
		ELSEIF _MODE LIKE 'Trigger.logpo.DELETE%' THEN
		--	Nie robimy niczego gdy _NewValue nie rozni sie od _OldValue
		--	Najpierw INSERT naglowka - UWAGA call nie wstawi niczego gdy _IDN_Log nie jest NULL
			CALL log_Ins('LOG.INSERT', _IDN_Log, @.Trigger.logpo._Miejsce, @.Trigger.logpo._Czynnosc, @.Trigger.logpo.GuidLink, @.Trigger.logpo._TableName, @.Trigger.logpo._Info, NULL, NULL, NULL, NULL, @.Trigger.logpo.GUIDLink2, @.Trigger.logpo.RecipGUID);
			INSERT INTO `logpo`
				(idnng, fld_name, `old`, `new`, `what`) 
			VALUES
				(_IDN_Log, _lp_FieldName, QUOTE(_OldValue), QUOTE(NULL), 'DEL')
			;
		END IF;
		
	END IF;
	
	IF _MODE LIKE 'INS.from.t_schema_OLD_NEW' THEN
		SET
			_IDN_Log = NULL,		-- czyscimy IDN log - wstawimy jak coś bedzie
			@.Trigger.logpo._Miejsce = _Miejsce,	
			@.Trigger.logpo._Czynnosc = _Czynnosc,	
			@.Trigger.logpo._GuidLink = _GuidLink,	
			@.Trigger.logpo.GUIDLink2 = _PARAM_A,
			@.Trigger.logpo.RecipGUID = _PARAM_B,
			@.Trigger.logpo._TableName = _TableName,	
			@.Trigger.logpo._Info = _Info,
			@.Trigger.schema.OK = 
				EXISTS(
					SELECT 
						t.COLUMN_NAME 
					FROM `t_schema_OLD_NEW` t, `t_schema` s  
					-- było WHERE s.COLUMN_NAME = t.COLUMN_NAME AND s.Src = 1 AND NOT t.IsEqu
					WHERE
						s.COLUMN_NAME = t.COLUMN_NAME 
						AND s.T_OLD 
						AND NOT t.IsEqu
				)
		;	
		IF @.Trigger.schema.OK THEN
			CALL log_Ins('LOG.INSERT', _IDN_Log, @.Trigger.logpo._Miejsce, @.Trigger.logpo._Czynnosc, @.Trigger.logpo._GuidLink, @.Trigger.logpo._TableName, @.Trigger.logpo._Info, NULL, NULL, NULL, NULL, @.Trigger.logpo.GUIDLink2, @.Trigger.logpo.RecipGUID);
			INSERT INTO `logpo`
			(idnng, fld_name, `old`, `new`, `what`) 
			SELECT 
				_IDN_Log AS idnng,
				t.COLUMN_NAME AS fld_name,
				-- t.OLD,
				IF(t.OLD_EXISTS,
					QUOTE(t.OLD),
					'b/d'
				) AS OLD,
				-- t.NEW,
				IF(t.NEW_EXISTS,
					QUOTE(t.NEW),
					'b/d'
				) AS NEW,
					-- NULL), QUOTE(_NewValue), 'INS')
				IF(NOT t.OLD_EXISTS AND t.NEW_EXISTS,
					'INS',
					IF(NOT t.NEW_EXISTS AND t.OLD_EXISTS,
						'DEL',
						IF(t.NEW_EXISTS AND t.OLD_EXISTS,
							'EDIT',
							'???'
						)
					)
				) AS what
			FROM `t_schema_OLD_NEW` t, `t_schema` s 
			WHERE 
				s.COLUMN_NAME = t.COLUMN_NAME 
				AND s.T_OLD 
				AND NOT t.IsEqu
			;
		END IF;
	END IF;
	
	
END$$

DROP PROCEDURE IF EXISTS `_log_select`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_log_select`(
	IN _MODE VARCHAR(38),
	IN _Context VARCHAR(150),	
	IN _UserGUID VARCHAR(150),	
	IN _GuidLink VARCHAR(150),	
	IN _Table_Link VARCHAR(50),
	IN _PARAM_A VARCHAR(200),
	IN _PARAMS MEDIUMTEXT

)
/*
	CALL _log_select('select', '', '_UserGUID', '', '', '', '');
*/
S_log_select: BEGIN
	DECLARE _SQLText TEXT;
	IF _MODE IN ('', 'select') THEN
		SET @.log.Params = _PARAMS;
		SET
			@.log.sel.WHERE = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'WHERE', ''), ''), 
			@.log.sel.UserGUID = _UserGUID,
			@.log.sel.GUIDlink = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'GUIDlink', ''), ''), 
			@.log.sel.table_links = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'table_links', ''), ''), 
			@.log.sel.czynnosc = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'czynnosc', ''), ''), 
			@.log.sel.miejsce = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'miejsce', ''), ''), 
			@.log.sel.czas = NULLIF(_Params2('_FetchParams', @._ModeParam, @.log.Params, 'czas', ''), ''), 
			@.ua.X = NULLIF(_Params2('_FetchParams', @._ModeParam, @.Params, 'X', ''), '')
		;
	/*	10 III 2023 UWAGA zanim zablokujemy prod. niepotrz. wpisów do logu wstawiamy dod. where	*/
		SET @.log.sel.WHERE = CONCAT_WS(' AND ', @.log.sel.WHERE, 'NOT(miejsce IN (3, 4) AND czynnosc = 2)');
	
		
		SET @.log.sel.table_links = IFNULL(@.log.sel.table_links, IF(IFNULL(_Table_Link, '') <> '', QUOTE(_Table_Link), NULL));
		SET @.log.sel.GUIDlink = IFNULL(@.log.sel.GUIDlink, NULLIF(_GuidLink, ''));
		IF _Context = 'osoby' THEN
			-- SET @.log.sel.table_links = "'osoby', '_user_accounts', 'uprawnienia_dict', 'Prac'";
			SET @.log.sel.czynnosc = "2, 3, 4, 5, 402, 415";
			SET @.log.sel.miejsce = "100, 302, 304, 1005";
		END IF;
		IF _Context = 'Pracownik' THEN
			-- SET @.log.sel.table_links = "'osoby', '_user_accounts', 'uprawnienia_dict', 'Prac'";
			SET @.log.sel.czynnosc = "2, 3, 4, 5, 402, 415";
			SET @.log.sel.miejsce = "100, 302, 304, 1005, 5076";
		END IF;
		IF _Context = 'Wazenie' THEN
			-- SET @.log.sel.table_links = "'osoby', '_user_accounts', 'uprawnienia_dict', 'Prac'";
			SET @.log.sel.czynnosc = "570";
			SET @.log.sel.miejsce = "3201";
		END IF;
		IF _Context = 'INT.NET.Hist.Konta' THEN
		--	historia konta usera
			-- SET @.log.sel.table_links = "'osoby', '_user_accounts', 'uprawnienia_dict', 'Prac'";
			SET @.log.sel.czynnosc = "2, 3, 4, 5, 402, 415";
			SET @.log.sel.miejsce = "100, 302, 304";
		END IF;
		IF _Context = 'INT.NET.User.Act' THEN
		--	historia czynnosci usera
		--	zabezp. log to podsta. czynnosci jesli nie podano żadnych (minimu np 2, 3, 4)
			SET @.log.sel.czynnosc = IF(IFNULL(@.log.sel.czynnosc, '') = '',  "2, 3, 4, 5, 6", @.log.sel.czynnosc);
			SET @.log.sel.miejsce = "100, 302, 303, 304";  -- IntNet - konta użytkownika, IntNetCenter - uprawnienia, Grupy osób
		END IF;
		IF _Context = 'INT.NET.Grupy' THEN
		--	historia czynnosci usera
		--	zabezp. log to podsta. czynnosci jesli nie podano żadnych (minimu np 2, 3, 4)
			SET @.log.sel.czynnosc = IF(IFNULL(@.log.sel.czynnosc, '') = '',  "2, 3, 4, 5, 6", @.log.sel.czynnosc);
			SET @.log.sel.miejsce = "304"; 	-- IntNetCenter - uprawnienia
		END IF;
		IF _Context = 'INT.NET.Uprawnienie' THEN
		--	historia czynnosci usera
		--	zabezp. log to podsta. czynnosci jesli nie podano żadnych (minimu np 2, 3, 4)
			SET @.log.sel.czynnosc = IF(IFNULL(@.log.sel.czynnosc, '') = '',  "2, 3, 4, 5, 6", @.log.sel.czynnosc);
			SET @.log.sel.table_links = QUOTE('uprawnienia_dict');
			SET @.log.sel.miejsce = "303";
		END IF;
		IF _Context = 'INT.NET.Uprawnienie.Osoby' THEN
		--	historia czynnosci usera
		--	zabezp. log to podsta. czynnosci jesli nie podano żadnych (minimu np 2, 3, 4)
			SET @.log.sel.czynnosc = IF(IFNULL(@.log.sel.czynnosc, '') = '',  "2, 3, 4, 6", @.log.sel.czynnosc);
			SET @.log.sel.miejsce = "303, 304"; 	-- IntNetCenter - uprawnienia, Grupy osób
		END IF;
		
		DROP TEMPORARY TABLE IF EXISTS `t_log_select`;
		CREATE TEMPORARY TABLE `t_log_select` LIKE `log`;
		/*
		SET _SQLText =
		"
		CREATE TEMPORARY TABLE IF NOT EXISTS `t_log_select`
		SELECT 
			_Format_DT(l.czas, '%ddd %d %mmm %YYYY %HH:%NN:%SS') AS  Czas_str,
			IFNULL(NULLIF(CONCAT_WS(' ', 
				-- NULLIF(TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko)), ''), 
				IF(usr.Imie1 IS NULL, '???', TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko))),
				_Brackets('(', IFNULL(sdl.log_USER, l.useridn),')')
			), ''), '?') AS Who,
			lm.nazwa AS Miejsce_Str, -- lm.Symbol,
			lc.nazwa AS Czynnosc_Str,
			CONCAT_WS(IF(l.czynnosc = 2, '\nJest:\n', IF(l.czynnosc = 4, '\nByło:\n', '\nZmienono:\n')), 
				IFNULL(_VarStr(l.Info_View), _VarStr(l.Info)),
				IF(l.czynnosc = 2,  -- wstawianie
					GROUP_CONCAT(
						-- _ConcatPre(CONCAT(lp.fld_name, ': '), lp.new)
						_Concat_OLD_NEW(CONCAT(lp.fld_name, ': '), NULL, '', lp.new)
					SEPARATOR '\n'
					),
					IF(l.czynnosc = 4,  -- usuwanie
						GROUP_CONCAT(
							-- _ConcatPre(CONCAT(lp.fld_name, ': '), lp.old)
							_Concat_OLD_NEW(CONCAT(lp.fld_name, ': '), lp.old, '', NULL)
						SEPARATOR '\n'
						),
						GROUP_CONCAT(
							_Concat_OLD_NEW(CONCAT(lp.fld_name, ': '), lp.old, '', lp.new)
						SEPARATOR '\n'
						)
					)
				)
			) AS Info_Text,
			-- sdl.log_HOST_NAME,
			IFNULL(NULLIF(TRIM(CONCAT_WS('',
				-- NULLIF(TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko)), ''),
				IF(usr.Imie1 IS NULL, '?', TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko))),
				_Brackets(' (', IFNULL(sdl.log_USER, l.useridn), ')'),
				_ConcatPre(', APP: ', _Brackets('""', sdl.log_APPNAME, '""')),
				_ConcatPre(', HOST/IP: ', IFNULL(sdl.log_HOST, l.IP)),
				_ConcatPre(' : ', sdl.log_HOST_NAME),
				_ConcatPre(', MACADDRESS: ', sdl.log_MACADDRESS),
				NULL
			)), ''), '?') AS WhoFrom,
			l.* 
		FROM `log` l
		LEFT JOIN `logpo` lp ON lp.idnng = l.IDN
		LEFT JOIN `log_miejsca` lm ON lm.idn = l.Miejsce
		LEFT JOIN `log_czynnosci` lc ON lc.idn = l.czynnosc
		LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = l.IDSession
		LEFT JOIN `osoby` usr ON usr.GUID = IFNULL(l.OsobaGUID, sdl.log_USER_GUID)
		WHERE
			TRUE
			AND #UserGUID#
			AND #GUIDlink#
			AND #table_link#
			AND #czynnosc#
			AND #miejsce#
			AND #czas#
		GROUP BY l.IDN
		-- ORDER BY l.Idn DESC
		#ORDER BY#
		;
		"
		;
		*/
		SET _SQLText =
		"
		INSERT IGNORE INTO `t_log_select`
		SELECT
			l.*
		FROM `log` l
		LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = l.IDSession
		WHERE
			TRUE
			AND #UserGUID#
			AND #GUIDlink#
			AND #table_link#
			AND #czynnosc#
			AND #miejsce#
			AND #czas#
			AND #WHERE#
		GROUP BY l.IDN
		-- ORDER BY l.Idn DESC
		ORDER BY l.Idn DESC
		;
		"
		;
		-- było SET _SQLText = REPLACE(_SQLText, '#UserGUID#', IF(NULLIF(@.log.sel.UserGUID, '') IS NULL, 'TRUE', 'l.OsobaGUID = @.log.sel.UserGUID'));
		SET _SQLText = REPLACE(_SQLText, '#WHERE#', IF(NULLIF(@.log.sel.WHERE, '') IS NULL, 'TRUE', @.log.sel.WHERE));
		-- SET _SQLText = REPLACE(_SQLText, '#UserGUID#', IF(NULLIF(@.log.sel.UserGUID, '') IS NULL, 'TRUE', '(l.OsobaGUID = @.log.sel.UserGUID OR sdl.log_USER_GUID = @.log.sel.UserGUID)'));
		SET _SQLText = REPLACE(_SQLText, '#UserGUID#', IF(NULLIF(@.log.sel.UserGUID, '') IS NULL, 'TRUE', '(l.OsobaGUID = @.log.sel.UserGUID)'));
		SET _SQLText = REPLACE(_SQLText, '#GUIDlink#', IF(NULLIF(@.log.sel.GUIDlink, '') IS NULL, 'TRUE', 'l.GUIDlink = @.log.sel.GUIDlink'));
		SET _SQLText = REPLACE(_SQLText, '#table_link#', IF(NULLIF(@.log.sel.table_links, '') IS NULL, 'TRUE', CONCAT('l.table_link IN (', @.log.sel.table_links, ')')));
		SET _SQLText = REPLACE(_SQLText, '#czynnosc#', IF(NULLIF(@.log.sel.czynnosc, '') IS NULL, 'TRUE', CONCAT('l.czynnosc IN (', @.log.sel.czynnosc, ')')));
		SET _SQLText = REPLACE(_SQLText, '#miejsce#', IF(NULLIF(@.log.sel.miejsce, '') IS NULL, 'TRUE', CONCAT('l.miejsce IN (', @.log.sel.miejsce, ')')));

		SET _SQLText = REPLACE(_SQLText, '#czas#', IFNULL(NULLIF(@.log.sel.czas, ''), 'l.czas > (NOW() - INTERVAL 1 MONTH)'));
		SET _SQLText = REPLACE(_SQLText, '#ORDER BY#', IFNULL(NULLIF(@.log.sel.Order, ''), 'ORDER BY l.Idn DESC'));

		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		SELECT 
			_Format_DT(l.czas, '%DZ%DW %ddd %D %mmm %YH %HH:%NN:%SS') AS  Czas_str,
			IFNULL(NULLIF(CONCAT_WS(' ', 
				IF(usr.Imie1 IS NULL, '???', TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko))),
				IFNULL(TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko)), '???'),
				CONCAT('(', IFNULL(sdl.log_USER, l.useridn),')')
			), ''), '?') AS Who,
			lm.nazwa AS Miejsce_Str, -- lm.Symbol,
			lc.nazwa AS Czynnosc,
			(@.what := IF(l.czynnosc IN (2), 'INS', IF(l.czynnosc IN (4), 'DEL', ''))) AS what,
			CONCAT_WS(' - ', lm.nazwa, lc.nazwa) AS Miejsce_Czynnosc_Str, 
			CONCAT_WS('', 
				-- IFNULL(_VarStr(l.Info_View), _VarStr(l.Info)),	-- ale w info jest <?xml version="1.0" ... zatem nie zwracaj tego ...
				NULLIF(_VarStr(l.Info_View), ''),
				CONCAT_WS('',
					-- IF(l.czynnosc = 2 OR IFNULL(lp.what, '') = 'INS', '\nJest:\n', IF(l.czynnosc = 4 OR IFNULL(lp.what, '') = 'DEL', '\nByło:\n', '\nZmienono:\n')),
					IF(@.what = 'INS', '\nJest:\n', IF(@.what = 'DEL', '\nByło:\n', '\nZmienino:\n')),
					GROUP_CONCAT(
						_Concat_OLD_NEW(
							CONCAT(lp.fld_name, ': '), 
							IF(IFNULL(lp.what, @.what) = 'INS', NULL, lp.old),
							'',
							IF(IFNULL(lp.what, @.what) = 'DEL', NULL, lp.new)
						)
						SEPARATOR '\n'
					)
				)
			) AS Info_Text,
			-- sdl.log_HOST_NAME,
			IFNULL(NULLIF(TRIM(CONCAT_WS('',
				-- NULLIF(TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko)), ''),
				IF(usr.Imie1 IS NULL, '?', TRIM(CONCAT_WS(' ', usr.Imie1, usr.Nazwisko))),
				-- _Brackets(' (', IFNULL(sdl.log_USER, l.useridn), ')'),
				CONCAT(' (', IFNULL(sdl.log_USER, l.useridn), ')'),
				CONCAT(', APP: ', '"', sdl.log_APPNAME, '"'),
				CONCAT(', HOST/IP: ', IFNULL(sdl.log_HOST, l.IP)),
				CONCAT(' : ', sdl.log_HOST_NAME),
				CONCAT(', MACADDRESS: ', sdl.log_MACADDRESS),
				NULL
			)), ''), '?') AS WhoFrom,
			l.* 
		FROM `t_log_select` l
		LEFT JOIN `logpo` lp ON lp.idnng = l.IDN
		LEFT JOIN `log_miejsca` lm ON lm.idn = l.Miejsce
		LEFT JOIN `log_czynnosci` lc ON lc.idn = l.czynnosc
		LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = l.IDSession
		LEFT JOIN `osoby` usr ON usr.GUID = IFNULL(l.OsobaGUID, sdl.log_USER_GUID)
		WHERE
		TRUE
		GROUP BY l.IDN
		ORDER BY l.Idn DESC
		;
		
		
	END IF;
	
END$$


/* ************************************************************************************************************************************************************************
	Przygotowanie TempTabla z information_schema z danycmi zmienionymi do loga `logpo`
	24 II 2022 
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `_Log_Diff_Schema`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_Log_Diff_Schema`(
	IN _MODE VARCHAR(150),
	IN _DBName VARCHAR(50),
	IN _TableName VARCHAR(100),	
	-- IN _TableNameOLD VARCHAR(100),	
	-- IN _TableNameNEW VARCHAR(100),	
	IN _TableNameNative VARCHAR(100),	
	IN _KeyFieldName VARCHAR(100),	-- Gdy pusty to ryzykujemy 1 rekord
	IN _KeyValue VARCHAR(100),	
	IN _Fields TEXT,	-- ValidFields
	IN _Param_A VARCHAR(50),	
	IN _Param_B VARCHAR(50)	
)
/*

CALL _Log_Diff_Schema('Prepare', '', 'opng_e', 'opng', 'delegacje', 'GUID', 'xxx', '*,-Nocleg', '1', '');
CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t;
UPDATE `t_sys_DBSCHEMA_To_LOG` t SET t.IsEqu = (t.OLD <=> t.NEW);
SELECT t.* FROM `t_sys_DBSCHEMA_To_LOG` t WHERE NOT t.IsEqu;
DESC opng '%time%';
SELECT @_SQLText;

CALL _sys_DBSCHEMA_To_LOG('Prepare.Schema', '', 'opng_e', 'opng', 'GUID', @IdnOper, '', '');
SELECT t.* FROM t_sys_DBSCHEMA_To_LOG t;

*/
S_Log_Diff_Schema: BEGIN

	DECLARE _SQLText, _SQLTextUpdateCase, _SQLTextUpdateOR, _SQLTextUpdateCols, _SQLTextUpdate, _SQLFullText TEXT;
	SET 
		_DBName = IF(IFNULL(_DBName, '') = '', DATABASE(), _DBName)
	;
	IF _MODE LIKE '%INIT%'  OR _MODE LIKE '%Prepare%' THEN
		DROP TEMPORARY TABLE IF EXISTS `t_LOG_cmpr_inf`;
		CREATE TEMPORARY TABLE `t_LOG_cmpr_inf` (
			`TABLE_SCHEMA` VARCHAR(250) DEFAULT NULL,			-- Baza 
			`TableNameNative` VARCHAR(250) NOT NULL DEFAULT '',			-- Tabela rzeczywista z której pobierane sa dane
			`TN_OLD_WE` VARCHAR(250) NOT NULL DEFAULT '',		-- wejsciowa Tabela z OLD wartościam
			`TN_NEW_WE` VARCHAR(250) NOT NULL DEFAULT '',		-- wejsciowa Tabela z NEW wartościam
			`TN_OLD` VARCHAR(250) NOT NULL DEFAULT '',		-- Tabela = wejsciowa lub = z tempa z OLD wartościam
			`TN_NEW` VARCHAR(250) NOT NULL DEFAULT '',		-- Tabela = wejsciowa lub = z tempa z NEW wartościam
			`T_OLD_is_Temp` BOOLEAN DEFAULT FALSE,
			`T_NEW_is_Temp` BOOLEAN DEFAULT FALSE,
			`KeyFieldName` VARCHAR(250) NOT NULL DEFAULT '',		-- KeyFieldName
			`KeyValue` LONGTEXT,						
			`Fields` TEXT,		-- Tabela z NEW wartościam
			`ChangeCount` INTEGER DEFAULT 0
		)
		;
		DROP TEMPORARY TABLE IF EXISTS `t_schema`;
		CREATE TEMPORARY TABLE `t_schema` (
		  `LP` BIGINT(21) UNSIGNED NOT NULL DEFAULT 0,
		  `TABLE_NAME` VARCHAR(64) NOT NULL DEFAULT '',
		  `COLUMN_NAME` VARCHAR(64) NOT NULL DEFAULT '',
		  `T_OLD` BOOLEAN NOT NULL DEFAULT 0,
		  `T_NEW` BOOLEAN NOT NULL DEFAULT 0,
		  `DATA_TYPE` VARCHAR(64) NOT NULL DEFAULT '',
		  `COLUMN_KEY` VARCHAR(3) NOT NULL DEFAULT '',
		  `COLUMN_DEFAULT` LONGTEXT DEFAULT NULL,
		  `COLUMN_COMMENT` VARCHAR(1024) NOT NULL DEFAULT '',
		  `IS_NULLABLE` VARCHAR(3) NOT NULL DEFAULT '',
		  -- `V_OLD` VARCHAR(1000) DEFAULT NULL,
		  -- `V_NEW` VARCHAR(1000) DEFAULT NULL,
		  -- `IsEqu` BOOLEAN NOT NULL DEFAULT 0,
		  PRIMARY KEY (`COLUMN_NAME`)
		  -- PRIMARY KEY (`TABLE_NAME`, `COLUMN_NAME`)
		)
		;
		DROP TEMPORARY TABLE IF EXISTS `t_schema_OLD_NEW`;
		CREATE TEMPORARY TABLE `t_schema_OLD_NEW` (
		  `COLUMN_NAME` VARCHAR(64) NOT NULL DEFAULT '',
		  `OLD_Exists` BOOLEAN NOT NULL DEFAULT 0,
		  `NEW_Exists` BOOLEAN NOT NULL DEFAULT 0,
		  `OLD` VARCHAR(1000) DEFAULT NULL,
		  `NEW` VARCHAR(1000) DEFAULT NULL,
		  `IsEqu` BOOLEAN NOT NULL DEFAULT 0,
		  PRIMARY KEY (`COLUMN_NAME`)
		)
		;
		
		DROP TEMPORARY TABLE IF EXISTS `t_LOG_fields_OLD_NEW`;
		CREATE TEMPORARY TABLE `t_LOG_fields_OLD_NEW` (
			`FieldName` VARCHAR(250) NOT NULL DEFAULT '',		-- Col_NameAs
			`OLD_Value` LONGTEXT,						-- Fetch
			`NEW_Value` LONGTEXT,						-- Fetch
			`IsEqu` BOOLEAN,
			`Native_Exists` BOOLEAN DEFAULT TRUE,		-- Col_NameAs
			`Old_Exists` BOOLEAN DEFAULT FALSE,		-- Col_NameAs
			`New_Exists` BOOLEAN DEFAULT FALSE,		-- Col_NameAs
			`FieldExists` BOOLEAN,
			`Deleted` BOOLEAN,
			PRIMARY KEY `FieldName`(`FieldName`)
		)
		;
		INSERT IGNORE INTO `t_LOG_cmpr_inf`	
		SET
			TABLE_SCHEMA = IFNULL(NULLIF(_DBName, ''), SCHEMA()),
			KeyFieldName = _KeyFieldName,
			KeyValue = _KeyValue,
			Fields = IFNULL(NULLIF(REPLACE(CONCAT(_Fields, ','), ',,', ','), ''), '*'),
			TableNameNative = ''
		;
	END IF;
	
	IF _MODE LIKE '%ADD.Table.%' THEN
	/********************************************************************************************************************
		ADD.Table.OLD
		ADD.Table.NEW
		Dodawanie kolumn
				tabela[temp][+ tabela natywna][+ listy pól]
		Można dodawać kilka razy a kolejność ma znaczenie
		Gdy mamy tabela[temp] to 
			- możemy mieć tabelę(e) natywną(e)
			- stworzona bedzie chwilowa tabela rzeczywista
		MODE
			From.Table[Temp][+Native]
		Tabele są podawane po przecinku
		W Diff porównujemy zawsze dwa zestawy o jednolitej pojedynczej strukturze danych nawet 
		jeśli pola należą do róznych natywnych tabel - może to byc temptable złożona z 2-3 tabel natywnych
		ale sama w sobie ma jednoznaczne pola
	*********************************************************************************************************************/
		SET 
			_TableName = IFNULL(_TableName, ''),
			@.Schema.in.MODE = IF(_MODE LIKE '%ADD.Table.OLD%', 'OLD', 'NEW')
		;
		SET 
			@.Schema.in.MODE.OLD = (@.Schema.in.MODE = 'OLD'),
			@.Schema.in.MODE.NEW = (@.Schema.in.MODE = 'NEW')
		;
set @X = '1';
		UPDATE `t_LOG_cmpr_inf`	ti
		SET
			-- ti.KeyFieldName = _KeyFieldName,
			-- ti.KeyValue = _KeyValue,
			-- ti.Fields = REPLACE(CONCAT(_Fields, ','), ',,', ',')
			-- ti.TableNameNative = _TableNameNative,
			ti.TN_OLD_WE = (@.ti.TN_OLD_WE := IF(@.Schema.in.MODE.OLD AND _TableName <> '', _TableName, ti.TN_OLD_WE)),
			ti.TN_OLD = @.ti.TN_OLD_WE,
			ti.TN_NEW_WE = (@.ti.TN_OLD_WE := IF(@.Schema.in.MODE.NEW AND _TableName <> '', _TableName, ti.TN_NEW_WE)),
			ti.TN_NEW = @.ti.TN_NEW_WE
		;
set @X = '2';
		UPDATE `t_LOG_cmpr_inf`	ti
		SET
			ti.T_OLD_is_Temp = (@.ti.T_OLD_is_Temp := 
				IF(@.Schema.in.MODE.OLD AND TN_OLD_WE <> '',
					NOT EXISTS(
						SELECT 
							t.TABLE_NAME 
						FROM information_schema.`TABLES` t 
						WHERE 
							t.TABLE_SCHEMA = ti.TABLE_SCHEMA 
							AND t.TABLE_NAME = ti.TN_OLD_WE
					),
					ti.T_OLD_is_Temp
				)
			),
			ti.T_NEW_is_Temp = (@.ti.T_NEW_is_Temp := 
				IF(@.Schema.in.MODE.NEW AND TN_NEW_WE <> '',
					NOT EXISTS(
						SELECT 
							t.TABLE_NAME 
						FROM information_schema.`TABLES` t 
						WHERE 
							t.TABLE_SCHEMA = ti.TABLE_SCHEMA 
							AND t.TABLE_NAME = ti.TN_NEW_WE
					),
					ti.T_NEW_is_Temp
				)
			)
		;
set @X = '3';
		IF @.Schema.in.MODE.OLD THEN
		--	Tabela OLD
			IF @.ti.T_OLD_is_Temp THEN
				CALL _Schema_Diff_Tools('Create.Table.from.TempTable', _TableName, '', '', '', '', '');
				UPDATE `t_LOG_cmpr_inf`	ti				
				SET 
					ti.TN_OLD = @.Schema.new.CON.TN
				;
			END IF;
		ELSE
		--	Tabela NEW
			IF @.ti.T_NEW_is_Temp THEN
				CALL _Schema_Diff_Tools('Create.Table.from.TempTable', _TableName, '', '', '', '', '');
				UPDATE `t_LOG_cmpr_inf` ti				
				SET 
					ti.TN_NEW = @.Schema.new.CON.TN
				;
			END IF;
		END IF;
set @X = '4';
		
		INSERT IGNORE INTO `t_schema`
			SELECT
				c.ORDINAL_POSITION AS LP, c.TABLE_NAME, c.COLUMN_NAME, 
				-- @.Schema.in.MODE.OLD AS T_OLD
				-- @.Schema.in.MODE.NEW AS T_NEW
				(c.TABLE_NAME = ti.TN_OLD) AS T_OLD,
				(c.TABLE_NAME = ti.TN_NEW) AS T_NEW,
				c.DATA_TYPE, c.COLUMN_KEY, c.COLUMN_DEFAULT, c.COLUMN_COMMENT, c.IS_NULLABLE
				-- ,NULL, NULL, 0
				-- ,c.*
			FROM `t_LOG_cmpr_inf` ti, information_schema.`COLUMNS` c
			WHERE 
				c.TABLE_SCHEMA = ti.TABLE_SCHEMA
				AND 
				c.TABLE_NAME IN (ti.TN_OLD, ti.TN_NEW) 
			ON DUPLICATE KEY UPDATE
				T_OLD = T_OLD OR (c.TABLE_NAME = ti.TN_OLD),
				T_NEW = T_NEW OR (c.TABLE_NAME = ti.TN_NEW)
		;
		
set @X = '5';
		INSERT IGNORE INTO `t_schema_OLD_NEW`
		(COLUMN_NAME)
		SELECT 
			s.COLUMN_NAME 
		FROM `t_schema` s, `t_LOG_cmpr_inf` ti
		WHERE
			NOT s.COLUMN_KEY IN ('PRI', 'UNI')
			-- AND NOT s.COLUMN_NAME IN ('IDN', 'GUID', 'alocaltime', 'localtime', 'remotetime', 'tag')
			AND NOT s.COLUMN_NAME IN ('GUID', 'localtime', 'alocaltime', 'remotetime', 'tag')
			AND
			(
				(ti.fields  LIKE CONCAT('%', s.COLUMN_NAME, ',%'))	-- gdy na liście
				OR
				(ti.fields LIKE '*%')	-- gdy *
			)
			AND NOT (ti.fields  LIKE CONCAT('%-', s.COLUMN_NAME, ',%'))
		;
set @X = '6';
		SELECT
			ti.KeyFieldName,		-- KeyFieldName
			ti.KeyValue,
			CONCAT_WS('&',
				'Alias=td',
				CONCAT('KeyFieldName=', ti.KeyFieldName),
				CONCAT('KeyValue=', ti.KeyValue)
			)
		INTO
			@.Schema.KeyFieldName,		-- KeyFieldName
			@.Schema.KeyValue,
			@.Schema.Param
		FROM `t_LOG_cmpr_inf` ti
		;
set @X = '7';
		CALL _Schema_Diff_Tools('Get.WHERE.Keys', '', '', '', '', '', @.Schema.Param);
	--	w @.Get.WHERE.Keys mamy ON/WHERE	
		-- DELETE FROM `t_schema` WHERE COLUMN_NAME IN ('IDN', 'GUID', 'localtime', 'remotetime', 'tag');
set @X = '8';
		SET @.Sec_UPDATE = 
		(
			SELECT
				CONCAT_WS('',
					'UPDATE `t_schema_OLD_NEW` t\n',
					-- 'INNER JOIN `t_LOG_cmpr_inf` ti ON TRUE',
					-- 'LEFT JOIN `#TN#` td ON #td.ON#	-- OLD\n',
					'LEFT JOIN `',
						IF(@.Schema.in.MODE.OLD, ti.TN_OLD, ti.TN_NEW),
						-- '` td ON #td.ON#	',
						'` td ON ', @.Get.WHERE.Keys, '\n',
					'SET\n',
						't.#old#_Exists = td.#_KeyFieldName# IS NOT NULL,\n',
						-- 't.NEW_Exists = t2.#_KeyFieldName# IS NOT NULL,\n',
						't.#old# = \n',
						'CASE t.COLUMN_NAME\n',
						GROUP_CONCAT(
							CONCAT(
								-- 'WHEN "', t.COLUMN_NAME, '" THEN _VarStr(t1.', t.COLUMN_NAME, ')'
								'WHEN "', t.COLUMN_NAME, '" THEN _VarStr(td.', t.COLUMN_NAME, ')'
							)
						SEPARATOR '\n'
						),
						'\nEND\n',
						'WHERE\n TRUE',
						'\n;'

				) AS Sec_UPDATE
			FROM `t_LOG_cmpr_inf` ti, `t_schema_OLD_NEW` t, `t_schema` s
			WHERE
				s.COLUMN_NAME = t.COLUMN_NAME
			ORDER BY s.LP
		)
		;
		SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#old#', @.Schema.in.MODE);
		SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#td.ON#', @.Get.WHERE.Keys);
		-- SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#_TableName1#', _TableName1);
		-- SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#_TableName2#', _TableName2);
		SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#_KeyFieldName#', @.Schema.KeyFieldName);
		-- SET @.Sec_UPDATE = REPLACE(@.Sec_UPDATE, '#KEY#', _Key);

		SET @.DB._SQLText = @.Sec_UPDATE;
	--	Wykonaj	
		CALL _ExecuteCmd(@.DB._SQLText, @Error);
	--	Drop table if exists	
		CALL _Schema_Diff_Tools('Drop.Table.from.TempTable', _TableName, '', '', '', '', '');
	--	Nalicz róznice - UWAGA dopiero po drugiej tabeli ma to sens
		UPDATE `t_schema_OLD_NEW` t SET t.IsEqu = (t.OLD <=> t.NEW);
		




	END IF;
	
					
END$$

DELIMITER ;

/*
$Log$
*/

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
select useridn,count(distinct date(czas)) as ile_dni,mid(replace(if(compressed,uncompress(info),info),char(10),';'),0.57,80) as info from log where czynnosc=-1 and czas>date_sub(current_date,interval 1 month) and not (if(compressed,uncompress(info),info) like "%niezna%" or if(compressed,uncompress(info),info) like "%iepopr%") and useridn<>'jmam'  group by useridn order by ile_dni desc;

select
@pole as nazwapola, 
extractvalue(info,concat('//DATAPACKET/ROWDATA/ROW[1]/@',@pole)) as pole_bylo,
extractvalue(info,concat('//DATAPACKET/ROWDATA/ROW[2]/@',@pole)) as pole_jest

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
