 DELIMITER $$

/* ************************************************************************************************************************************************************************
	sys_browsers_tools
************************************************************************************************************************************************************************ */	
DROP PROCEDURE IF EXISTS `sys_browsers_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sys_browsers_tools`(
	IN _MODE VARCHAR(250),
	IN _Id_browser VARCHAR(50),	
	IN _User VARCHAR(50),	
	IN _Limit VARCHAR(50),	
	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)	
)
/*
	Przyklad wywol.
	
	CALL sys_browsers_tools('', '', '', '', '', '', '');
*/

S_sys_browsers_tools: BEGIN 

	DECLARE _PrfGUID_c, _PrfGUID_f, _PrfGUID_p, _PrfGUID_d VARCHAR(38);
	DECLARE _sql_text_SELECT MEDIUMTEXT; -- @.sql.text.SELECT
	DECLARE _SQLText MEDIUMTEXT;
	SET @._User = _User;
	SET @@group_concat_max_len = 1024*1024;
	
	IF IFNULL(_User, '') = '' THEN
		IF IFNULL(@SYSTEM.Client.Session.log_USER_GUID, '') = '' THEN
			/*	20 XII 2023
			CALL _sys_db_logons_rec_tools('GET.@SYSTEM.Client.Session.log_USER_GUID', @SYSTEM.Client.Session.GUID, 0, '', '', '', '', '');
			*/
			CALL _sessions_APP('SET.VAR', '', '', '', '', '', '');
		END IF;
		SET _User = @SYSTEM.Client.Session.log_USER_GUID;
	END IF;
	SET @xxxx._User = _User;
	
	IF _MODE = '_prepare_names' THEN
	/********************************************************************************************************************************
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
	********************************************************************************************************************************/
		-- SET @SYSTEM.Client.Session.ID = '';
		SET @SYSTEM.Client.Session.GUID = IFNULL(@SYSTEM.Client.Session.GUID, '');
		-- md5!!! SET @t.temptable.md5 = MD5(CONCAT(_Id_browser, @SYSTEM.Client.Session.GUID));
		SET @t.temptable.md5 = MD5_2(_Id_browser, @SYSTEM.Client.Session.GUID);
		SET @t.temptable.name = CONCAT('`t_', @t.temptable.md5, '`');
		SET @t.temptable.name.check = CONCAT('`t_check_', @t.temptable.md5, '`');
		SET @t.temptable.name.maxtime = CONCAT('`t_maxtime_', @t.temptable.md5, '`');
		SET @t.temptable.name.key = CONCAT('`t_key_', @t.temptable.md5, '`');
		SET @t.temptable.name.information_schema = CONCAT('`t_information_schema_', @t.temptable.md5, '`');
		SET @t.temptable.name.TAGS = CONCAT('`t_TAGS_', @t.temptable.md5, '`');
	END IF;

	IF _MODE = 'browsers' THEN
	/********************************************************************************************************************************
		CALL sys_browsers_tools('browsers','','','','','','','','');
	********************************************************************************************************************************/
		-- SELECT ID, Nazwa, `Comment`, treenode FROM _sys_browsers_n;
		SELECT 
			-- n.*, 
		--	n.ID, n.Nazwa, IF(IFNULL(n.UgrpGuid, '') = '', 'ALL', n.UgrpGuid) AS UgrpGuid, n.ModifyAt, n.treenode 
		-- FROM _sys_browsers_n n
		-- WHERE
		--	n.Active	
			n.ID, IF(v.view IS NULL , n.Nazwa, v.view) AS Nazwa, IF(IFNULL(n.UgrpGuid, '') = '', 'ALL', n.UgrpGuid) AS UgrpGuid, n.ModifyAt, n.treenode,v.view AS ActiveItem, v.GUID AS LocalView 
		FROM _sys_browsers_n n, _sys_browsers_views v		
		WHERE
			n.Active AND n.ID = v.Id_browser				
		;
-- TODO: ugrpguid

	END IF;
	
	IF _MODE IN ('select.init', 'select.init.for.information_schema') THEN
	/********************************************************************************************************************************
		INFO SELECT
		Przygotowuje wszystkie select i tempy o ile to konieczne
		Zwraca tekst ostrzegajacy o przekroczenu limitu rekordu o ile brak jest zadanego limitu i jest limit w definicji browsera
		CALL sys_browsers_tools('select.init', 'k', 'jmam', '', '', '', '', '', '');
		LIMIT 450
		CALL sys_browsers_tools('select.init', 'k', 'jmam', '450', '', '', '', '', '');
		lub 50 (mozna nie pisac "limit"
		CALL sys_browsers_tools('select.init', 'k', 'jmam', 'limit 50', '', '', '', '', '');
		ALE TAKZE dla information_schema
		CALL sys_browsers_tools('select.init.for.information_schema', 'k', 'jmam', '', '', '', '', '', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
		
		SET 
			@.sql.Err = '',
			@.sql.n.Exists = FALSE
		;
		SELECT
			n.Params,
			n.LimitRec,
			TRUE,
			EXISTS(SELECT g.GrupaGUID FROM `grupy_osob` g WHERE g.GrupaGUID = IF(IFNULL(n.UgrpGuid, '') = '', 'ALL', n.UgrpGuid) AND g.OsobaGUID = _User) AS UgrpGuid_OK
		INTO
			@.sql.n.Params,
			@.sql.n.LimitRec,
			@.sql.n.Exists,
			@.sql.n.UgrpGuid_OK
		FROM `_sys_browsers_n` n
		WHERE
			n.ID = _Id_browser
		;
		IF NOT @.sql.n.Exists THEN	
			SET @.sql.Err = 'Nie istnieje taki browser!';
		ELSEIF NOT @.sql.n.UgrpGuid_OK THEN
			SET @.sql.Err = 'Nie ma uprawnien do takiego browsera!';
		END IF;

		IF @.sql.Err = '' THEN
			SET @.sql.Use.Agg = (LOCATE('Agg', @.sql.n.Params) > 0);
			SET @.sql.Use.Temporary.table = @.sql.Use.Agg OR (LOCATE('Temp', @.sql.n.Params) > 0);
			
			IF _MODE != 'select.init.for.information_schema' THEN
			set @.trace.Y = 'ha';
				CALL sys_browsers_tools('sqltext.build.select', _Id_browser, _User, _Limit, '', '', _Param_C, _Param_D, _Param_E);
				
-- CALL _PrepareSQLText('SQL.PREPARE.t_sql.prepare', '', '', '', @SQL, '', '', '', '');

CALL _PrepareSQLText('SQL.PREPARE.t_sql.prepare', '', '', '', @SQL, '', '', '', '');
CALL _PrepareSQLText('SQL.PREPARE.INIT', _Id_browser, '', '', @SQL, '', '', '', '');
-- CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', _Id_browser, 'Id_SQL', '', @sql.text.MAIN, '', '', '', '');
CALL _PrepareSQLText('SQL.PREPARE.FILL.main.SQL', _Id_browser, '', '', @sql, _Limit, '', '', '');
SELECT `SQL.Body` INTO @sql.text.template FROM `t_sql.prepare` LIMIT 1;
			ELSE
				CALL sys_browsers_tools('sqltext.build.information_schema', _Id_browser, _User, _Limit, '\n FALSE', _Param_B, _Param_C, _Param_D, _Param_E);
			END IF;
			
			SET 
				@.sql.INFO = '',
				@.sql.n.LimitRec.returned = 0,
				@.sql.Err = ''
			;
			CALL _sys_usr_profile_utilities('get.profil.default.PARAMS', _Id_browser, _PrfGUID_p, @_All_PrfGUID, _User, '', '', '', '', '');
			--	przygotu TempTable parametrow dla _PrfGUID_p
			CALL _PrepareSQLText_with_HashParams('init', @We, '', @_f_Value_Down, _PrfGUID_p, @_Result, @_ResultMsg, '', '');
			--	Inicjalne
			CALL _PrepareSQLText_with_HashParams('Execute.Before.After.execute.sql.INIT', @nothing, @nothing, @nothing, _Id_browser, @.sql.Err, @.sql.INFO, '', '');
			--	Finalne przenies gdzie indziej TODO !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			CALL _PrepareSQLText_with_HashParams('Execute.Before.After.execute.sql.FINAL', @nothing, @nothing, @nothing, _Id_browser, @.sql.Err, @.sql.INFO, '', '');
		END IF;
		
		IF @.sql.Err = '' THEN
		--	Bez bledu na razie zatem ...
		--	@sql.text.template wypenij parametrami o ile istnieja tam jakies #param#
			CALL _PrepareSQLText_with_HashParams('Fill.content', @sql.text.template, '', @_f_Value_Down, '', @.sql.Err, @.sql.INFO, '', '');	
		END IF;
		
		IF @.sql.Err = '' AND _MODE != 'select.init.for.information_schema' THEN
		--	Bez bledu na razie zatem ...
		--	Gdy nie było limitu - sprawdz czy zwracany tekst nie bedzie zbyt duzy
			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.check);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
			SET _SQLText = CONCAT('CREATE TEMPORARY TABLE ', @t.temptable.name.check, @sql.text.template.check.count);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
			SELECT FOUND_ROWS() INTO @.sql.n.LimitRec.returned;
			
			
			
			IF @.sql.text.LIMIT = '' THEN
				IF @.sql.n.LimitRec.returned > @.sql.n.LimitRec THEN
					SET @.sql.INFO = REPLACE(REPLACE('Liczba pozycji w przegladarce (#r) przekroczy ustalony maksymalny limit (#n)!\nZmien ustawienia filtrow.', '#n', @.sql.n.LimitRec), '#r', @.sql.n.LimitRec.returned);  
				END IF;
			END IF;

			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.check);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
		
		SELECT _VarStr(_ConcatSTR2(@.sql.INFO, @.sql.Err, ' ')) AS Info, @.sql.n.LimitRec.returned AS Count, CURRENT_TIMESTAMP() AS SelectTime;
		
		-- LEAVE S_sys_browsers_tools;
	END IF;
	
	IF _MODE = 'select' THEN
	/********************************************************************************************************************************
		FULL SELECT
		CALL sys_browsers_tools('select', 'k', 'jmam', '', '', '', '', '', '');
	********************************************************************************************************************************/
		IF @.sql.Use.Temporary.table THEN
		--	Usun temp table	
			SET _SQLText = REPLACE('DROP TEMPORARY TABLE IF EXISTS @t.temptable.name', '@t.temptable.name', @t.temptable.name);
			SET @_SQLText.Drop.temp = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	kreuj temp table	
			SET @t.temptable.name.SQL = REPLACE(REPLACE('CREATE TEMPORARY TABLE @t.temptable.name \n@sql.text.template', '@t.temptable.name', @t.temptable.name), '@sql.text.template', @sql.text.template);
			SET _SQLText = @t.temptable.name.SQL;
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		-- teraz select
			SET _SQLText = REPLACE('SELECT * FROM @t.temptable.name', '@t.temptable.name', @t.temptable.name);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
			SET _SQLText = @sql.text.template;
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
	END IF;
	
	IF _MODE = 'select.agg' THEN
	/********************************************************************************************************************************
		Agg SELECT
		CALL sys_browsers_tools('select.agg', 'k', 'jmam', '', '', '', '');
	********************************************************************************************************************************/
		IF @.sql.Use.Agg THEN
			SET _SQLText = REPLACE(REPLACE('SELECT\n@.sql.text.SELECT.AGG \nFROM @t.temptable.name \n;', '@.sql.text.SELECT.AGG', @.sql.text.SELECT.AGG), '@t.temptable.name', @t.temptable.name);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	Usun temp table	
 			SET _SQLText = REPLACE('DROP TEMPORARY TABLE IF EXISTS @t.temptable.name', '@t.temptable.name', @t.temptable.name);
			SET @_SQLText.Drop.temp = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
			SET _SQLText = 'SELECT\n"" AS ""';
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
	END IF;

	IF _MODE = 'select.Get.SQL' THEN
	/********************************************************************************************************************************
		Agg SELECT
		CALL sys_browsers_tools('select.Get.SQL', 'k', 'jmam', '', '', '', '');
	********************************************************************************************************************************/
		SELECT
			@sql.text.template AS SQL_text
		;
	END IF;
	
	IF _MODE = 'select.maxtime.init' THEN
	/********************************************************************************************************************************
		SELECT ost. maxtime - prepare
		CALL sys_browsers_tools('select.maxtime.init', 'k', 'jmam', '', '', '2014-07-30 14:27:20', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
		SET @.sql.maxtime.Field = '';
		SET @.sql.Key.Field = '';
		SELECT
			c.col_NameAS
		INTO
			@.sql.Key.Field
		FROM `_sys_browsers_col` c
		WHERE
			c.Id_browser = _Id_browser
			AND c.IsKey
			AND NOT c.Deleted
		LIMIT 1
		;	
		SELECT
			c.col_NameAS
		INTO
			@.sql.maxtime.Field
		FROM `_sys_browsers_col` c
		WHERE
			c.Id_browser = _Id_browser
			AND c.IsLocalTime
			AND NOT c.Deleted
		LIMIT 1
		;	
		
		/* 
		było
		SELECT
			p.C_FieldName
		FROM `_sys_browsers_p` p
		WHERE
			p.Id_browser = _Id_browser
			AND p.IsKey
			AND NOT p.Deleted
		LIMIT 1
		INTO 
			@.sql.Key.Field
		;	
		SELECT
			p.C_FieldName
		FROM `_sys_browsers_p` p
		WHERE
			p.Id_browser = _Id_browser
			AND p.IsLocalTime
			AND NOT p.Deleted
		LIMIT 1
		INTO 
			@.sql.maxtime.Field
		;	
		*/
		IF IFNULL(@.sql.maxtime.Field, '') != '' AND IFNULL(@.sql.Key.Field, '') != '' THEN
			CALL sys_browsers_tools('sqltext.build.maxtime', _Id_browser, _User, _Limit, CONCAT('\n', @.sql.maxtime.Field, ' > ', QUOTE(_Param_A)), _Param_B, _Param_C, _Param_D, _Param_E);
			-- SET _SQLText = REPLACE(@sql.text.template, '\nTRUE', CONCAT('\n', @.sql.maxtime.Field, ' > ', QUOTE(_Param_A)));
			SET @t.temptable.name.maxtime.SQL = @sql.text.template;
			-- select @t.temptable.name.maxtime.SQL; 
		--	Gdy nie było limitu - sprawdz czy zwracany tekst nie bedzie zbyt duzy
		--	DROP
			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.maxtime);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	CREATE
			SET _SQLText = CONCAT('CREATE TEMPORARY TABLE ', @t.temptable.name.maxtime, @t.temptable.name.maxtime.SQL);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	Znajdz sumy i zwroc	
			SELECT FOUND_ROWS() INTO @.sql.n.maxtime.count.returned;
			SELECT @.sql.n.maxtime.count.returned AS Count;
			

			/*
			SET @t.temptable.name.maxtime = CONCAT('`t_maxtime_', @t.temptable.md5, '`');





		--	Gdy nie było limitu - sprawdz czy zwracany tekst nie bedzie zbyt duzy
			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.maxtime);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
			SET _SQLText = CONCAT('CREATE TEMPORARY TABLE ', @t.temptable.name.maxtime, @t.temptable.name.maxtime.SQL);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
			SELECT FOUND_ROWS() INTO @.sql.n.maxtime.count.returned;
			
			
			
			IF @.sql.text.LIMIT = '' THEN
				IF @.sql.n.LimitRec.returned > @.sql.n.LimitRec THEN
					SET @.sql.INFO = REPLACE(REPLACE('Liczba pozycji w przegladarce (#r) przekroczy ustalony maksymalny limit (#n)!\nZmien ustawienia filtrow.', '#n', @.sql.n.LimitRec), '#r', @.sql.n.LimitRec.returned);  
				END IF;
			END IF;

			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.check);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		*/
		-- CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
		
	END IF;
	
	IF _MODE = 'select.maxtime.select.delta' THEN
	/********************************************************************************************************************************
		SELECT ost. maxtime
		CALL sys_browsers_tools('select.maxtime', 'k', 'jmam', '', '', '2014-07-30 14:27:20', '');
	********************************************************************************************************************************/
	--	SELECT
		SET _SQLText = CONCAT('SELECT * FROM ', @t.temptable.name.maxtime);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
	--	DROP
		SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.maxtime);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);

	END IF;
	
	IF _MODE = 'select.key.init' THEN
	/********************************************************************************************************************************
		SELECT  dla rekordu
		CALL sys_browsers_tools('select.key.init', 'k', 'jmam', '', '', 'IM_8e5eb2fc37bbfca04e1b1b1fbb49a26b', '');
	********************************************************************************************************************************/
		-- IsKey
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
		SET @.sql.Key.Field = '';
		SELECT
			c.col_NameAS
		INTO
			@.sql.Key.Field
		FROM `_sys_browsers_col` c
		WHERE
			c.Id_browser = _Id_browser
			AND c.IsKey
			AND NOT c.Deleted
		LIMIT 1
		;	
		/*
		było
		SELECT
			p.C_FieldName
		FROM `_sys_browsers_p` p
		WHERE
			p.Id_browser = _Id_browser
			AND p.IsKey
			AND NOT p.Deleted
		LIMIT 1
		INTO 
			@.sql.Key.Field
		;
		*/
		/*
		IF IFNULL(@.sql.Key.Field, '') != '' THEN
			CALL sys_browsers_tools('sqltext.build.select', 'k', 'jmam', '', '', '', '');
			SET _SQLText = REPLACE(@sql.text.template, '\nTRUE', CONCAT('\n', @.sql.Key.Field, ' = ', QUOTE(_Param_A)));
			SET @_SQLText = _SQLText;
			select @_SQLText; 
		-- CALL _ExecuteCmd(_SQLText, @Error);
		END IF;
		*/
		
		-- LEAVE S_sys_browsers_tools;
		-- CALL sys_browsers_tools('sqltext.build.key', _Id_browser, _User, _Limit, CONCAT('\n', @.sql.Key.Field, ' = ', QUOTE(_Param_A)), _Param_B);
		
		-- LEAVE S_sys_browsers_tools;
		
		IF IFNULL(@.sql.Key.Field, '') != '' THEN
			CALL sys_browsers_tools('sqltext.build.key', _Id_browser, _User, _Limit, CONCAT('\n', @.sql.Key.Field, ' = ', QUOTE(_Param_A)), _Param_B, _Param_C, _Param_D, _Param_E);
			SET @t.temptable.name.key.SQL = @sql.text.template;
			-- select @t.temptable.name.key.SQL; 
		--	Gdy nie było limitu - sprawdz czy zwracany tekst nie bedzie zbyt duzy
		--	DROP
			SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.key);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	CREATE
			SET _SQLText = CONCAT('CREATE TEMPORARY TABLE ', @t.temptable.name.key, @t.temptable.name.key.SQL);
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		--	Znajdz sumy i zwroc	
			SELECT FOUND_ROWS() INTO @.sql.n.maxtime.count.returned;
			SELECT @.sql.n.maxtime.count.returned AS Count;
			
		END IF;
		
	END IF;
	
	IF _MODE = 'select.key.select.delta' THEN
	/********************************************************************************************************************************
		SELECT ost. dla danego klucza
		CALL sys_browsers_tools('select.key.select.delta', '', '', '', '', '', '');
	********************************************************************************************************************************/
	--	SELECT
		SET _SQLText = CONCAT('SELECT * FROM ', @t.temptable.name.key);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
	--	DROP
		SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.key);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);

	END IF;
	
	
	IF _MODE = 'Update.browsers_p.from.information_schema' THEN
	/********************************************************************************************************************************
		z information_schema rozpisuje w `_sys_browsers_col` pola DB_FieldType a przez to GUI_FieldType
		CALL sys_browsers_tools('Update.browsers_p.from.information_schema', 'k', '', '', '', '', '', '', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);

	--	DROP
		SET _SQLText = CONCAT('DROP TABLE IF EXISTS ', @t.temptable.name.information_schema);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		CALL sys_browsers_tools('select.init.for.information_schema', _Id_browser, _User, _Limit, '\n FALSE', _Param_B, _Param_C, _Param_D, _Param_E);
		-- CALL sys_browsers_tools('sqltext.build.information_schema', _Id_browser, _User, _Limit, '\n FALSE', _Param_B, _Param_C, _Param_D, _Param_E);
		-- było CALL sys_browsers_tools('build.sql._sys_browsers_sect.information_schema', _Id_browser, _User, _Limit, '\n FALSE', _Param_B, _Param_C, _Param_D, _Param_E);
		IF IFNULL(@sql.text.template, '') = '' THEN
			SELECT s.SQL INTO @sql.text.template FROM `_sys_browsers_sql` s WHERE s.Id_browser = _Id_browser AND s.Kind = 'SQL' LIMIT 1;
		END IF;
		
		SET @t.temptable.name.information_schema.SQL = @sql.text.template;

	--	kreuj table	
		SET @t.temptable.name.information_schema.SQL = REPLACE(REPLACE('CREATE TABLE @t.temptable.name.information_schema \n@sql.text.template', '@t.temptable.name.information_schema', @t.temptable.name.information_schema), '@sql.text.template', @sql.text.template);
		SET _SQLText = @t.temptable.name.information_schema.SQL;
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
	-- teraz select
		-- select @_SQLText;

		SET _SQLText = "
		INSERT IGNORE INTO `_sys_browsers_col` 
		(GUID, Id_browser, Kind, DB_FieldType, LP, col_Expr, col_Name, col_NameAS, DisplayLabel, COMMENT)
		SELECT -- SUM(table_name='zmpo') = SUM(table_name='zmpo_e') AS ok 
			UUID() AS GUID,
			'_Id_browser' AS Id_browser,
			'COL' AS Kind,
			c.Data_TYPE,
			-- 'k.From' AS Source_sect,
			c.ORDINAL_POSITION AS LP,
			'$' AS col_Expr,
			c.COLUMN_NAME AS col_Name,
			c.COLUMN_NAME AS col_NameAS,
			c.COLUMN_NAME AS DisplayLabel,
			COLUMN_COMMENT AS `Comment`
		FROM information_schema.columns c 
		WHERE 
			c.table_schema=DATABASE() 
			AND c.table_name = '@t.temptable.name.information_schema'
		;
		"
		;
		SET _SQLText = REPLACE(_SQLText, '@t.temptable.name.information_schema', REPLACE(@t.temptable.name.information_schema, '`', ''));
		SET _SQLText = REPLACE(_SQLText, '_Id_browser', _Id_browser);
		SET @_SQLText = _SQLText;
		SET @_SQLText_ins = _SQLText;
		
		
		CALL _ExecuteCmd(_SQLText, @Error);
		
		SET _SQLText = "
		UPDATE information_schema.columns ic, `_sys_browsers_col` c
		SET
			c.DB_FieldType = ic.Data_TYPE,
			c.GUI_FieldType =
				CASE 
				WHEN ic.Data_TYPE IN ('int', 'smallint', 'tinyint', 'mediumint', 'bigint') THEN 'Int'
				WHEN ic.Data_TYPE IN ('double', 'float', 'decimal') THEN 'float'
				WHEN ic.Data_TYPE IN ('decimal', 'numeric') THEN 'float'
				WHEN ic.Data_TYPE IN ('date') THEN 'date'
				WHEN ic.Data_TYPE IN ('time') THEN 'time'
				WHEN ic.Data_TYPE IN ('timestamp', 'datetime') THEN 'datetime'
				WHEN ic.Data_TYPE IN ('TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT') THEN 'text'
				WHEN ic.Data_TYPE IN ('TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB') THEN 'Blob'
				WHEN ic.Data_TYPE IN ('CHAR', 'VARCHAR', 'SET', 'ENUM') THEN 'Str'
				ELSE
				'Str'
				END
		WHERE
			ic.table_schema=DATABASE() 
			AND ic.table_name = '@t.temptable.name.information_schema'
			AND	c.Id_browser = '_Id_browser'
			AND ic.COLUMN_NAME = c.col_NameAS
		;
		"
		;
		SET _SQLText = REPLACE(_SQLText, '@t.temptable.name.information_schema', REPLACE(@t.temptable.name.information_schema, '`', ''));
		SET _SQLText = REPLACE(_SQLText, '_Id_browser', _Id_browser);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		
		/*

SELECT -- SUM(table_name='zmpo') = SUM(table_name='zmpo_e') AS ok 
	c.Data_TYPE,
	CASE 
	WHEN c.Data_TYPE IN ('int', 'smallint', 'tinyint', 'mediumint', 'bigint') THEN 'Int'
	WHEN c.Data_TYPE IN ('double', 'float', 'decimal') THEN 'float'
	WHEN c.Data_TYPE IN ('decimal', 'numeric') THEN 'float'
	WHEN c.Data_TYPE IN ('date') THEN 'date'
	WHEN c.Data_TYPE IN ('time') THEN 'time'
	WHEN c.Data_TYPE IN ('timestamp', 'datetime') THEN 'datetime'
	WHEN c.Data_TYPE IN ('TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT') THEN 'text'
	WHEN c.Data_TYPE IN ('TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB') THEN 'Blob'
	WHEN c.Data_TYPE IN ('CHAR', 'VARCHAR', 'SET', 'ENUM') THEN 'Str'
	ELSE
	'Str'
	END
	AS GUI_FieldType_init,
	p.GUI_FieldType,
	-- 'Str','Int','float','Bool','Date','Time','DateTime','Text','Blob'
	c.*
FROM information_schema.columns c, `_sys_browsers_p` p 
WHERE 
	table_schema=DATABASE() AND table_name = 't_information_schema_dbdab7978bb1c24226e6a7a5382347a1'
	AND	p.Id_browser = _Id_browser
	AND c.COLUMN_NAME = p.FieldName
;

		SET _SQLText = REPLACE('SELECT * FROM @t.temptable.name', '@t.temptable.name', @t.temptable.name);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);

		
		SET _SQLText = CONCAT('SELECT * FROM ', @t.temptable.name.information_schema);
		SET @_SQLText = _SQLText;
		select @t.temptable.name.information_schema.SQL, _Id_browser, _User, _Limit, '\n FALSE', _Param_B, _Param_C, _Param_D, _Param_E;
		
		CALL _ExecuteCmd(_SQLText, @Error);
*/		
	--	DROP
		SET _SQLText = CONCAT('DROP TABLE IF EXISTS ', @t.temptable.name.information_schema);
		SET @_SQLText = _SQLText;
		-- CALL _ExecuteCmd(_SQLText, @Error);

	END IF;
	
	
	IF _MODE = 'TAG.Init' THEN
	/********************************************************************************************************************************
		Dla Zaznaczonych - Inicjacja
		CALL sys_browsers_tools('TAG.Init', 'k', 'jmam', '', '', '', '');
		Zwracam @t.temptable.name.TAGS czyli nazwe temporki aby apro wstawil tam id-ki
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
	--	DROP
		SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.TAGS);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		SET @t.temptable.name.TAGS.SQL = 
			"(
			  `ID` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
			  PRIMARY KEY (`ID`)
			);"
			;
	--	CREATE
		SET _SQLText = CONCAT('CREATE TEMPORARY TABLE ', @t.temptable.name.TAGS, @t.temptable.name.TAGS.SQL);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
		SELECT @t.temptable.name.TAGS AS TableName;
	END IF;
	
	IF _MODE = 'TAG.Execute' THEN
	/********************************************************************************************************************************
		Dla Zaznaczonych - wykonaj
		w _Param_A Akcja
		Zwracam rozne formy selectow - jedno kolumnowo/wierszowe lub wielo do wielu
		CALL sys_browsers_tools('TAG.Execute', 'k', 'jmam', '', '', 'PRINT', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
	--	TUTAJ AKCJE	
		SET @TAG.Execute.ACT = _Param_A;
		IF @TAG.Execute.ACT = 'PRINT' THEN
			SELECT 0 AS OK;
		END IF;
		IF @TAG.Execute.ACT = 'PRINT_2' THEN
			SELECT 0 AS OK;
		END IF;
	END IF;
	
	IF _MODE = 'TAG.Clear' THEN
	/********************************************************************************************************************************
		Dla Zaznaczonych - czysc
		CALL sys_browsers_tools('TAG.Clear', 'k', 'jmam', '', '', '', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('_prepare_names', _Id_browser, _User, _Limit, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E);
	--	DROP
		SET _SQLText = CONCAT('DROP TEMPORARY TABLE IF EXISTS ', @t.temptable.name.TAGS);
		SET @_SQLText = _SQLText;
		CALL _ExecuteCmd(_SQLText, @Error);
	END IF;
	
	
	IF _MODE LIKE 'sqltext.init.by.%' THEN
	/********************************************************************************************************************************
		CALL sys_browsers_tools('sqltext.init.by.system', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('sqltext.init.by.profil', 'X1', '', '', '', '', '', '', '');
	********************************************************************************************************************************/
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_col`; 
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_filters`; 
		
		SET @_All_PrfGUID = '', _PrfGUID_c = '', _PrfGUID_f = '', _PrfGUID_p = '', @_All_PrfGUID = '';
		
		IF _MODE = 'sqltext.init.by.profil' THEN
		
set @.trace.X.1 = '3';	
			CALL _sys_usr_profile_utilities('get.profil.default.COLUMNS', _Id_browser, _PrfGUID_c, @_All_PrfGUID, _User, '', '', '', '', '');
set @.trace.X.1 = '4';	
			CALL _sys_usr_profile_utilities('get.profil.default.FILTERS', _Id_browser, _PrfGUID_f, @_All_PrfGUID, _User, '', '', '', '', '');
			-- synchronizuj kolumny
set @.trace.X.1 = '5';	
			CALL _sys_usr_profile_utilities('profile.syns.with.ALL', _Id_browser, _PrfGUID_c, @_All_PrfGUID, _User, '', '', '', '', '');
			-- synchronizuj filtry
set @.trace.X.1 = '6';	
			CALL _sys_usr_profile_utilities('profile.syns.with.ALL', _Id_browser, _PrfGUID_f, @_All_PrfGUID, _User, '', '', '', '', '');
			/**/
			UPDATE `_sys_usr_profile_cpf` f
			SET
				f.f_UpdateNow = 1
			WHERE
				f.PrfGUID = _PrfGUID_f
			;
			/**/
		ELSE
set @.trace.X.1 = '7';	
			-- md5!!! SET _PrfGUID_c = MD5(CONCAT('COLUMNS', _Id_browser));
			SET _PrfGUID_c = MD5_2('COLUMNS', _Id_browser);
set @.trace.X.1 = '8';	
			-- md5!!! SET _PrfGUID_f = MD5(CONCAT('FILTERS', _Id_browser));
			SET _PrfGUID_f = MD5_2('FILTERS', _Id_browser);
		END IF;
		
			SET @_PrfGUID_c = _PrfGUID_c;
			SET @_PrfGUID_f = _PrfGUID_f;
			
			CREATE TEMPORARY TABLE `tx_sys_browsers_col` 
				SELECT
					c.*,
					_VarInt(IFNULL(c.c_Visible, 0)) AS Visible,
					_VarInt(1) AS Included
				-- FROM `v_sys_usr_profile_columns` c
				FROM `v_sys_profile_browser_columns` c
				WHERE
					c.PrfGUID = _PrfGUID_c
					AND NOT c.Deleted
			;	
			CREATE TEMPORARY TABLE `tx_sys_browsers_filters` 
				SELECT
					f.*,
					_VarInt(IFNULL(f.f_Active, 0)) AS Filter_Active,
					(IFNULL(f.f_sql_Expr, '')) AS Filter_FilterExpr,
					_VarInt(1) AS Included
				-- FROM `v_sys_usr_profile_filters` f
				FROM `v_sys_profile_browser_filters` f
				WHERE
					-- f.Id_browser = _Id_browser
					f.PrfGUID = _PrfGUID_f
					AND NOT f.Deleted
			;	
			
			
		IF _MODE = 'sqltext.init.by.profil' THEN
			UPDATE `tx_sys_browsers_col` c
			SET
				c.Included = 
					(c.c_Visible AND !c.NeverVisible) 
					OR (c.AlwaysIncluded) 
					OR (c.Kind = 'STYLE') 
					OR (c.IsKey) 
					OR (c.IsLocalTime) 
					-- OR (c.Filter_type IN ('WHERE', 'HAVING') AND c.Filter_Active) 
					OR (c.GROUP_BY_Ord > -1)
			;
			UPDATE `tx_sys_browsers_filters` f
			SET
				f.Included = f.Filter_Active
			;
		ELSE
			UPDATE `tx_sys_browsers_col` c
			SET
				c.Included = 1
			;
			UPDATE `tx_sys_browsers_filters` f
			SET
				f.Included = 1
			;
		END IF;
	END IF;	--	_MODE LIKE 'sqltext.init.by.%' 

	IF _MODE LIKE 'sqltext.build.%' THEN
	
	/********************************************************************************************************************************
		CALL sys_browsers_tools('sqltext.build.select', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('sqltext.build.information_schema', 'X1', '', '', '', '', '', '', '');
	********************************************************************************************************************************/
		IF _MODE = 'sqltext.build.information_schema' THEN
			CALL sys_browsers_tools('sqltext.init.by.system', _Id_browser, '', '', '', '', '', '', '');
		ELSE
			CALL sys_browsers_tools('sqltext.init.by.profil', _Id_browser, '', '', '', '', '', '', '');
		END IF;
		--	do @.Prf.GUID wpisywany jest GUID profilu
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect`; 
		CREATE TEMPORARY TABLE `tx_sys_browsers_sect` 
			SELECT
				s.*,
				_VarInt(
					!(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%') 
					OR
					s.AlwaysIncluded
				) AS Included
			FROM `_sys_browsers_sect` s
			WHERE
				s.Id_browser = _Id_browser
				AND NOT s.Deleted
		;	
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect_need`; 
		CREATE TEMPORARY TABLE `tx_sys_browsers_sect_need` (
		  `Source_sect` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
		   PRIMARY KEY (`Source_sect`)
		)
		;
		INSERT IGNORE INTO `tx_sys_browsers_sect_need`
			SELECT
				n.Source_sect
			FROM `tx_sys_browsers_col` c, `_sys_browsers_sect_need` n, `_sys_browsers_sect` s
			WHERE
				c.Included
				AND 
				n.GUID = c.def_c_GUID
				AND
				s.GUID = n.Source_sect
				AND
				NOT s.Deleted
		;	
		UPDATE `tx_sys_browsers_sect` s
		SET
			s.Included = EXISTS(SELECT n.Source_sect FROM `tx_sys_browsers_sect_need` n WHERE s.GUID = n.Source_sect)
		WHERE
			(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%' OR s.Kind LIKE '%from%') 
			AND !s.Included
		;
		INSERT IGNORE INTO `tx_sys_browsers_sect_need`
			SELECT
				n.Source_sect
			FROM `tx_sys_browsers_sect` t, `_sys_browsers_sect_need` n, `_sys_browsers_sect` s
			WHERE
				t.Included
				AND 
				n.GUID = t.GUID
				AND
				s.GUID = n.Source_sect
				AND
				NOT s.Deleted
		;	
		UPDATE `tx_sys_browsers_sect` s
		SET
			s.Included = EXISTS(SELECT n.Source_sect FROM `tx_sys_browsers_sect_need` n WHERE s.GUID = n.Source_sect)
		WHERE
			(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%' OR s.Kind LIKE '%from%') 
			AND !s.Included
		;

--		LEAVE S_sys_browsers_tools;

	--	Inicjalnie	
		SET @sql.text.template = "SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n-- EXT1\n-- EXT2\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n";
		-- SET @sql.text.template = "SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n[FROM]\n[JOIN]\nWHERE[WHERE][GROUP][HAVING][ORDER][LIMIT]\n";
		SELECT
			s.SQL
		INTO
			@sql.text.template
		FROM `_sys_browsers_sql` s
		WHERE
			s.Id_browser = _Id_browser
			AND NOT s.Deleted
			AND s.Kind = 'MAIN'
		LIMIT 1
		;
		
		SET @sql.text = @sql.text.template;
	--	SELECT	
		SELECT 
			IFNULL(GROUP_CONCAT(c.sql_colref_AS ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AS
		INTO
			@.sql.text.SELECT
		FROM `tx_sys_browsers_col` c
		WHERE
			c.Included
		-- JMAM!!! GROUP BY c.Id_browser
		;
set @.trace.X = 'A';
	--	SELECT.Agg
		SELECT 
			IFNULL(GROUP_CONCAT(c.sql_colref_AggFooter ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AggFooter
		INTO
			@.sql.text.SELECT.AGG
		FROM `tx_sys_browsers_col` c
		WHERE
			c.Included
			AND
			c.AggFooterType != 'atNone'
		-- JMAM!!! GROUP BY c.Id_browser
		;

	--	FROM
		SELECT 
			IFNULL(s.sql_Expr, '') AS C_SQLExpr
		INTO
			@.sql.text.FROM
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND s.Kind LIKE '%from%'
		ORDER BY s.LP
		LIMIT 1
		;
		
	--	JOINy
		SELECT 
			IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\n"), '') AS C_SQLExpr
		INTO
			@.sql.text.JOIN
		FROM `tx_sys_browsers_sect` s
		WHERE
			s.Included
			AND (s.Kind LIKE '%left%') OR (s.Kind LIKE '%inner%')
		;
set @.trace.X = 'B';
		SET @sql.text.MAIN = @sql.text.template;
		CALL sys_browsers_tools('SQL.PREPARE.INIT', _Id_browser, '', '', '', 'information_schema', '', '', '');
set @.trace.X = 'B1';
		CALL sys_browsers_tools('SQL.PREPARE.ADDSQL.MAIN', _Id_browser, '', '', '', 'information_schema', '', '', '');
set @.trace.X = 'B2';
		CALL sys_browsers_tools('SQL.PREPARE.PARSE.WHERE.HAVING...', _Id_browser, '', '', '', 'information_schema', '', '', '');
set @.trace.X = 'B3';
		CALL sys_browsers_tools('SQL.PREPARE.GET.MAIN', _Id_browser, '', '', '', 'information_schema', '', '', '');
set @.trace.X = 'B4';
		SET @sql.text.template = @sql.text.MAIN.template;
		
	/*	
	--	WHERE
		SELECT 
			IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\nAND "), '\nTRUE') AS C_SQLExpr
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND (s.Kind LIKE '%where%')
			AND s.Deleted = 0
		INTO 
			@.sql.text.WHERE.S
		;
		SELECT 
			IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR "\nAND "), '') AS C_SQLExpr
		FROM `tx_sys_browsers_filters` f 
		WHERE
			f.Included
			AND f.Kind = 'WHERE' 
			AND f.Filter_Active
		INTO 
			@.sql.text.WHERE.P
		;
		IF _MODE = 'sqltext.build.select' THEN
			SET @.sql.text.WHERE = _ConcatSTR2(@.sql.text.WHERE.S, @.sql.text.WHERE.P, "\nAND ");
		ELSEIF _MODE IN ('sqltext.build.maxtime', 'sqltext.build.key', 'sqltext.build.information_schema') THEN
			SET @.sql.text.WHERE = _ConcatSTR2(@.sql.text.WHERE.S, _Param_A, "\nAND ");
		END IF;
		
	--	HAVING
		SELECT 
			IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR " AND "), '') AS C_SQLExpr
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND (s.Kind LIKE '%having%')
		INTO 
			@.sql.text.HAVING.S
		;
		SELECT 
			IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR " AND "), '') AS C_SQLExpr
		FROM `tx_sys_browsers_filters` f 
		WHERE
			f.Included
			AND f.Kind = 'HAVING' 
			AND f.Filter_Active
		INTO 
			@.sql.text.HAVING.P
		;
		SET @.sql.text.HAVING = _ConcatSTR2(@.sql.text.HAVING.S, @.sql.text.HAVING.P, " AND ");
	*/	
	--	GROUP
		SELECT 
			IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
			INTO
			@.sql.text.GROUP.S
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND (s.Kind LIKE '%GROUP%')
		;
set @.trace.X = 'C1';
		SELECT 
			IFNULL(GROUP_CONCAT(IF(IFNULL(c.GROUP_BY_Expr, '') != '', c.GROUP_BY_Expr, IF(IFNULL(c.col_NameAS, '') != '', c.col_NameAS, IF(IFNULL(c.col_Name, '') != '', c.col_Name, ''))) ORDER BY c.LP SEPARATOR ", "), '') AS C_SQLExpr
			INTO
			@.sql.text.GROUP.P
		FROM `tx_sys_browsers_col` c
		WHERE
			c.Included
			AND c.GROUP_BY_Ord > -1
		;
		SET @.sql.text.GROUP = _ConcatSTR2(@.sql.text.GROUP.S, @.sql.text.GROUP.P, ", ");
		
	--	ORDER
		SELECT 
			IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
			INTO
			@.sql.text.ORDER
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND (s.Kind LIKE '%ORDER%')
		;
		
	--	LIMIT
		SET @.sql.text.LIMIT = '';
		SELECT 
			IFNULL(s.sql_Expr, '') AS C_SQLExpr
		INTO
			@.sql.text.LIMIT
		FROM `_sys_browsers_sect` s
		WHERE
			s.Id_browser = _Id_browser
			AND s.Kind LIKE '%limit%'
		ORDER BY s.LP
		LIMIT 1
		;
set @.trace.X = 'C2';
		SET @.sql.text.LIMIT = UPPER(IF(@.sql.text.LIMIT != '', @.sql.text.LIMIT, IF(Locate('Limit', _Limit) > 0, _Limit, IF(_Limit != '', CONCAT('LIMIT ', _Limit), ''))));
		--	"SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n"
		SET @sql.text.template = REPLACE(@sql.text.template, "[SELECT]", @.sql.text.SELECT);
		SET @sql.text.template = REPLACE(@sql.text.template, "[FROM]", @.sql.text.FROM);
		SET @sql.text.template = REPLACE(@sql.text.template, "[JOIN]", @.sql.text.JOIN);
		SET @sql.text.template = REPLACE(@sql.text.template, "[WHERE]", @.sql.text.WHERE);
		SET @sql.text.template = REPLACE(@sql.text.template, "[HAVING]", IF(@.sql.text.HAVING != '', CONCAT("\nHAVING \n", @.sql.text.HAVING), ''));
		SET @sql.text.template = REPLACE(@sql.text.template, "[GROUP]", IF(@.sql.text.GROUP != '', CONCAT("\nGROUP BY ", @.sql.text.GROUP), ''));
		SET @sql.text.template = REPLACE(@sql.text.template, "[ORDER]", IF(@.sql.text.ORDER != '', CONCAT("\nORDER BY ", @.sql.text.ORDER), ''));

		SET @sql.text.X = @sql.text.template;

		SET @sql.text.template.check.count = @sql.text.template;
		
		IF _MODE = 'sqltext.build.select' THEN
			SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '');
			SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", IF(@.sql.text.LIMIT != '', CONCAT('\n', @.sql.text.LIMIT), ''));
		ELSEIF _MODE IN ('sqltext.build.maxtime', 'sqltext.build.key') THEN
			SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS');
			SET @sql.text.template = REPLACE(@sql.text.template, "-- EXT1", CONCAT(', (', IF(@.sql.text.WHERE.P != '', @.sql.text.WHERE.P, 'TRUE'),') AS REC_OK '));
			SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", '');
		ELSEIF _MODE IN ('sqltext.build.information_schema') THEN
			SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '');
			SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", '');
		END IF;
		SET @sql.text.template.check.count = REPLACE(@sql.text.template.check.count, "[LIMIT]", CONCAT('\nLIMIT ', 0));
		SET @sql.text.template.check.count = REPLACE(@sql.text.template.check.count, "[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS');

		SET @sql.text.MAIN = @sql.text.template;
		
set @.trace.X = 'C3';
-- na razie		CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', _Id_browser, '', 'select', @sql.text.template, '', '', '', '');
set @.trace.X = 'C4';
-- na razie		CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.ANY', _Id_browser, 'check.count', 'select', @sql.text.template.check.count, '', '', '', '');
set @.trace.X = 'C5';
		
		/*
		IF _Param_A != '' THEN
			select @sql.text.template;
		END IF;
		*/
		LEAVE S_sys_browsers_tools;
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect`; 
		DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_col`; 
	END IF;
	

	
	IF _MODE LIKE 'SQL.PREPARE.%' THEN
	
	/********************************************************************************************************************************
		CALL sys_browsers_tools('SQL.PREPARE.INIT', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.INIT', 'X1', '', '', '', 'schema', '', '', '');
		
		CALL sys_browsers_tools('SQL.PREPARE.ADDSQL.MAIN', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.ADDSQL.MAIN', 'X1', '', '', '', 'schema', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.ADDSQL.INIT.FINAL', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.ADDSQL.INIT.FINAL', 'X1', '', '', '', 'schema', '', '', '');

		CALL sys_browsers_tools('SQL.PREPARE.PARSE.WHERE.HAVING...', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.PARSE.WHERE.HAVING...', 'X1', '', '', '', 'schema', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.PARSE.WHERE.???...', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('SQL.PREPARE.PARSE.WHERE.???...', 'X1', '', '', '', 'schema', '', '', '');
		
		CALL sys_browsers_tools('sql.build.select', 'X1', '', '', '', '', '', '', '');
		CALL sys_browsers_tools('sql.build.information_schema', 'X1', '', '', '', '', '', '', '');
		_Param_B 	<> '' to  information_schema !!!!
	********************************************************************************************************************************/
		SET 
		--	Context
			_Param_B = IF(IFNULL(_Param_B, '')  = '', 'select', _Param_B)
		;
		IF _MODE = 'SQL.PREPARE.INIT' THEN
			IF _Param_B = 'information_schema' THEN	--	information_schema
				CALL sys_browsers_tools('sqltext.init.by.system', _Id_browser, '', '', '', '', '', '', '');
			ELSE
				CALL sys_browsers_tools('sqltext.init.by.profil', _Id_browser, '', '', '', '', '', '', '');
			END IF;
			--	do @.Prf.GUID wpisywany jest GUID profilu
			DROP TEMPORARY TABLE IF EXISTS `t_sql.prepare`;
			CREATE TEMPORARY TABLE `t_sql.prepare` (
			  `ID_SECT` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
			  `Kind` VARCHAR(150) NOT NULL DEFAULT '' COMMENT 'Kind z sql',
			  `Context` VARCHAR(150) NOT NULL DEFAULT 'select' COMMENT 'np. information_schema',
			  `_Id_browser` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz browsera',
			  `SQLINIT` MEDIUMTEXT COMMENT 'WHERE',
			  `SQLFINAL` MEDIUMTEXT COMMENT 'WHERE',
			  `WHERE` MEDIUMTEXT COMMENT 'WHERE',
			  `WHERE.P` MEDIUMTEXT COMMENT 'WHERE',
			  `WHERE.S` MEDIUMTEXT COMMENT 'WHERE',
			  `HAVING` MEDIUMTEXT COMMENT 'HAVING',
			  `HAVING.P` MEDIUMTEXT COMMENT 'HAVING',
			  `HAVING.S` MEDIUMTEXT COMMENT 'HAVING',
			  `GROUP` MEDIUMTEXT COMMENT 'GROUP',
			  `GROUP.P` MEDIUMTEXT COMMENT 'GROUP',
			  `GROUP.S` MEDIUMTEXT COMMENT 'GROUP',
			  `ORDER` MEDIUMTEXT COMMENT 'GROUP',
			  `_Param_DEFAULT_WHERE` VARCHAR(150) NOT NULL DEFAULT '',
			  `_Param_A` VARCHAR(150) NOT NULL DEFAULT '',
			  `_Param_B` VARCHAR(150) NOT NULL DEFAULT '',
			  `_Param_C` VARCHAR(150) NOT NULL DEFAULT '',
			  `_Param_D` VARCHAR(150) NOT NULL DEFAULT '',
			  `_Param_E` VARCHAR(150) NOT NULL DEFAULT '',
			  `Is_SQL` BOOLEAN DEFAULT FALSE,
			  `Is_information_schema` BOOLEAN DEFAULT FALSE,
			  PRIMARY KEY (`ID_SECT`)
			);
			
			TRUNCATE `t_sql.prepare`;
		END IF;
		
		IF _MODE LIKE 'SQL.PREPARE.ADDSQL.%' THEN
			
			IF _MODE = 'SQL.PREPARE.ADDSQL.MAIN' THEN
			
			--	dodaj sql-ke np. glowna
				IF IFNULL(@sql.text.MAIN, '')  = '' THEN
					SELECT
						s.SQL
					INTO
						@sql.text.MAIN
					FROM `_sys_browsers_sql` s
					WHERE
						s.Id_browser = _Id_browser
						AND NOT s.Deleted
						AND s.Kind = 'MAIN'
					LIMIT 1
					;
				END IF;
				SET 
					@sql.text.MAIN = 
						IF(IFNULL(@sql.text.MAIN, '')  = '', 
							"SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n-- EXT1\n-- EXT2\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n", 
							@sql.text.MAIN
						)
				;
				
				REPLACE `t_sql.prepare`
				(ID_SECT, Kind, `Context`, _Id_browser, SQLINIT, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E)
					SELECT 
					'MAIN', 'MAIN', _Param_B, _Id_browser, @sql.text.MAIN, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E
				;
			END IF;
			
			IF _MODE = 'SQL.PREPARE.ADDSQL.INIT.FINAL' THEN
				SET @ID_SECT = 0;
				INSERT IGNORE INTO `t_sql.prepare`
				(ID_SECT, Kind, Context, _Id_browser, SQLINIT, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E)
					SELECT 
						-- _VarStr(@ID_SECT := @ID_SECT + 1), 
						s.GUID, s.Kind, _Param_B, _Id_browser, s.SQL, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E
					FROM `_sys_browsers_sql` s
					WHERE
						s.Id_browser = _Id_browser
						AND s.Kind IN ('INIT', 'FINAL')
						AND NOT s.Deleted
				;
			END IF;
			
			UPDATE `t_sql.prepare` t
			SET 
				-- t.Context = _Param_B,
				t.Is_SQL = LOCATE('SELECT', SQLINIT) + LOCATE('CALL', SQLINIT) > 0,
				t.Is_information_schema = (Context = 'information_schema'),
				t.SQLFINAL = t.SQLINIT
			;
			UPDATE `t_sql.prepare` t
			SET 
				_Param_DEFAULT_WHERE = IF(t.Is_information_schema, 'FALSE', t._Param_DEFAULT_WHERE)	--	dla Is_information_schema zawsze 'FALSE'
			;
		END IF;	--	IF _MODE LIKE 'SQL.PREPARE.ADDSQL.%' THEN
		
		IF _MODE = 'SQL.PREPARE.GET.MAIN' THEN
			SET @sql.text.MAIN.template = 
				IFNULL(
				(SELECT t.SQLFINAL FROM `t_sql.prepare` t WHERE t.Kind = 'MAIN' LIMIT 1)
				, @sql.text.MAIN.template
				)
			;
		END IF;
		
		IF _MODE LIKE 'SQL.PREPARE.PARSE.%' THEN
			IF _MODE = 'SQL.PREPARE.PARSE.WHERE.HAVING...' THEN
			--	WHERE	
				UPDATE `t_sql.prepare` t
				SET
					t.`WHERE.S` = (
						SELECT 
							IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\nAND "), '\nTRUE') AS C_SQLExpr
						FROM `_sys_browsers_sect` s
						WHERE
							s.Id_browser = t._Id_browser
							AND (s.Kind LIKE '%where%')
							AND s.Deleted = 0
					)
				WHERE
					t.Is_SQL
				;
				UPDATE `t_sql.prepare` t
				SET
					t.`WHERE.P` = (
						SELECT 
							IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR "\nAND "), '') AS C_SQLExpr
						FROM `tx_sys_browsers_filters` f 
						WHERE
							f.Included
							AND f.Kind = 'WHERE' 
							AND f.Filter_Active
					)
				WHERE
					t.Is_SQL
				;
				UPDATE `t_sql.prepare` t
				SET
					t.`WHERE` = 
						IF(t.Context = 'select',
							_ConcatSTR2(t.`WHERE.S`, t.`WHERE.P`, "\nAND "),
							IF(t.Context IN ('maxtime', 'key', 'information_schema'),
								_ConcatSTR2(t.`WHERE.S`, t._Param_DEFAULT_WHERE, "\nAND "),
								t.`WHERE`
							)
						)
				WHERE
					t.Is_SQL
				;
			--	HAVING
				UPDATE `t_sql.prepare` t
				SET
					t.`HAVING.S` = (
						SELECT 
							IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR " AND "), '') AS C_SQLExpr
						FROM `_sys_browsers_sect` s
						WHERE
							s.Id_browser = t._Id_browser
							AND (s.Kind LIKE '%having%')
							AND s.Deleted = 0
					)
				WHERE
					t.Is_SQL
				;
				UPDATE `t_sql.prepare` t
				SET
					t.`HAVING.P` = (
						SELECT 
							IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR " AND "), '') AS C_SQLExpr
						FROM `tx_sys_browsers_filters` f 
						WHERE
							f.Included
							AND f.Kind = 'HAVING' 
							AND f.Filter_Active
					)
				WHERE
					t.Is_SQL
				;
				UPDATE `t_sql.prepare` t
				SET
					t.`HAVING` = 
							_ConcatSTR2(t.`HAVING.S`, t.`HAVING.P`, " AND ")
				WHERE
					t.Is_SQL
				;

				UPDATE `t_sql.prepare` t
				SET
					t.SQLFINAL = 
						REPLACE(REPLACE(t.SQLFINAL, "[WHERE]", t.`WHERE`), "[HAVING]", IF(t.`HAVING` != '', CONCAT("\nHAVING \n", t.`HAVING`), ''))
				WHERE
					t.Is_SQL
				;
			END IF;
			LEAVE S_sys_browsers_tools;

			
			DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect`; 
			DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_col`; 
		END IF;
	END IF;
	
	IF _MODE = 'Split#.@sql.TEXT' THEN
	/********************************************************************************************************************************
		CALL sys_browsers_tools('Split#.@sql.TEXT', '', '', '', '', '', '');
	********************************************************************************************************************************/
	-- kurcze to dziala wolno
		IF @sql.TEXT = '' THEN
			LEAVE S_sys_browsers_tools;
		END IF;
		SET @sql.out = '';
		SET @sql.Continue = TRUE;
		SET @sql.i = 0;
		WHILE @sql.Continue DO
			SET @sql.P1 = LOCATE('#', @sql.TEXT, 1);
			SET @sql.P2 = LOCATE('#', @sql.TEXT, @sql.P1 + 1);
			SET @sql.Continue = (@sql.P1 != 0) AND (@sql.P2 != 0);
			IF @sql.Continue THEN
				SET @sql.Hash = SUBSTR(@sql.TEXT, @sql.P1 + 1, @sql.P2 - @sql.P1 - 1);
				SET @sql.TEXT = REPLACE(@sql.TEXT, CONCAT('#', @sql.Hash, '#'), '');
				SET @sql.out = CONCAT(@sql.out, ';', @sql.Hash);
			END IF;
			SET @sql.i = @sql.i + 1;
			SET @sql.Continue = @sql.Continue AND @sql.i < 50;
		END WHILE;
		
		select @sql.out, @sql.i;
	END IF;	-- _MODE = 'Split#.@sql.TEXT' 


	
END
$$

DROP PROCEDURE IF EXISTS `_sys_usr_profile_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_usr_profile_tools`(
	IN _MODE VARCHAR(250),
	IN _Key VARCHAR(50),	
	IN _Id_browser VARCHAR(50),	
	IN _User VARCHAR(50),	
	IN _All_PrfGUID VARCHAR(50),
	IN _Param_A VARCHAR(50),		--	 np. SearchText w _MODE = 'SELECT.profiles.FILTERS.get.lookup.search'
	IN _Param_B VARCHAR(50),	
	IN _Param_C VARCHAR(50),	
	IN _Param_D VARCHAR(50),	
	IN _Param_E VARCHAR(50)	
)
/*

*/

S_sys_browsers_tools: BEGIN 

	DECLARE _PrfGUID_x, _PrfGUID_c, _PrfGUID_f, _PrfGUID_p, _PrfGUID_d VARCHAR(38);
	
	DECLARE _sql_text_SELECT MEDIUMTEXT; -- @.sql.text.SELECT
	DECLARE _SQLText, _SQLBuff MEDIUMTEXT;

	CALL _sys_usr_profile_utilities('update.user', '', @empty, @empty, _User, '', '', '', '', '');
	
	SET @_User = _User;
	
	IF _MODE LIKE 'SELECT.profile.COLUMNS.by.GUID' THEN
	/********************************************************************************************************************************
		Podaje kolumny profilu uzytkownika.
		Dla usera 'jmam' i przeglądarki 'x' 
		możesz:
		wołać konkretny profil o GUIDzie = 'Gjmam'
		CALL _sys_usr_profile_tools('SELECT.profile.COLUMNS.by.GUID', 'Gjmam', 'k', 'jmam', '', '', '', '', '', '');

		albo domyślny - wtedy GUID profilu dajesz pusty ale musi być user i ID przeglądarki
		CALL _sys_usr_profile_tools('SELECT.profile.COLUMNS.by.GUID', '', 'k', 'jmam', '', '', '', '', '', '');
		
		
	********************************************************************************************************************************/
		SET _PrfGUID_c = _Key, @_All_PrfGUID = '';
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.COLUMNS', _Id_browser, _PrfGUID_c, @_All_PrfGUID, _User, 'sync', '', '', '', '');
		
		SELECT c.* FROM `v_sys_profile_browser_columns` c WHERE c.PrfGUID = _PrfGUID_c ORDER BY c.LP;
	END IF;	--	_MODE LIKE 'SELECT.profile.COLUMNS.by.GUID	' 

	IF _MODE LIKE 'SELECT.profile.FILTERS.by.GUID' THEN
	/********************************************************************************************************************************
		Podaje pozycje filtrow profilu uzytkowniak.
		Dla usera 'jmam' i przeglądarki 'x' 
		możesz:
		wołać konkretny profil o GUIDzie = 'Gjmam'
		CALL _sys_usr_profile_tools('SELECT.profile.FILTERS.by.GUID', 'Gjmam', 'x', 'jmam', '', '', '', '', '', '');

		albo domyślny - wtedy GUID profilu dajesz pusty ale musi być user i ID przeglądarki
		CALL _sys_usr_profile_tools('SELECT.profile.FILTERS.by.GUID', 'f354e517-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		
	********************************************************************************************************************************/
		SET _PrfGUID_f = _Key, @_All_PrfGUID = '';
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.FILTERS', _Id_browser, _PrfGUID_f, @_All_PrfGUID, _User, 'sync', '', '', '', '');
		
		SELECT * FROM `v_sys_profile_browser_filters` f WHERE f.PrfGUID = _PrfGUID_f;
	END IF;	--	_MODE LIKE 'SELECT.profile.FILTERS.by.GUID' 

	IF _MODE LIKE 'SELECT.profile.FILTERS.v.by.GUID' THEN
	/********************************************************************************************************************************
		Podaje wartosci dla pozycji filtrow z kontenera wartosci (ArrayIN) czyli `_sys_usr_profile_cpf_f_v`.
		wołać konkretny profil o GUIDzie = 'Gjmam'
		CALL _sys_usr_profile_tools('SELECT.profile.FILTERS.v.by.GUID', 'Gjmam', 'x', 'jmam', '', '', '', '', '', '');

		albo domyślny - wtedy GUID profilu dajesz pusty ale musi być user i ID przeglądarki
		CALL _sys_usr_profile_tools('SELECT.profile.FILTERS.v.by.GUID', 'f354e517-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		
	********************************************************************************************************************************/
		SET _PrfGUID_f = _Key, @_All_PrfGUID = '';
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.FILTERS', _Id_browser, _PrfGUID_f, @_All_PrfGUID, _User, 'sync', '', '', '', '');
		
		SELECT 
			f.GUID,
			v.Valuef
		FROM `v_sys_usr_profile_filters` f
		INNER JOIN `_sys_usr_profile_cpf_f_v` v ON v.guidf = f.GUID
		WHERE
			f.PrfGUID = _PrfGUID_f
			AND
			NOT f.Deleted
		;
	END IF;	--	_MODE LIKE 'SELECT.profile.FILTERS.v.by.GUID' 
	
	IF _MODE LIKE 'SELECT.profile.PARAMS.by.GUID' THEN
	/********************************************************************************************************************************
		Podaje pozycje parametrow
		Dla usera 'jmam' i przeglądarki 'x' 
		możesz:
		wołać konkretny profil o GUIDzie = 'Gjmam'
		CALL _sys_usr_profile_tools('SELECT.profile.PARAMS.by.GUID', 'Gjmam', 'x', 'jmam', '', '', '', '', '', '');

		albo domyślny - wtedy GUID profilu dajesz pusty ale musi być user i ID przeglądarki
		CALL _sys_usr_profile_tools('SELECT.profile.PARAMS.by.GUID', 'f354e517-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		
	********************************************************************************************************************************/
		SET _PrfGUID_p = _Key, @_All_PrfGUID = '';
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.PARAMS', _Id_browser, _PrfGUID_p, @_All_PrfGUID, _User, 'sync', '', '', '', '');
		
		SELECT * FROM `v_sys_profile_browser_params` p WHERE p.PrfGUID = _PrfGUID_p;
	END IF;	--	_MODE LIKE 'SELECT.profile.PARAMS.by.GUID' 

	IF _MODE LIKE 'SELECT.profile.CUBE.by.GUID' THEN
	/********************************************************************************************************************************
		Podaje pozycje wymiarów i agregatów profilu uzytkownika.
		Dla usera 'jmam' i przeglądarki 'x' 
		możesz:
		wołać konkretny profil o GUIDzie = 'Gjmam'
		CALL _sys_usr_profile_tools('SELECT.profile.CUBE.by.GUID', 'Gjmam', 'x', 'jmam', '', '', '', '', '', '');

		albo domyślny - wtedy GUID profilu dajesz pusty ale musi być user i ID przeglądarki
		CALL _sys_usr_profile_tools('SELECT.profile.CUBE.by.GUID', 'f354e517-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		
	********************************************************************************************************************************/
		SET _PrfGUID_d = _Key, @_All_PrfGUID = '';
		-- CALL _sys_usr_profile_utilities('get.profil.default.COLUMNS', _Id_browser, _PrfGUID_c, @_All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.CUBE', _Id_browser, _PrfGUID_d, @_All_PrfGUID, _User, 'sync', '', '', '', '');
		
		SELECT * FROM `v_sys_profile_browser_cube` d WHERE d.PrfGUID = _PrfGUID_d;
	END IF;	--	_MODE LIKE 'SELECT.profile.CUBE.by.GUID' 

	
	IF _MODE = 'SELECT.profiles.FILTERS.get.rec' THEN
	/********************************************************************************************************************************
		Zwraca 1 rekord filtra 
		_KEY to GUID konkretnej pozycji filtra
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.rec', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
	********************************************************************************************************************************/
	
		SET @.Prf.f.GUID = _Key;
		SELECT * FROM `v_sys_profile_browser_filters` f WHERE f.GUID = @.Prf.f.GUID;
	END IF;
	
	IF _MODE = 'SELECT.profiles.FILTERS.get.lookup' THEN
	/********************************************************************************************************************************
		Zwraca 1 rekord filtra 
		_KEY to GUID konkretnej pozycji filtra
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
	********************************************************************************************************************************/
		SET @.Prf.f.GUID = _Key;
		SET @.Prf.f.LookUp_SQL = IFNULL(
		(
			SELECT 
				s.SQL AS LookUp_SQL
			FROM `v_sys_profile_browser_filters` f
			-- INNER JOIN `_sys_browsers_col` p ON p.guid = f.ColGUID
			LEFT JOIN `_sys_browsers_sql` s ON s.guid = f.Filter_LookUp_SQL_GUID
			WHERE
				f.GUID = @.Prf.f.GUID
				AND
				NOT f.Deleted
		), '')
		;
		IF @.Prf.f.LookUp_SQL != '' THEN
			SET _SQLText = @.Prf.f.LookUp_SQL;
			
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
			SELECT '' AS GUID, '' AS X;
		END IF;
	END IF;
	
	IF _MODE = 'SELECT.profiles.FILTERS.get.lookup.search' THEN
	/********************************************************************************************************************************
		Zwraca 1 rekord filtra 
		_KEY to GUID konkretnej pozycji filtra
		_Param_A	szukany tekst
		_Param_B	Klucz
		_Param_C	dodatkowy parametr (_ExtParam w erp_do_search_similar())
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.search', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', 'szukaj', 'Klucz', 'Param', '', '');
		
	********************************************************************************************************************************/
		SET @.Prf.f.GUID = _Key;
		SET @.Prf.f.LookUp_SQL = '';
		SET @.Prf.f.SQL_IsSimilarSearch = 0;
		
		SELECT 
			s.SQL AS LookUp_SQL, s.SQL_IsSimilarSearch
		INTO
			@.Prf.f.LookUp_SQL, @.Prf.f.SQL_IsSimilarSearch
		FROM `v_sys_profile_browser_filters` f
		LEFT JOIN `_sys_browsers_sql` s ON s.guid = f.Filter_LookUp_SQL_GUID
		-- FROM `v_sys_usr_profile_filters` f
		-- bylo INNER JOIN `_sys_browsers_p` p ON p.guid = f.ColGUID
		-- INNER JOIN `_sys_browsers_col` p ON p.guid = f.ColGUID
		-- LEFT JOIN `_sys_browsers_sql` s ON s.guid = p.Filter_LookUp_SQL_GUID
		WHERE
			f.GUID = @.Prf.f.GUID
			AND
			NOT f.Deleted
		;
		IF @.Prf.f.LookUp_SQL != '' AND @.Prf.f.SQL_IsSimilarSearch AND IFNULL(_Param_A, '') != '' THEN
			SET _SQLText = REPLACE(@.Prf.f.LookUp_SQL, '%s', _Param_A);
			SET _SQLText = REPLACE(_SQLText, '%Key', IFNULL(_Param_B, ''));
			SET _SQLText = REPLACE(_SQLText, '%p', IFNULL(_Param_C, ''));

			
			SET @_SQLText = _SQLText;
			SET @_Param_B = _Param_B;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
			SELECT '' AS GUID, '' AS X;
		END IF;
	END IF;
	
	IF _MODE LIKE 'SELECT.profiles.FILTERS.get.lookup.DisplayValues.%' THEN
	/********************************************************************************************************************************
		Zwraca HRV Human readable values dla danej pozycji filtra
		_KEY to GUID konkretnej pozycji filtra
		
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.DOWN', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.UP', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
	********************************************************************************************************************************/
		SET @.Prf.f.GUID = _Key;
		SELECT 
			f.f_Flag, f.f_Value_Down, f.f_Value_Up
		INTO
			@.Prf.f.Flag, @.Prf.f.Value_Down, @.Prf.f.Value_Up
  FROM `v_sys_profile_browser_filters` f
		WHERE 
			f.GUID = @.Prf.f.GUID
		;
		IF _MODE = 'SELECT.profiles.FILTERS.get.lookup.DisplayValues.UP' AND @.Prf.f.Flag != 'ffBetween' THEN
		--	WYCHODZIMY
			SELECT "" AS "";
			LEAVE S_sys_browsers_tools;
		END IF;
		
		IF @.Prf.f.Flag = 'ffIN' THEN
			SET _SQLBuff = IFNULL(
				(
					SELECT GROUP_CONCAT(QUOTE(v.Valuef) SEPARATOR ', ') FROM `_sys_usr_profile_cpf_f_v` v WHERE v.GUIDf = @.Prf.f.GUID
				), '')
			;
		ELSE
			SET _SQLBuff = IF(_MODE = 'SELECT.profiles.FILTERS.get.lookup.DisplayValues.DOWN',
				QUOTE(@.Prf.f.Value_Down),
				QUOTE(@.Prf.f.Value_Up)
				)
			;
		END IF;
		
		SET @_SQLBuff = _SQLBuff;
		SELECT
			IFNULL(s.SQL_ResultSQL, ''), IFNULL(s.SQL_KeyFieldName, ''), IFNULL(s.SQL_ResultFieldNames, '')
		INTO
			@.Prf.s.SQL_ResultSQL, @.Prf.s.SQL_KeyFieldName, @.Prf.s.SQL_ResultFieldNames
		FROM `v_sys_profile_browser_filters` f
		-- bylo INNER JOIN `_sys_browsers_p` p ON p.guid = f.ColGUID
		-- INNER JOIN `_sys_browsers_col` p ON p.guid = f.ColGUID
		LEFT JOIN `_sys_browsers_sql` s ON s.guid = f.Filter_LookUp_SQL_GUID
		WHERE
			f.GUID = @.Prf.f.GUID
			AND
			NOT f.Deleted
		LIMIT 1
		;
		
		IF @.Prf.s.SQL_ResultSQL != '' THEN
			SET _SQLText = REPLACE(@.Prf.s.SQL_ResultSQL, '%s', _SQLBuff);
			
			SET @_SQLText = _SQLText;
			CALL _ExecuteCmd(_SQLText, @Error);
		ELSE
			SELECT '' AS GUID, '' AS X;
		END IF;
	END IF;	--	_MODE = 'SELECT.profiles.FILTERS.get.f_v.str' 
	
	IF _MODE LIKE 'SELECT.profiles.%.by.user' THEN
	/********************************************************************************************************************************
		CALL _sys_usr_profile_tools('SELECT.profiles.columns.by.user', '', 'x6','', '', '', '','','','');
		CALL _sys_usr_profile_tools('SELECT.profiles.filters.by.user', '', 'x6','', '', '', '','','','');
		CALL _sys_usr_profile_tools('SELECT.profiles.params.by.user', '', 'x6','', '', '', '','','','');
		CALL _sys_usr_profile_tools('SELECT.profiles.cube.by.user', '', 'x6','', '', '', '','','','');		
	********************************************************************************************************************************/
		SET @_All_PrfGUID = '', _PrfGUID_c = '', _PrfGUID_f = '', _PrfGUID_p = '', @_All_PrfGUID = '';
		
		IF _MODE = 'SELECT.profiles.COLUMNS.by.user' THEN
			CALL _sys_usr_profile_utilities('get.profil.default.COLUMNS', _Id_browser, _PrfGUID_c, @_All_PrfGUID, _User, '', '', '', '', '');
		ELSEIF _MODE = 'SELECT.profiles.FILTERS.by.user' THEN
			CALL _sys_usr_profile_utilities('get.profil.default.FILTERS', _Id_browser, _PrfGUID_f, @_All_PrfGUID, _User, '', '', '', '', '');
		ELSEIF _MODE = 'SELECT.profiles.PARAMS.by.user' THEN
			CALL _sys_usr_profile_utilities('get.profil.default.PARAMS', _Id_browser, _PrfGUID_p, @_All_PrfGUID, _User, '', '', '', '', '');
		ELSE
			CALL _sys_usr_profile_utilities('get.profil.default.CUBE', _Id_browser, _PrfGUID_d, @_All_PrfGUID, _User, '', '', '', '', '');
		END IF;
		
	--	UWAGA 2021-10-11 !!!!!!!!!!!!!!!!!!!!! 
	--	tymczasowo dla BALTIMY i bazy httest p.Mielewski Karol dostaje możliwośc usuwanie nie soich profili
	--	docelowo musi byc upr lbo admin????
		SET @.prf.Is.removable = FALSE OR (_User = '634f5499-dbb7-11ea-9e19-d4ae52cb9337*' AND SCHEMA() = 'httest');
		SELECT
			-- md5!!! (@.prf.DefaultPrf := (_VarStr(p.GUID) = MD5(CONCAT(p.Typ, p.Re_Id)))) AS DefaultPrf,
			(@.prf.DefaultPrf := (_VarStr(p.GUID) = MD5_2(p.Typ, p.Re_Id))) AS DefaultPrf,
			(SELECT COUNT(*) FROM `_sys_usr_profile_cpf` cpf WHERE cpf.PrfGUID = p.GUID) AS Ile_elem,
			(p.OwnerGUID = _User) AS IsProfilUsera,
			(p.GUID <=> 
				(SELECT p2.GUID FROM `_sys_usr_profile` p2 WHERE p2.Re_Id = p.Re_Id AND p2.OwnerGUID = p.OwnerGUID AND p2.Typ = p.Typ AND p2.deleted = 0 ORDER BY p2.LastUsedAt DESC LIMIT 1)
					
			) AS IsProfilAktualny,
			(NOT @.prf.DefaultPrf AND ((p.OwnerGUID = _User) OR @.prf.Is.removable)) AS IsRemovable,
			p.*,
			o.idnuser,concat(o.imie1, ' ',o.nazwisko) as imie_nazwisko
		FROM `_sys_usr_profile` p
		INNER JOIN osoby o ON o.guid = p.OwnerGUID
		WHERE
			TRUE
			AND p.Re_Id = _Id_browser
			AND p.deleted = 0
			AND (_Param_E='ALL' OR p.OwnerGUID = _User)
			-- AND p.Typ = IF(_MODE = 'SELECT.profiles.c.by.user', 'COLUMNS', 'FILTERS')
			AND p.Typ = 
				REPLACE(REPLACE(_MODE, 'SELECT.profiles.', ''), '.by.user', '')
			/*
				IF(_MODE = 'SELECT.profiles.c.by.user', 
					'COLUMNS', 
					IF(_MODE = 'SELECT.profiles.f.by.user', 
						'FILTERS',
						IF(_MODE = 'SELECT.profiles.p.by.user', 
							'PARAMS',
							'CUBE'
						)
					)
				)
			*/	
		;
	END IF;	--	_MODE LIKE 'SELECT.profiles.%.by.user' 

	
	IF _MODE LIKE 'SELECT.profiles.styles' THEN
	/********************************************************************************************************************************
		CALL _sys_usr_profile_tools('SELECT.profiles.styles', '', '', '', '', '', '', '', '', '');
		
	********************************************************************************************************************************/
		SELECT 
				s.*
			FROM `_sys_usr_profile` p
			INNER JOIN `_sys_usr_profile_styles` s ON s.PrfGUID = p.GUID
			WHERE
				p.GUID = 'Style' AND 
				p.OwnerGUID = 'ALL'
		;
	END IF;	--	_MODE LIKE 'SELECT.profiles.%.by.user' 

	IF _MODE = 'profil.Prepare.ParamValues' THEN
	/********************************************************************************************************************************
		Ustawia wartosci parametrow ktore nie sa edytowane lub Fixed.
		CALL _sys_usr_profile_tools('profil.Prepare.ParamValues', '', 'X1', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('profil.Prepare.ParamValues', @.Prf.GUID, '', '', '', '', '', '', '', '');
PO CO ?????????????????????????????????????????????????????????		
	********************************************************************************************************************************/
		SET _PrfGUID_p = _Key, @_All_PrfGUID = '';
		CALL _sys_usr_profile_utilities('get.profil.default.PARAMS', _Id_browser, _PrfGUID_p, @_All_PrfGUID, _User, '', '', '', '', '');
		
		-- TUTAJ Parametry zczytywać będziemy w petli LOOP
		CREATE TEMPORARY TABLE `t_params`
			SELECT
				pf.GUID,
				pf.Par_Name, 
				pf.Value_Down, 
				pf.Empty_value_type, 
				pf.Param_Init_Type, 
				pf.Param_Init_SQL_GUID
			FROM `v_sys_profile_browser_filters` pf
			WHERE
				pf.is_Param
		;
		
	END IF;	--	_MODE = 'profil.Prepare.ParamValues' 
	
	IF _MODE = 'profile.load.from' THEN
	/********************************************************************************************************************************
		pobieranie z innego profilu
		CALL _sys_usr_profile_tools('profile.load.from', '', 'k', '', '', 'SrcGUID', '', '', '', '');
		CALL _sys_usr_profile_tools('profile.load.from', 'KeyProfil', 'k', '', '', 'SrcGUID', '', '', '', '');
		w _Key GUID profilu na ktĂłry stoimy a w 
		w _Param_A zrodlowy profil
	********************************************************************************************************************************/
		SET _All_PrfGUID = NULL;
		CALL _sys_usr_profile_utilities('profile.load.from', _Id_browser, _Key, _All_PrfGUID, _User, _Param_A, '', '', '', '');
	END IF;	--	_MODE LIKE 'profile.load.from' 

	IF _MODE = 'profile.load.from.ALL' THEN
	/********************************************************************************************************************************
		Pobieranie pozycji z profilu ALL - czyli przywroc ustawienia fabryczne  (_Param_B = '')
		LUB
		pobieranie z ALL brakującychy (_Param_B <> '')
		CALL _sys_usr_profile_tools('profile.load.from.ALL', 'KeyProfilu', 'x6', '', '', '', '', '', '', '');
		w _Key GUID profilu do ktorego kopiujemy z ALL - MUSI ISTNIEC!!!!
	********************************************************************************************************************************/
		SET
			_All_PrfGUID = ''		--	Zrodlowy profil
		;
		CALL _sys_usr_profile_utilities('profile.load.from.ALL', _Id_browser, _Key, _All_PrfGUID, _User, '', '', '', '', '');
	END IF;	--	_MODE = 'profile.load.from.ALL' 

	
	IF _MODE LIKE 'profile.save.as%' THEN
	/********************************************************************************************************************************
		Zapisz pod inna nazwa
		CALL _sys_usr_profile_tools('profile.save.as', '', 'k', '', '', 'Nowa nazwa', '', '', '', '');
		CALL _sys_usr_profile_tools('profile.save.as', 'KeyProfil', 'k', '', '', 'Nowa nazwa', '', '', '', '');
		w _Key GUID profilu który zachowujemy jako... (czasem jest to profill ALL)
		w _Param_A Nazwa nowego profilu pod jaka zapisujemy profil _Key
		w _User zazwyczaj "" ALE czasem gdy kopiujemy profill ALL na profil usera - to mamy tu uzytkownika (usera)
	********************************************************************************************************************************/
		SET 
			_PrfGUID_x = NULL,
			@._sys_usr_profile_tools.src._Key = _Key,
			@._sys_usr_profile_tools.new.Name = _Param_A,
			@._sys_usr_profile_tools.Status = 0,
			@._sys_usr_profile_tools.Msg = ''
		;
				--	SET @._sys_usr_profile_tools.src._Key = _Key;
				--	SET @._sys_usr_profile_tools.new.Name = _Param_A;
	--	Najpierw test na duplikat klucza Re_Id_Typ_OwnerGUID		
		SET @._sys_usr_profile_tools.src.EXISTS = EXISTS(
		SELECT 
			d.GUID 
		FROM `_sys_usr_profile` s,  `_sys_usr_profile` d
		WHERE 
			s.GUID = @._sys_usr_profile_tools.src._Key
			AND d.Re_Id = s.Re_Id
			AND d.Typ = s.typ
			AND d.OwnerGUID = s.OwnerGUID
			AND d.PrfName = @._sys_usr_profile_tools.new.Name
		)
		;
		--	SELECT @._sys_usr_profile_tools.src.EXISTS;
		IF NOT @._sys_usr_profile_tools.src.EXISTS THEN
		--	Zapisujemy gdy nie istnieje
			CALL _sys_usr_profile_utilities('profile.save.as', _Id_browser, _PrfGUID_x, _All_PrfGUID, _User, 
				@._sys_usr_profile_tools.src._Key, @._sys_usr_profile_tools.new.Name, '', '', '');
		ELSE
		--	Istnieje pod taką nazwą..wypad
			SET 
				@._sys_usr_profile_tools.Status = 1,
				@._sys_usr_profile_tools.Msg = 'Istnieje już profil o takiej nazwie!'
			;
		END IF;
		SELECT
			@._sys_usr_profile_tools.Status AS Status,
			@._sys_usr_profile_tools.Msg AS Msg,
			_PrfGUID_x AS GUID
		;
	END IF;	--	_MODE LIKE 'profile.save.as' 
	
	
	IF _MODE LIKE 'profile.Delete%' THEN
	/********************************************************************************************************************************
		Usuwanie profilu - ng + detale
		CALL _sys_usr_profile_tools('profile.Delete', 'KeyProfil', '', '', '', '', '', '', '', '');
		w _Key GUID profilu który usuwamy
		_User
	********************************************************************************************************************************/
	--	UWAGA 2021-10-11 !!!!!!!!!!!!!!!!!!!!! 
	--	tymczasowo dla BALTIMY i bazy httest p.Mielewski Karol dostaje możliwośc usuwanie nie soich profili
	--	docelowo musi byc upr lbo admin????
		SET @.prf.Is.removable = FALSE OR (_User = '634f5499-dbb7-11ea-9e19-d4ae52cb9337*' AND SCHEMA() = 'httest');
		UPDATE `_sys_usr_profile` p, `_sys_usr_profile_cpf` cpf
		SET
			p.Deleted = 1,
			cpf.Deleted = 1
		WHERE
			p.GUID = _Key
			-- md5!!! AND (p.GUID != MD5(CONCAT(p.Typ, p.Re_Id)))
			AND (p.GUID != MD5_2(p.Typ, p.Re_Id))
			AND 
			cpf.PrfGUID = p.GUID
			-- AND
			-- IF(IFNULL(_User, '') <> '', p.OwnerGUID = _User, TRUE)
			AND 
			((p.OwnerGUID = IFNULL(_User, '')) OR @.prf.Is.removable)
		;
		DELETE p FROM `_sys_usr_profile` p
		WHERE
			p.GUID = _Key
			AND p.Deleted = 1
		;
		IF ROW_COUNT() > 0 THEN
			SELECT 'OK' AS Status, '' AS Msg;
		ELSE
			SELECT 'Err' AS Status, 'Operacja nie powiodła się!' AS Msg;
		END IF;
	END IF;
END
$$

-- DROP PROCEDURE IF EXISTS `sys_browsers_SQD_tools`$$
DROP PROCEDURE IF EXISTS `sys_browsers_Edit_tools`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sys_browsers_Edit_tools`(
	IN _MODE VARCHAR(250),
	IN _Id_browser VARCHAR(50),		--	Klucz browsera
	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)	
)
/*
	Przyklad wywol.
	
	CALL sys_browsers_Edit_tools('import.SQD.init', 'X1', '', '', '', '', '');
	CALL sys_browsers_Edit_tools('import.SQD.do.insert', 'X1', '', '', '', '', '');
	CALL sys_browsers_Edit_tools('import.SQD.close', 'X1', '', '', '', '', '');
				

*/

S_sys_browsers_Edit_tools: BEGIN 

	IF _MODE IN ('Edit.SQL.Init', 'Edit.SQL.Clear') THEN
	/********************************************************************************************************************************
		Czysci tabele wymiany
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('Edit.SQL.Init', 'X1', '', '', '', '', '');
	********************************************************************************************************************************/
		TRUNCATE `t_sys_browsers_sect`;
		TRUNCATE `t_sys_browsers_col`;
		TRUNCATE `t_sys_browsers_filters`;
		TRUNCATE `t_sys_browsers_params`;
	END IF;	--	_MODE IN ('import.SQD.close', 'import.SQD.drop.temp')

	IF _MODE = 'Edit.SQL.rebuild.sec.col' THEN
	/********************************************************************************************************************************
		Zapisuje to co wynika z SQL-ki (sekcje, kolumny) 
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('Edit.SQL.rebuild.sec.col', _Id_browser, '', '', '', '', '');
	********************************************************************************************************************************/
		UPDATE `_sys_browsers_sect` SET deleted = 1 WHERE Id_browser = _Id_browser;
		INSERT INTO `_sys_browsers_sect` 
		(`GUID`,`Id_browser`, `LP`, `Kind`, `sect_Need_Alias`, `Sect_BaseName`, `sect_TableName`, `sect_AliasName`, `sect_expr`) 
		SELECT
			GUID, Id_browser, LP, Kind, sect_Need_Alias, Sect_BaseName, sect_TableName, sect_AliasName, sect_expr
		FROM `t_sys_browsers_sect` t
		ORDER BY t.LP
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = t.GUID,
			`Id_browser` = t.Id_browser, 
			`LP` = t.LP, 
			`Kind` = t.Kind, 
			`sect_Need_Alias` = t.sect_Need_Alias,
			`sect_BaseName` = t.Sect_BaseName,
			`sect_TableName` = t.sect_TableName,
			`sect_AliasName` = t.sect_AliasName,
			`sect_expr` = t.sect_expr
		;
	
		UPDATE `_sys_browsers_col` SET deleted = 1 WHERE Id_browser = _Id_browser;
		
		INSERT IGNORE INTO `_sys_browsers_col` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `col_Need_Alias`, `col_Expr`, `col_Alias`, `col_Name`, `col_NameAS`, `Content_Src`) 
		-- (`GUID`, `Id_browser`, `Kind`, `LP`, `col_Name`, `col_NameAS`, `Editable`, `Comment`, `IsKey`, `AlwaysIncluded`, `Content_Src`) 
		SELECT
			c.GUID, c.Id_browser, c.Kind, c.LP, c.col_Need_Alias, c.col_Expr, c.col_Alias, c.col_Name, c.col_NameAS, 'SQL'
			-- c.GUID, c.Id_browser, c.Kind, c.LP, c.col_Name, c.col_NameAS, c.Editable, c.Comment, c.IsKey, c.AlwaysIncluded, 'SQL'
		FROM `t_sys_browsers_col` c
		ORDER BY c.LP
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = c.GUID,
			`Id_browser` = c.Id_browser, 
			`LP` = c.LP, 
			`col_Need_Alias` = c.col_Need_Alias,
			`col_Expr` = c.col_Expr,
			`col_Alias` = c.col_Alias,
			`col_Name` = c.col_Name, 
			`col_NameAS` = c.col_NameAS,
			`_sys_browsers_col`.`Content_Src` = CONCAT('SQL,', `_sys_browsers_col`.`Content_Src`)
		;
	
		CALL sys_browsers_Edit_tools('Edit.SQL.Refresh', _Id_browser, '', '', '', '', '');
	END IF;	--	_MODE = 'Edit.SQL.After' 
	


	IF _MODE = 'INIT.t_sys_XXXXXXXXXX' THEN
		CREATE TABLE `t_sys_FilterConteners` (
		  `GUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
		  `Id_browser` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'ID z `_sys_browsers_n` ale nie koniecznie',
		  `LP` INT(11) NOT NULL DEFAULT '0',
		  `Active` INT(11) NOT NULL DEFAULT '0',
		  `Name` VARCHAR(250) NOT NULL DEFAULT '',
		  `ValueAArrayStrIN` VARCHAR(250) NOT NULL DEFAULT '',
		  `ValueDown` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': Variant read GetDown write SetDown stored IsDownValueStored;',
		  `ValueUp` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': Variant read GetUp write SetUp stored IsUpValueStored;',
		  `AvaibleFlags` VARCHAR(250) NOT NULL DEFAULT 'ffEqu' COMMENT ': TSetFilterFlag read FAvaibleFlags write SetAvaibleFlags default CInitialAvaibleFlags;',
		  `FieldName` VARCHAR(250) NOT NULL DEFAULT '',
		  `DisplayLabel` VARCHAR(250) NOT NULL DEFAULT '',
		  `AliasName` VARCHAR(250) NOT NULL DEFAULT '',
		  `LookUpFieldName` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FLookUpFieldName write FLookUpFieldName;',
		  `LookUpResultFieldName` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FLookUpResultFieldName write FLookUpResultFieldName;',
		  `LookUpSQL` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read GetLookUpSQL write SetLookUpSQL;',
		  `SQLLookUp` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': TStrings read GetSQL write SetSQL;',
		  `SubSelectSQL` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FSubSelectSQL write SetSubSelectSQL;',
		  `Flag` VARCHAR(250) NOT NULL DEFAULT 'ffEqu' COMMENT ': TFilterFlag read FFlag write FFlag default ffEqu;',
		  `Neg` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FNeg write FNeg default False;',
		  `LookUpEdited` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read GetLookUpEdited write FLookUpEdited default False;',
		  `Visible` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read GetVisible write FVisible default True;',
		  `CaseSensitive` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FCaseSensitive write FCaseSensitive default False;',
		  `FieldType` VARCHAR(250) NOT NULL DEFAULT 'ftString' COMMENT ': TFieldType read FFieldType write SetFieldType default ftString;',
		  `KindFilter` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': TKindFilter read FKindFilter write SetKindFilter default kfSQL;',
		  `UseCustomSettings` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FUseCustomSettings write FUseCustomSettings default False;',
		  `ValueArrayIN` MEDIUMTEXT NOT NULL COMMENT ': TArrayIN read GetArrayIN write SetArrayIN;',
		  `IsTab_String` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean  read FIsTab_String write FIsTab_String default false;',
		  `LookUpDropDownWidth` INT(11) NOT NULL DEFAULT '0' COMMENT ': Integer read FLookUpDropDownWidth write FLookUpDropDownWidth default 200;',
		  `IdnCechyDef` INT(11) NOT NULL DEFAULT '0' COMMENT ': Integer read FLookUpDropDownWidth write FLookUpDropDownWidth stored False;',
		  `NestedFilters` MEDIUMTEXT NOT NULL COMMENT ': TFilterCollection read FNestedFilters write FNestedFilters;',
		  `ExtraAndStatement` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FExtraAndStatement write FExtraAndStatement;',
		  `NestedOrAnd` VARCHAR(250) NOT NULL DEFAULT 'oaAnd' COMMENT ': TOrAnd read FNestedOrAnd write FNestedOrAnd default oaAnd;',
		  PRIMARY KEY (`GUID`),
		  UNIQUE KEY `Id_browser_FieldName` (`Id_browser`,`FieldName`, `Name`)
		) ENGINE=MYISAM DEFAULT CHARSET=cp1250  
		;
		CREATE TABLE `t_ParamConteners` LIKE `t_sys_FilterConteners`;
		CREATE TABLE `t_sys_browsers_sect` LIKE `_sys_browsers_sect`;
		CREATE TABLE `t_sys_browsers_col` LIKE `_sys_browsers_col`;
		CREATE TABLE `t_sys_browsers_filters` LIKE `_sys_browsers_filters`;
		CREATE TABLE `t_sys_browsers_params` LIKE `_sys_browsers_params`;
	END IF;	--	_MODE = 'INIT.t_sys_XXXXXXXXXX' 
	
	
	IF _MODE IN ('import.SQD.close', 'import.SQD.drop.temp') THEN
	/********************************************************************************************************************************
		Usuwa tabele tymczasowe
		w _Id_browser GUID Browsera
	********************************************************************************************************************************/
		CALL sys_browsers_Edit_tools('Edit.SQL.Clear', _Id_browser, '', '', '', '', '');
		/*
		-- DROP TEMPORARY TABLE IF EXISTS `t_sys_FieldDefsCollection`;
		DROP TABLE IF EXISTS `t_sys_FieldDefsCollection`;
		-- DROP TEMPORARY TABLE IF EXISTS `t_sys_FilterConteners`;
		DROP TABLE IF EXISTS `t_sys_FilterConteners`;
		DROP TABLE IF EXISTS `t_sys_browsers_sect`;
		DROP TABLE IF EXISTS `t_sys_browsers_col`;
		*/
		TRUNCATE `t_sys_FieldDefsCollection`;
		TRUNCATE `t_sys_FilterConteners`;
	END IF;	--	_MODE IN ('import.SQD.close', 'import.SQD.drop.temp')
	
	IF _MODE = 'import.SQD.init' THEN
	/********************************************************************************************************************************
		Usuwa tabele tymczasowe
		w _Id_browser GUID Browsera
	********************************************************************************************************************************/
		CALL sys_browsers_Edit_tools('import.SQD.drop.temp', 'X', '', '', '', '', '');
		/*
		-- CREATE TEMPORARY TABLE `t_sys_FieldDefsCollection` (
		CREATE TABLE `t_sys_FieldDefsCollection` (
		  `GUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
		  `Id_browser` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'ID z `_sys_browsers_n` ale nie koniecznie',
		  `DataType` VARCHAR(250) NOT NULL DEFAULT 'ftString' COMMENT ': TFieldType read FFieldType write SetFieldType default ftString;',
		  `FieldName` VARCHAR(200) NOT NULL DEFAULT '',
		  `FieldIndex` INT(11) NOT NULL DEFAULT '1048',
		  `Alignment` VARCHAR(200) NOT NULL DEFAULT '',
		  `DisplayLabel` VARCHAR(200) NOT NULL DEFAULT '',
		  `DisplayFormat` VARCHAR(200) NOT NULL DEFAULT '',
		  `DisplayWidth` INT(11) NOT NULL DEFAULT '0',
		  `Size` INT(11) NOT NULL DEFAULT '0',
		  `ReadOnly` INT(11) NOT NULL DEFAULT '0',
		  `Visible` INT(11) NOT NULL DEFAULT '1',
		  `Tag` INT(11) NOT NULL DEFAULT '0',
		  `Descr` VARCHAR(200) NOT NULL DEFAULT '',
		  `EditMask` VARCHAR(200) NOT NULL DEFAULT '',
		  `AutoGenerateValue` VARCHAR(200) NOT NULL DEFAULT 'arNone',
		  `CustomConstraint` VARCHAR(200) NOT NULL DEFAULT '',
		  `ConstraintErrorMessage` VARCHAR(200) NOT NULL DEFAULT '',
		  `DefaultExpression` VARCHAR(200) NOT NULL DEFAULT '',
		  `FieldKind` VARCHAR(200) NOT NULL DEFAULT '',
		  `ImportedConstraint` VARCHAR(200) NOT NULL DEFAULT '',
		  `ListSource` VARCHAR(200) NOT NULL DEFAULT '',
		  `LookupDataSet` VARCHAR(200) NOT NULL DEFAULT '',
		  `LookupKeyFields` VARCHAR(200) NOT NULL DEFAULT '',
		  `LookupResultField` VARCHAR(200) NOT NULL DEFAULT '',
		  `KeyFields` VARCHAR(200) NOT NULL DEFAULT '',
		  `LookupCache` INT(11) NOT NULL DEFAULT '0',
		  `Origin` VARCHAR(200) NOT NULL DEFAULT '',
		  `ProviderFlags` VARCHAR(200) NOT NULL DEFAULT '[pfInWhere, pfInUpdate]',
		  `Required` INT(11) NOT NULL DEFAULT '0',
		  `ExtOptions` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'TFieldDefsOptions read GetExtOptions write SetExtOptions',
		  `EditorOptions` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'TFieldDefsEditorOptions read GetEditorOptions write SetEditorOptions',
		  `SummaryOptions` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'TFieldDefsSummaryOptions read GetSummaryOptions write SetSummaryOptions',
		  `TimeOptions` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'TTimeFieldController read GetTimeOptions write SetTimeOptions',
		  `NumericCalculator` VARCHAR(250) NOT NULL DEFAULT '' COMMENT 'TNumericFieldCalculator read GetNumericCalculator write SetNumericCalculator',
		  `Version` VARCHAR(250) NOT NULL DEFAULT '',
		  `CheckUpr` INT(11) NOT NULL DEFAULT '0',
		  PRIMARY KEY (`GUID`),
		  UNIQUE KEY `Id_browser_FieldName` (`Id_browser`,`FieldName`)
		) ENGINE=MYISAM DEFAULT CHARSET=cp1250  
		;
		
		-- CREATE TEMPORARY TABLE `t_sys_FilterConteners` (
		CREATE TABLE `t_sys_FilterConteners` (
		  `GUID` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
		  `Id_browser` VARCHAR(200) NOT NULL DEFAULT '' COMMENT 'ID z `_sys_browsers_n` ale nie koniecznie',
		  `LP` INT(11) NOT NULL DEFAULT '0',
		  `Active` INT(11) NOT NULL DEFAULT '0',
		  `Name` VARCHAR(250) NOT NULL DEFAULT '',
		  `ValueAArrayStrIN` VARCHAR(250) NOT NULL DEFAULT '',
		  `ValueDown` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': Variant read GetDown write SetDown stored IsDownValueStored;',
		  `ValueUp` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': Variant read GetUp write SetUp stored IsUpValueStored;',
		  `AvaibleFlags` VARCHAR(250) NOT NULL DEFAULT 'ffEqu' COMMENT ': TSetFilterFlag read FAvaibleFlags write SetAvaibleFlags default CInitialAvaibleFlags;',
		  `FieldName` VARCHAR(250) NOT NULL DEFAULT '',
		  `DisplayLabel` VARCHAR(250) NOT NULL DEFAULT '',
		  `AliasName` VARCHAR(250) NOT NULL DEFAULT '',
		  `LookUpFieldName` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FLookUpFieldName write FLookUpFieldName;',
		  `LookUpResultFieldName` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FLookUpResultFieldName write FLookUpResultFieldName;',
		  `LookUpSQL` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read GetLookUpSQL write SetLookUpSQL;',
		  `SQLLookUp` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': TStrings read GetSQL write SetSQL;',
		  `SubSelectSQL` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FSubSelectSQL write SetSubSelectSQL;',
		  `Flag` VARCHAR(250) NOT NULL DEFAULT 'ffEqu' COMMENT ': TFilterFlag read FFlag write FFlag default ffEqu;',
		  `Neg` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FNeg write FNeg default False;',
		  `LookUpEdited` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read GetLookUpEdited write FLookUpEdited default False;',
		  `Visible` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read GetVisible write FVisible default True;',
		  `CaseSensitive` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FCaseSensitive write FCaseSensitive default False;',
		  `FieldType` VARCHAR(250) NOT NULL DEFAULT 'ftString' COMMENT ': TFieldType read FFieldType write SetFieldType default ftString;',
		  `KindFilter` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': TKindFilter read FKindFilter write SetKindFilter default kfSQL;',
		  `UseCustomSettings` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean read FUseCustomSettings write FUseCustomSettings default False;',
		  `ValueArrayIN` MEDIUMTEXT NOT NULL COMMENT ': TArrayIN read GetArrayIN write SetArrayIN;',
		  `IsTab_String` INT(11) NOT NULL DEFAULT '0' COMMENT ': Boolean  read FIsTab_String write FIsTab_String default false;',
		  `LookUpDropDownWidth` INT(11) NOT NULL DEFAULT '0' COMMENT ': Integer read FLookUpDropDownWidth write FLookUpDropDownWidth default 200;',
		  `IdnCechyDef` INT(11) NOT NULL DEFAULT '0' COMMENT ': Integer read FLookUpDropDownWidth write FLookUpDropDownWidth stored False;',
		  `NestedFilters` MEDIUMTEXT NOT NULL COMMENT ': TFilterCollection read FNestedFilters write FNestedFilters;',
		  `ExtraAndStatement` VARCHAR(250) NOT NULL DEFAULT '' COMMENT ': String read FExtraAndStatement write FExtraAndStatement;',
		  `NestedOrAnd` VARCHAR(250) NOT NULL DEFAULT 'oaAnd' COMMENT ': TOrAnd read FNestedOrAnd write FNestedOrAnd default oaAnd;',
		  PRIMARY KEY (`GUID`),
		  UNIQUE KEY `Id_browser_FieldName` (`Id_browser`,`FieldName`, `Name`)
		) ENGINE=MYISAM DEFAULT CHARSET=cp1250  
		;
		CREATE TABLE `t_ParamConteners` LIKE `t_sys_FilterConteners`;
		CREATE TABLE `t_sys_browsers_sect` LIKE `_sys_browsers_sect`;
		CREATE TABLE `t_sys_browsers_col` LIKE `_sys_browsers_col`;
		CREATE TABLE `t_sys_browsers_filters` LIKE `_sys_browsers_filters`;
		CREATE TABLE `t_sys_browsers_params` LIKE `_sys_browsers_params`;
		*/
	END IF;	--	_MODE = 'import.SQD.init' 
	
	IF _MODE = 'import.SQD.do.insert' THEN
	/********************************************************************************************************************************
		1. Zapisuje to co wynika z SQL-ki (sekcje, kolumny) 
		oraz 
		2. to co wynika z SQD (kolumny, filtry, NA RAZIE BEZ WYMIARÓW)
		oraz 
		3. SQL-ke zapisuje do SQLek browsera
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('import.SQD.do.insert', 'X1', '', '', '', '', '');
	********************************************************************************************************************************/

		CALL sys_browsers_Edit_tools('Edit.SQL.rebuild.sec.col', _Id_browser, '', '', '', '', '');
	
set @X = '-6';
	
	--	Kolumny z `t_sys_FieldDefsCollection`
		-- UPDATE `_sys_browsers_col` SET deleted = 1 WHERE Id_browser = _Id_browser;
		INSERT IGNORE INTO `t_sys_browsers_col` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `col_Name`, `col_NameAS`, `Editable`, `Comment`, `IsKey`, `AlwaysIncluded`, `Content_Src`) 
		SELECT 
			GUID, Id_browser, 'COL', FieldIndex, FieldName, FieldName,  NOT ReadOnly, Descr, KeyFields <> '', Required, c.GUID
		FROM `t_sys_FieldDefsCollection` c
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = c.GUID,
			`Id_browser` = c.Id_browser, 
			`Editable` = NOT c.ReadOnly, 
			`Comment`= c.Descr, 
			`IsKey` = c.KeyFields <> '', 
			`AlwaysIncluded` = c.Required <> 0,
			`t_sys_browsers_col`.`Content_Src` = c.GUID
		;
set @X = '-5';

		INSERT IGNORE INTO `_sys_browsers_col` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `col_Name`, `col_NameAS`, `Editable`, `Comment`, `IsKey`, `AlwaysIncluded`, `Content_Src`) 
		SELECT 
			c.GUID, c.Id_browser, c.Kind, c.LP, c.col_Name, c.col_NameAS, c.Editable, c.Comment, c.IsKey, c.AlwaysIncluded, 'SQD-COL'
		FROM `t_sys_browsers_col` c
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`Id_browser` = c.Id_browser, 
			`Kind` = c.Kind,
			`Editable` = c.Editable, 
			`Comment`= c.Comment, 
			`IsKey` = c.IsKey, 
			`AlwaysIncluded` = c.AlwaysIncluded,
			`_sys_browsers_col`.`Content_Src` = CONCAT(`_sys_browsers_col`.`Content_Src`, ',SQD-COL')
		;
		
set @X = '-4';
		
		UPDATE `t_sys_browsers_col` c 
		SET
			c.GUID = IFNULL(
			(SELECT dc.GUID FROM `_sys_browsers_col` dc WHERE dc.Id_Browser = c.Id_Browser AND dc.col_NameAs = c.col_NameAs AND dc.Kind = c.Kind),
			'')
		WHERE
			c.Id_browser = _Id_browser
			
		;
set @X = '-3';

		UPDATE `t_sys_browsers_col` tc, v_sys_usr_profile_columns c, `t_sys_FieldDefsCollection` tdc 
		SET
			c.DisplayLabel = tdc.DisplayLabel,
			c.c_Visible = tdc.Visible,
			c.c_DisplayFormat = tdc.DisplayFormat,
			c.c_AggFooterFormat = tdc.DisplayFormat,
			c.c_DisplayWidth = tdc.DisplayWidth,
			c.c_Alignment = tdc.Alignment
		WHERE
			-- md5!!! c.PrfGUID = _VarStr(MD5(CONCAT('COLUMNS', _Id_browser)))
			c.PrfGUID = _VarStr(MD5_2('COLUMNS', _Id_browser))
			AND
			tc.GUID = c.def_c_GUID
			AND
			tdc.Id_Browser = tc.Id_Browser AND tdc.FieldName = tc.col_NameAs AND tc.Kind = 'COL'
		;

	
	--	Kolumny z filtrow `t_sys_FilterConteners`
		UPDATE `_sys_browsers_filters` SET deleted = 1 WHERE Id_browser = _Id_browser;
set @X = '-2';
		
		INSERT IGNORE INTO `t_sys_browsers_filters` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `f_name`, `col_Alias`, 
		`sql_colref`, 
		`NeverVisible`, `Filter_AvaibleFlags`, `Filter_LogicSQL`, `Filter_LookUp_SQL_GUID`, `Content_Src`) 
		SELECT 
			f.GUID, f.Id_browser, 'WHERE', f.LP, f.FieldName, f.AliasName, 
			CONCAT(
				f.AliasName, 
				IF(f.AliasName = '' OR (LOCATE('.', f.AliasName) > 0), '', '.'), 
				f.FieldName
			) AS sql_colref, 
			0,  f.AvaibleFlags, 
			IF(f.Flag = 'ffLogicSQL', f.LookUpSQL, ''), 
			-- md5!!! IF(f.LookUpSQL != '', MD5(f.LookUpSQL), ''), 
			IF(f.LookUpSQL != '', MD5_1(f.LookUpSQL), ''), 
			'SQD-FILTER'
		FROM `t_sys_FilterConteners` f
		-- WHERE FALSE
		ON DUPLICATE KEY
		UPDATE
			`GUID` = f.GUID,
			`Id_browser` = f.Id_browser, 
			`Kind` = 'WHERE',
			`Filter_AvaibleFlags` = f.AvaibleFlags, 
			`Filter_LogicSQL` = IF(f.Flag = 'ffLogicSQL', f.LookUpSQL, ''),
			-- md5!!! `Filter_LookUp_SQL_GUID` = IF(f.LookUpSQL != '', MD5(f.LookUpSQL), ''),
			`Filter_LookUp_SQL_GUID` = IF(f.LookUpSQL != '', MD5_1(f.LookUpSQL), ''),
			`t_sys_browsers_filters`.`Content_Src` = CONCAT(`t_sys_browsers_filters`.`Content_Src`, ',SQD-FILTER')
		;
set @X = '-1';
		
		UPDATE `t_sys_browsers_filters` f 
		SET
			f.def_c_GUID = IFNULL(
			(SELECT c.GUID FROM `_sys_browsers_col` c WHERE c.Id_Browser = f.Id_Browser AND c.col_Name = f.f_name AND c.col_Alias = f.col_Alias),
			NULL)
		WHERE
			f.Id_browser = _Id_browser
			
		;
set @X = '1';
		INSERT IGNORE INTO `_sys_browsers_filters` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `def_c_GUID`, `f_name`, `col_Alias`, `sql_colref`, `NeverVisible`, `Filter_AvaibleFlags`, `Filter_LogicSQL`, `Filter_LookUp_SQL_GUID`, `Content_Src`) 
		SELECT 
			f.GUID, f.Id_browser, 'WHERE', f.LP, f.def_c_GUID, f.f_name, f.col_Alias, sql_colref, NeverVisible,  f.Filter_AvaibleFlags, Filter_LogicSQL, Filter_LookUp_SQL_GUID, 'SQD-FILTER'
		FROM `t_sys_browsers_filters` f
		-- WHERE FALSE
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = f.GUID,
			`Id_browser` = f.Id_browser, 
			`def_c_GUID` = f.def_c_GUID,
			`Kind` = f.Kind,
			`Filter_AvaibleFlags` = f.Filter_AvaibleFlags, 
			`Filter_LogicSQL` = f.Filter_LogicSQL,
			`Filter_LookUp_SQL_GUID` = f.Filter_LookUp_SQL_GUID,
			`_sys_browsers_filters`.`Content_Src` = CONCAT(`_sys_browsers_filters`.`Content_Src`, ',SQD-FILTER')
		;
		
set @X = '2';
		UPDATE `t_sys_browsers_filters` f 
		SET
			f.GUID = IFNULL(
			(SELECT df.GUID FROM `_sys_browsers_filters` df WHERE df.Id_Browser = f.Id_Browser AND df.f_Name = f.f_Name AND df.Kind = f.Kind),
			'')
		WHERE
			f.Id_browser = _Id_browser
			
		;

set @X = '3';

		UPDATE v_sys_usr_profile_filters f, `t_sys_browsers_filters` tf, `t_sys_FilterConteners` tfc 
		SET
			f.DisplayLabel = tfc.DisplayLabel,
			f.f_Active = tfc.Active,
			f.f_CaseSensitive = tfc.CaseSensitive,
			f_Neg = tfc.Neg,
			f_Flag = tfc.Flag,
			f.f_Value_Down = tfc.ValueDown,
			f.f_Value_Up = tfc.ValueUp
			-- f_sql_Expr = tfc.sql_Expr
		WHERE
			-- md5!!! f.PrfGUID = _VarStr(MD5(CONCAT('FILTERS', _Id_browser)))
			f.PrfGUID = _VarStr(MD5_2('FILTERS', _Id_browser))
			AND
			tf.GUID = f.def_f_GUID
			AND
			tfc.GUID = tf.GUID
		;

set @X = '4';

	--	Kolumny z parametrów `t_sys_ParamConteners`
		UPDATE `_sys_browsers_params` SET deleted = 1 WHERE Id_browser = _Id_browser;
		INSERT IGNORE INTO `t_sys_browsers_params` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `p_name`, `Content_Src`, GUI_FieldType) 
		SELECT 
			p.GUID, p.Id_browser, 'PARAM', 0, p.NAME, 'SQD-PARAM', 
			(
			SELECT
				sp.ParamExtra
			FROM `slowniki_pierwotne` sp
			WHERE
				sp.Slownik_GUID = 'BOR_DataType'
				AND
				sp.DisplayValue = p.DataType
			) AS GUI_FieldType
		FROM `t_sys_ParamConteners` p
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = p.GUID,
			`Id_browser` = p.Id_browser, 
			`t_sys_browsers_params`.`Content_Src` = CONCAT(`t_sys_browsers_params`.`Content_Src`, ',SQD-PARAM'),
			`GUI_FieldType` = 
				(
				SELECT
					sp.ParamExtra
				FROM `slowniki_pierwotne` sp
				WHERE
					sp.Slownik_GUID = 'BOR_DataType'
					AND
					sp.DisplayValue = p.DataType
				)
		;
		
set @X = '5';
		
		INSERT IGNORE INTO `_sys_browsers_params` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `p_name`, `Content_Src`, GUI_FieldType)
		SELECT 
			p.GUID, p.Id_browser, p.Kind, p.LP, p.p_name, p.Content_Src, p.GUI_FieldType
		FROM `t_sys_browsers_params` p
		-- WHERE FALSE
		ON DUPLICATE KEY
		UPDATE
			`Deleted` = 0,
			`GUID` = p.GUID,
			`Id_browser` = p.Id_browser, 
			`_sys_browsers_params`.`Content_Src` = p.Content_Src,
			`GUI_FieldType` = p.GUI_FieldType
		;
set @X = '6';
		UPDATE `t_sys_browsers_params` p 
		SET
			p.GUID = IFNULL(
			(SELECT dp.GUID FROM `_sys_browsers_params` dp WHERE dp.Id_Browser = p.Id_Browser AND dp.p_Name = p.p_Name),
			'')
		WHERE
			p.Id_browser = _Id_browser
			
		;
set @X = '7';
		UPDATE v_sys_usr_profile_params p, `t_sys_browsers_params` tp, `t_sys_ParamConteners` tpc 
		SET
			p.DisplayLabel = tpc.DisplayLabel,
			p.f_Active = tpc.Active,
			p.f_CaseSensitive = tpc.CaseSensitive,
			p.f_Value_Down = tpc.ValueDown
			-- f_sql_Expr = tfc.sql_Expr
		WHERE
			-- md5!!! p.PrfGUID = _VarStr(MD5(CONCAT('PARAMS', _Id_browser)))
			p.PrfGUID = _VarStr(MD5_2('PARAMS', _Id_browser))
			AND
			tp.GUID = p.def_p_GUID
			AND
			tpc.GUID = tp.GUID
		;


/*

Na razie
		
		
		
		SET 
			@p.c.Id_browser = MD5(CONCAT('COLUMNS', _Id_browser)),
			@p.f.Id_browser = MD5(CONCAT('FILTERS', _Id_browser))
		;
		


		
	--	`t_sys_ParamConteners`
		UPDATE `_sys_usr_profile_f` pf, `t_sys_ParamConteners` f
		SET
			pf.Ord = f.LP, 
			-- pf.Active = f.Active,
			-- pf.Visible = f.Visible,
			pf.DisplayLabel = f.DisplayLabel,
			pf.Filter_Type = 'PARAM',
			-- pf.CaseSensitive = f.CaseSensitive,
			pf.Value_Down = f.ParamValue
			
		WHERE
			pf.PrfGUID = @p.f.Id_browser
			AND
			pf.ColGUID = f.GUID
		;
		
		*/
		
set @X = '8';
	--	SQL-ki z filtrow `t_sys_FilterConteners`
		INSERT IGNORE INTO `_sys_browsers_sql` 
		(`GUID`, `Id_browser`, `Kind`, `LP`, `SQL`, `SQL_IsSimilarSearch`, `SQL_ResultSQL`, `SQL_KeyFieldName`,`SQL_ResultFieldNames`) 
		SELECT 
			-- md5!!! MD5(f.LookUpSQL), 
			MD5_1(f.LookUpSQL), 
			Id_browser, 'LOOKUP', 0, f.LookUpSQL, 0, f.LookUpSQL, f.LookUpFieldName, f.LookUpResultFieldName 
		FROM `t_sys_FilterConteners` f
		WHERE 
			f.LookUpSQL != ''
		;
		
		CALL sys_browsers_Edit_tools('Edit.SQL.Refresh', _Id_browser, '', '', '', '', '');
		
	END IF;	--	_MODE LIKE 'import.SQD.do.insert' 


	
	IF _MODE = 'Edit.SQL.GET' THEN
	/********************************************************************************************************************************
		Zwraca SQL-kę browsera
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('Edit.SQL.Get', 'X1', '', '', '', '', '');
	********************************************************************************************************************************/
		-- CALL sys_browsers_Edit_tools('Edit.SQL.Init', 'X1', '', '', '', '', '');
		-- na razie wlam 'sqltext.build.information_schema' bo nie wiem czy sa tam juz sqlki
		CALL sys_browsers_Edit_tools('Edit.SQL.Refresh', _Id_browser, '', '', '', '', '');
		SELECT s.SQL FROM `_sys_browsers_sql` s WHERE s.Id_browser = _Id_browser AND s.Kind = 'SQL';
	END IF;	--	_MODE = 'Edit.SQL.GET' 
	
	IF _MODE = 'Edit.SQL.After' THEN
	/********************************************************************************************************************************
		Zapisuje to co wynika z SQL-ki (sekcje, kolumny) 
		oraz SQL-ke zapisuje do SQLek browsera
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('Edit.SQL.After', 'X1', '', '', '', '', '');
	********************************************************************************************************************************/
		CALL sys_browsers_Edit_tools('Edit.SQL.rebuild.sec.col', _Id_browser, '', '', '', '', '');
		CALL sys_browsers_Edit_tools('Edit.SQL.Refresh', _Id_browser, '', '', '', '', '');
	END IF;	--	_MODE = 'Edit.SQL.After' 
	
	IF _MODE = 'Edit.SQL.Refresh' THEN
	/********************************************************************************************************************************
		Wstawia do browserów (kolumy) i profili col i filtr dla ALL 
		w _Id_browser GUID Browsera
		CALL sys_browsers_Edit_tools('Edit.SQL.Refresh', 'X1', '', '', '', '', '');
	********************************************************************************************************************************/
		CALL sys_browsers_tools('sqltext.build.information_schema', _Id_browser, '', '', '', '', '', '', '');
		INSERT IGNORE INTO `_sys_browsers_sql` 
		(`GUID`, `Id_browser`, `Kind`, `SQL`) 
		SELECT 
			_Id_browser, _Id_browser, 'SQL', @sql.text.template
		FROM `t_sys_FilterConteners` f
		-- WHERE FALSE
		ON DUPLICATE KEY
		UPDATE
			`SQL` = @sql.text.template
		;
	END IF;	--	_MODE = 'Edit.SQL.Refresh' 



		IF _MODE LIKE 'DISTRIBUTE.Browser.Tools%' THEN
			IF _MODE = 'DISTRIBUTE.Browser.Tools.temp.drop' THEN
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_n`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_sect`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_sect_need`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_col`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_filters`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_params`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_cube`;
			--	Profile
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile_cpf`;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile_cpf_f_v`;
			END IF;
			
			IF _MODE = 'DISTRIBUTE.Browser.Tools.temp.create' THEN
				SET @_Id_browser = _Id_browser;
				
			--	Ustawienia Browserow
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_n`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_n`
				SELECT
					n.*
				FROM `_sys_browsers_n` n
				WHERE
					n.Id = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_sect`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_sect`
				SELECT
					s.*
				FROM `_sys_browsers_sect` s
				WHERE
					s.Id_browser = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_sect_need`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_sect_need`
				SELECT
					sn.*
				FROM `_sys_browsers_sect` s
				INNER JOIN `_sys_browsers_sect_need` sn ON sn.Source_sect = s.GUID
				WHERE
					s.Id_browser = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_col`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_col`
				SELECT
					c.*
				FROM `_sys_browsers_col` c
				WHERE
					c.Id_browser = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_filters`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_filters`
				SELECT
					f.*
				FROM `_sys_browsers_filters` f
				WHERE
					f.Id_browser = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_params`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_params`
				SELECT
					p.*
				FROM `_sys_browsers_params` p
				WHERE
					p.Id_browser = @_Id_browser
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_browsers_cube`;
				CREATE TEMPORARY TABLE `t_clone_sys_browsers_cube`
				SELECT
					c.*
				FROM `_sys_browsers_cube` c
				WHERE
					c.Id_browser = @_Id_browser
				;
			--	Profile
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile`;
				CREATE TEMPORARY TABLE `t_clone_sys_usr_profile`
				SELECT
					p.*
				FROM `_sys_usr_profile` p
				WHERE
					p.Re_Id = @_Id_browser
					AND
					p.OwnerGUID = 'ALL'
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile_cpf`;
				CREATE TEMPORARY TABLE `t_clone_sys_usr_profile_cpf`
				SELECT
					pc.*
				FROM `t_clone_sys_usr_profile` p
				INNER JOIN `_sys_usr_profile_cpf` pc ON pc.PrfGUID = p.GUID
				;
				DROP TEMPORARY TABLE IF EXISTS `t_clone_sys_usr_profile_cpf_f_v`;
				CREATE TEMPORARY TABLE `t_clone_sys_usr_profile_cpf_f_v`
				SELECT
					pcv.*
				FROM `t_clone_sys_usr_profile_cpf` pc
				INNER JOIN `_sys_usr_profile_cpf_f_v` pcv ON pcv.GUIDf = pc.GUID
				;
			
			END IF;
		END IF;
		

		IF _MODE = 'CLONE.Browser' THEN
		/********************************************************************************************************************************
			Klonuje browser z nowym GUIDem i nazwa 
			CALL sys_browsers_Edit_tools('CLONE.Browser', 'X1', '', '', '', '', '');
			_Id_browser GUID Browsera
			_Param_A 	Nowy GUID Browsera
			_Param_B 	Nowa nazwa
		********************************************************************************************************************************/
			CALL sys_browsers_Edit_tools('DISTRIBUTE.Browser.Tools.temp.create', _Id_browser, _Param_A, _Param_B, '', '', '');
			SET 
				-- md5!!! @p.c.Re_Id = MD5(CONCAT('COLUMNS', _Id_browser)),
				@p.c.Re_Id = MD5_2('COLUMNS', _Id_browser),
				-- md5!!! @p.f.Re_Id = MD5(CONCAT('FILTERS', _Id_browser)),
				@p.f.Re_Id = MD5_2('FILTERS', _Id_browser),
				-- md5!!! @p.p.Re_Id = MD5(CONCAT('PARAMS', _Id_browser)),
				@p.p.Re_Id = MD5_2('PARAMS', _Id_browser),
				-- md5!!! @p.d.Re_Id = MD5(CONCAT('CUBE', _Id_browser)),
				@p.d.Re_Id = MD5_2('CUBE', _Id_browser),
				_Param_A = IF(IFNULL(_Param_A, '')  = '', UUID(), _Param_A)
			;
			SET @_Id_browser = _Id_browser, @_CLONE_Id_browser = _Param_A;
			
		
	/*
	dokoncz 
	*/
	
			UPDATE `t_clone_sys_browsers_n` t
			SET
				t.Id = @_CLONE_Id_browser,
				t.Nazwa = IF(IFNULL(_Param_B, '') = '', t.Nazwa, _Param_B)
			;	

			UPDATE `t_clone_sys_browsers_sect` t
			SET
				t.Id_browser = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser))
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser)
			;	

			UPDATE `t_clone_sys_browsers_sect_need` t
			SET
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser)),
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser),
				-- md5!!! t.Source_sect = MD5(CONCAT(t.Source_sect, @_CLONE_Id_browser))
				t.Source_sect = MD5_2(t.Source_sect, @_CLONE_Id_browser)
			;	
		
			UPDATE `t_clone_sys_browsers_col` t
			SET
				t.Id_browser = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser))
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser)
			;	

			UPDATE `t_clone_sys_browsers_filters` t
			SET
				t.Id_browser = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser)),
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser),
				-- md5!!! t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5(CONCAT(t.def_c_GUID, @_CLONE_Id_browser)))
				t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5_2(t.def_c_GUID, @_CLONE_Id_browser))
				-- t.Filter_LookUp_SQL_GUID = MD5(CONCAT(t.Filter_LookUp_SQL_GUID, @_CLONE_Id_browser)),
			;	

			UPDATE `t_clone_sys_browsers_params` t
			SET
				t.Id_browser = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser))
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser)
			;	

			UPDATE `t_clone_sys_browsers_cube` t
			SET
				t.Id_browser = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser)),
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser),
				-- md5!!! t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5(CONCAT(t.def_c_GUID, @_CLONE_Id_browser)))
				t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5_2(t.def_c_GUID, @_CLONE_Id_browser))
			;	
		--	Profile
			UPDATE `t_clone_sys_usr_profile_cpf` t, `t_clone_sys_usr_profile` tn
			SET
				-- md5!!! t.PrfGUID = MD5(CONCAT(tn.Typ, @_CLONE_Id_browser))
				t.PrfGUID = MD5_2(tn.Typ, @_CLONE_Id_browser)
			WHERE
				t.PrfGUID = tn.GUID
			;	
			UPDATE `t_clone_sys_usr_profile` t
			SET
				t.Re_Id = @_CLONE_Id_browser,
				-- md5!!! t.GUID = MD5(CONCAT(t.Typ, @_CLONE_Id_browser))
				t.GUID = MD5_2(t.Typ, @_CLONE_Id_browser)
			;	
			UPDATE `t_clone_sys_usr_profile_cpf` t
			SET
				-- md5!!! t.GUID = MD5(CONCAT(t.GUID, @_CLONE_Id_browser)),
				t.GUID = MD5_2(t.GUID, @_CLONE_Id_browser),
				-- md5!!! t.GUID_ALL = MD5(CONCAT(t.GUID_ALL, @_CLONE_Id_browser)),
				t.GUID_ALL = MD5_2(t.GUID_ALL, @_CLONE_Id_browser),
				-- md5!!! t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5(CONCAT(t.def_c_GUID, @_CLONE_Id_browser))),
				t.def_c_GUID = IF(IFNULL(t.def_c_GUID, '') = '', NULL, MD5_2(t.def_c_GUID, @_CLONE_Id_browser)),
				-- md5!!! t.def_f_GUID = IF(IFNULL(t.def_f_GUID, '') = '', NULL, MD5(CONCAT(t.def_f_GUID, @_CLONE_Id_browser))),
				t.def_f_GUID = IF(IFNULL(t.def_f_GUID, '') = '', NULL, MD5_2(t.def_f_GUID, @_CLONE_Id_browser)),
				-- md5!!! t.def_p_GUID = IF(IFNULL(t.def_p_GUID, '') = '', NULL, MD5(CONCAT(t.def_p_GUID, @_CLONE_Id_browser))),
				t.def_p_GUID = IF(IFNULL(t.def_p_GUID, '') = '', NULL, MD5_2(t.def_p_GUID, @_CLONE_Id_browser)),
				-- md5!!! t.def_d_GUID = IF(IFNULL(t.def_d_GUID, '') = '', NULL, MD5(CONCAT(t.def_d_GUID, @_CLONE_Id_browser)))
				t.def_d_GUID = IF(IFNULL(t.def_d_GUID, '') = '', NULL, MD5_2(t.def_d_GUID, @_CLONE_Id_browser))
			;	
			UPDATE `t_clone_sys_usr_profile_cpf_f_v` t
			SET
				-- md5!!! t.GUIDf = MD5(CONCAT(t.GUIDf, @_CLONE_Id_browser))
				t.GUIDf = MD5_2(t.GUIDf, @_CLONE_Id_browser)
			;	
		--	Wstawianie
			INSERT IGNORE INTO `_sys_usr_profile_cpf_f_v`
			SELECT * FROM `t_clone_sys_usr_profile_cpf_f_v`;
			
			INSERT IGNORE INTO `_sys_usr_profile_cpf`
			SELECT * FROM `t_clone_sys_usr_profile_cpf`;
			
			INSERT IGNORE INTO `_sys_usr_profile`
			SELECT * FROM `t_clone_sys_usr_profile`;
			
			INSERT IGNORE INTO `_sys_browsers_cube`
			SELECT * FROM `t_clone_sys_browsers_cube`;

			INSERT IGNORE INTO `_sys_browsers_params`
			SELECT * FROM `t_clone_sys_browsers_params`;

			INSERT IGNORE INTO `_sys_browsers_filters`
			SELECT * FROM `t_clone_sys_browsers_filters`;

			INSERT IGNORE INTO `_sys_browsers_col`
			SELECT * FROM `t_clone_sys_browsers_col`;

			INSERT IGNORE INTO `_sys_browsers_sect_need`
			SELECT * FROM `t_clone_sys_browsers_sect_need`;

			INSERT IGNORE INTO `_sys_browsers_sect`
			SELECT * FROM `t_clone_sys_browsers_sect`;

			INSERT IGNORE INTO `_sys_browsers_n`
			SELECT * FROM `t_clone_sys_browsers_n`;
			
			CALL sys_browsers_Edit_tools('DISTRIBUTE.Browser.Tools.temp.drop', _Id_browser, _Param_A, _Param_B, '', '', '');
		END IF;	--	_MODE = 'CLONE.Browser' 
		
	
	
END
$$

DROP PROCEDURE IF EXISTS `_sys_usr_profile_utilities`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_usr_profile_utilities`(
	IN _MODE VARCHAR(250),
	IN _Re_Id VARCHAR(50),	
	INOUT _PrfGUID VARCHAR(50),	
	INOUT _All_PrfGUID VARCHAR(50),
	INOUT _User VARCHAR(50),	
	IN _Param_A VARCHAR(50),		--	 np. SearchText w _MODE = 'SELECT.profiles.FILTERS.get.lookup.search'
	IN _Param_B VARCHAR(50),	
	IN _Param_C VARCHAR(50),	
	IN _Param_D VARCHAR(50),	
	IN _Param_E VARCHAR(50)	
)
/*

*/

S_sys_usr_profile_utilities: BEGIN 

	DECLARE _Typ VARCHAR(250);
	DECLARE _Name_AS VARCHAR(250);		--	nazwa docelowa
	DECLARE _PrfGUID_SRC VARCHAR(250);	--	Zrodlowy profil
	DECLARE _TimeSt_0 TIMESTAMP DEFAULT '0000-00-00 00:00:00';
	DECLARE _sql_text_SELECT MEDIUMTEXT; -- @.sql.text.SELECT
	DECLARE _SQLText, _SQLBuff MEDIUMTEXT;

	
	IF _MODE = 'update.user' THEN
	/********************************************************************************************************************************
		Gdy _User = '' to pobierz z logowania
		CALL _sys_usr_profile_utilities('update.user', '', @empty, @empty, _User, '', '', '', '', '');
	********************************************************************************************************************************/
		IF IFNULL(_User, '') = '' THEN
			IF IFNULL(@SYSTEM.Client.Session.log_USER_GUID, '') = '' THEN
				/*	20 XII 2023
				CALL _sys_db_logons_rec_tools('GET.@SYSTEM.Client.Session.log_USER_GUID', @SYSTEM.Client.Session.GUID, 0, '', '', '', '', '');
				*/
				CALL _sessions_APP('SET.VAR', '', '', '', '', '', '');
			END IF;
			SET _User = @SYSTEM.Client.Session.log_USER_GUID;
		END IF;
		SET @_User = _User;
	END IF;	--	_MODE = 'Edit.SQL.Refresh' 

	IF _MODE LIKE 'get.profil.default.%' THEN
	/********************************************************************************************************************************
		Gdy _User = '' to pobierz z logowania
		CALL _sys_usr_profile_utilities('get.profil.default.COLUMNS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.default.FILTERS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.default.PARAMS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.default.CUBE', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
	********************************************************************************************************************************/
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'get.profil.default.PARAMS', '', '', '');
		SET _Typ = REPLACE(_MODE, 'get.profil.default.', '');	--	 zostanie 'COLUMNS' lub 'FILTERS', etc
		set @._Typ = _Typ, @._User = _User, @._Re_Id = _Re_Id;
		IF IFNULL(_All_PrfGUID, '') = '' THEN
			-- md5!!! SET _All_PrfGUID = IF(_Typ = 'COLUMNS', MD5(CONCAT('COLUMNS', _Re_Id)), IF(_Typ = 'FILTERS', MD5(CONCAT('FILTERS', _Re_Id)), IF(_Typ = 'PARAMS', MD5(CONCAT('PARAMS', _Re_Id)), MD5(CONCAT('CUBE', _Re_Id))))); 
			SET 
				_All_PrfGUID = 
					IF(_Typ = 'COLUMNS', 
						MD5_2('COLUMNS', _Re_Id), 
						IF(_Typ = 'FILTERS', 
						 MD5_2('FILTERS', _Re_Id), 
							IF(_Typ = 'PARAMS', 
								MD5_2('PARAMS', _Re_Id), 
								MD5_2('CUBE', _Re_Id)
							)
						)
					)
			; 
		END IF;
SET @u._All_PrfGUID = _All_PrfGUID;	
SET @._All_PrfGUID = _All_PrfGUID;	
		IF IFNULL(_PrfGUID, '') = '' THEN
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'get.profil.default.PARAMS.1', '', '', '');
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'get.profil.default.PARAMS.1.1', '', '', '');
			SET
				_PrfGUID = IFNULL(
					(
					SELECT
						p.GUID AS GUID
					FROM `_sys_usr_profile` p
					WHERE
						p.Re_Id = _Re_Id -- 'x'
						AND p.PrfName = ''
						AND p.OwnerGUID = _User -- 'jmam'
						AND p.Typ = _Typ
					ORDER BY LastUsedAt DESC
					LIMIT 1
					)
					, '')
			;
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'get.profil.default.PARAMS.1.1', '', '', '');
SET @u.1._PrfGUID = _PrfGUID;
SET @._PrfGUID = _PrfGUID;
			IF _PrfGUID = '' THEN
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'get.profil.default.PARAMS.1.2', '', '', '');
				CALL _sys_usr_profile_utilities('profile.save.as', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _All_PrfGUID, '', '', '', '');
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'get.profil.default.PARAMS.1.2', '', '', '');
			END IF;
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'get.profil.default.PARAMS.1', '', '', '');
		END IF;
SET @u.2._PrfGUID = _PrfGUID;
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'get.profil.default.PARAMS', '', '', '');
	END IF;	--	_MODE LIKE 'get.profil.default.%' THEN
	

	IF _MODE LIKE 'get.profil.by.guid.or.default.%' THEN
	/********************************************************************************************************************************
		Gdy _User = '' to pobierz z logowania
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.COLUMNS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.FILTERS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.PARAMS', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		CALL _sys_usr_profile_utilities('get.profil.by.guid.or.default.CUBE', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
	********************************************************************************************************************************/
		SET @SyncGo = 0;
		IF IFNULL(_PrfGUID, '') = '' THEN
			CALL _sys_usr_profile_utilities(REPLACE(_MODE, 'by.guid.or.', ''), _Re_Id, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		END IF;
			SET @SyncGo = concat(IFNULL(_PrfGUID, ':null:'), '...', _Param_A);
		IF IFNULL(_PrfGUID, '') != '' AND _Param_A = 'sync' THEN
			SET @SyncGo = 1;
			CALL _sys_usr_profile_utilities('profile.syns.with.ALL', _Re_Id, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		END IF;
		
	END IF;	--	_MODE LIKE 'get.profil.default.%' THEN

	IF _MODE = 'profile.save.as' THEN
	/********************************************************************************************************************************
		Zapisz pod inna nazwa/ do innego profilu
		CALL _sys_usr_profile_utilities('profile.save.as', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '_PrfGUID_SRC', '_Name_AS', '', '', '');
		w _PrfGUID GUID profilu który powstanie z tego ktory zachowujemy jako... (czasem jest to profill ALL)
		w _Param_A Profil zrodlowy czyli ten ktory zachowujemy jako... (czasem jest to profill ALL)
		w _Param_B Nazwa nowego profilu pod jaka zapisujemy profil _Key
		w _User zazwyczaj "" ALE czasem gdy kopiujemy profill ALL na profil usera - to mamy tu uzytkownika (usera)
	********************************************************************************************************************************/
		-- w @.Prf.Profile.Typ mam typ profilu 'COLUMNS' lub 'FILTERS'
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as', '', '', '');
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as.1.0', '', '', '');
		SET
			_PrfGUID_SRC = _Param_A,			--	Zrodlowy profil
			_Name_AS = _Param_B,				--	nazwa docelowa
			_PrfGUID = IF(IFNULL(_PrfGUID, '') = '', UUID(), _PrfGUID)
		;
		SET 
			@.Prf.NewCreate.GUID = _PrfGUID, 
			@.Prf.NewCreate.PrfName = _Name_AS,
			@.Prf.NewCreate.OwnerGUID = _User
			, @._PrfGUID_SRC = _PrfGUID_SRC
		;
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as.1.0', '', '', '');
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as.1.1', '', '', '');

		SET @.ROW_COUNT = null;
		/*
		DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile`;
		CREATE TEMPORARY TABLE `t_sys_usr_profile` LIKE `_sys_usr_profile`;
		INSERT INTO `t_sys_usr_profile`
		*/
		DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile`;
		CREATE TEMPORARY TABLE `t_sys_usr_profile` 
			SELECT
				p.*
			FROM `_sys_usr_profile` p
			WHERE
				p.GUID = _PrfGUID_SRC -- @._PrfGUID_SRC
		;
		SET @.ROW_COUNT = ROW_COUNT();
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as.1.1', '', '', '');
		IF @.ROW_COUNT > 0 THEN
		-- IF @.ROW_COUNT.ext > 0 THEN
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as.1.2', '', '', '');
			UPDATE `t_sys_usr_profile` t
			SET
				t.GUID = @.Prf.NewCreate.GUID, 
				t.PrfName = @.Prf.NewCreate.PrfName,
				t.OwnerGUID = IF(@.Prf.NewCreate.OwnerGUID != '', @.Prf.NewCreate.OwnerGUID, t.OwnerGUID),
				t.CreateAt = NOW(),
				t.LastSyncTime = NOW(),
				t.LastUsedAt = NOW()
			;
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as.1.2', '', '', '');
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as.1.3', '', '', '');
			INSERT IGNORE INTO `_sys_usr_profile`
			SELECT
				t.*
			FROM `t_sys_usr_profile` t
			;
		-- DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile`;
		
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as.1.3', '', '', '');
-- CALL _sys_watch_time_Tools('start', 'SQL.INIT', 'profile.save.as.1.4', '', '', '');
			CALL _sys_usr_profile_utilities('profile.copy.from', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _PrfGUID_SRC, '', '', '', '');
-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as.1.4', '', '', '');
		END IF;

-- CALL _sys_watch_time_Tools('stop', 'SQL.INIT', 'profile.save.as', '', '', '');
	END IF;	--	_MODE LIKE 'profile.save.as' 


			IF _MODE = 'profile.Delete' THEN
			/********************************************************************************************************************************
				Usuwanie profilu - ng + detale
				CALL _sys_usr_profile_utilities('profile.Delete', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '_PrfGUID_SRC', '', '', '', '');
				w _PrfGUID GUID profilu ktory usuwamy
				w _Param_B gdy <> '' to nalezy uwzglednic GUID_ALL
			********************************************************************************************************************************/
				UPDATE `_sys_usr_profile` p, `_sys_usr_profile_cpf` cpf
				SET
					p.Deleted = 1,
					cpf.Deleted = 1
				WHERE
					p.GUID = _PrfGUID
					-- md5!!! AND (p.GUID != MD5(CONCAT(p.Typ, p.Re_Id)))
					AND (p.GUID != MD5_2(p.Typ, p.Re_Id))
					AND 
					cpf.PrfGUID = p.GUID
				;
			END IF;

			IF _MODE = 'profile.copy.from' THEN
			/********************************************************************************************************************************
				Pobieranie pozycji z innego profilu
				CALL _sys_usr_profile_utilities('profile.copy.from', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '_PrfGUID_SRC', '', '', '', '');
				w _PrfGUID GUID profilu do ktorego kopiujemy
				w _Param_A Profil zrodlowy czyli ten z ktorego kopiujemy
				w _Param_B gdy <> '' to nalezy uwzglednic GUID_ALL
			********************************************************************************************************************************/
				SET
					_PrfGUID_SRC = _Param_A		--	Zrodlowy profil
				;
			--	Kolumny i wszystki einne
				DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile_cpf`;
				CREATE TEMPORARY TABLE `t_sys_usr_profile_cpf` LIKE `_sys_usr_profile_cpf`;
				INSERT INTO `t_sys_usr_profile_cpf`
				SELECT
					c.*
				FROM `_sys_usr_profile_cpf` c
				WHERE
					c.PrfGUID = _PrfGUID_SRC	--	żródłowy
				;
			--	ze względu na detale (values) musze miec zmianę GUID(src) -> GUID docelowy!!!
				DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile_old_new_GUID`;
				CREATE TEMPORARY TABLE `t_sys_usr_profile_old_new_GUID` 
				SELECT
					UUID_SHORT() AS GUID,	--	zmieniamy GUID ale ten rekord ma jeszcze detale
					tc.GUID AS OldGUID
				FROM `t_sys_usr_profile_cpf` tc
				;
				UPDATE `t_sys_usr_profile_cpf` tc,
				(SELECT * FROM `t_sys_usr_profile_old_new_GUID`) ton
				SET
					--	było tc.GUID = UUID(),	--	zmieniamy GUID ale ten rekord ma jeszcze detale
					tc.GUID = ton.GUID,
					tc.CreateAt = NOW(),
					-- tc.GUID_ALL = tc.GUID
					tc.PrfGUID = _PrfGUID
				WHERE
					ton.OldGUID = tc.GUID
				;
				IF _Param_B = '' THEN
					DELETE FROM `_sys_usr_profile_cpf`
					WHERE
						PrfGUID = _PrfGUID
					;
				END IF;
				INSERT IGNORE INTO `_sys_usr_profile_cpf`
				SELECT
					tc.*
				FROM `t_sys_usr_profile_cpf` tc
				;
			--	Wartosci profili (values)
				DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile_cpf_f_v`;
				CREATE TEMPORARY TABLE `t_sys_usr_profile_cpf_f_v` LIKE `_sys_usr_profile_cpf_f_v`;
				INSERT INTO `t_sys_usr_profile_cpf_f_v`
				SELECT
					cv.*
				FROM `_sys_usr_profile_cpf` c, `_sys_usr_profile_cpf_f_v` cv
				WHERE
					c.PrfGUID = _PrfGUID_SRC	--	źródłowe filter nody
					AND cv.GUIDf = c.GUID		--	wart. filter noda
				;
				
				UPDATE `t_sys_usr_profile_cpf_f_v` tcv,
				(SELECT * FROM `t_sys_usr_profile_old_new_GUID`) ton
				SET
					tcv.GUIDf = ton.GUID
				WHERE
					ton.OldGUID = tcv.GUIDf
				;
				INSERT IGNORE INTO `_sys_usr_profile_cpf_f_v`
				SELECT
					tcv.*
				FROM `t_sys_usr_profile_cpf_f_v` tcv
				;
				DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile_cpf`;
				DROP TEMPORARY TABLE IF EXISTS `t_sys_usr_profile_cpf_f_v`;
		
			END IF;	--	_MODE = 'profile.copy.from' 
	
	IF _MODE = 'profile.load.from' THEN
	/********************************************************************************************************************************
		Pobieranie pozycji z innego profilu
		CALL _sys_usr_profile_utilities('profile.load.from', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '_PrfGUID_SRC', '', '', '', '');
		w _PrfGUID GUID profilu do ktorego kopiujemy MUSI ISTNIEC!!!!
		w _Param_A Profil zrodlowy czyli ten z ktorego kopiujemy
	********************************************************************************************************************************/
		SET
			_PrfGUID_SRC = _Param_A		--	Zrodlowy profil
		;
		CALL _sys_usr_profile_utilities('profile.copy.from', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _PrfGUID_SRC, '', '', '', '');
	-- 	Ale aby nie tracić tgo co w ALL - synchronizuj brakujące z ALL
		SET _PrfGUID_SRC = '';
		CALL _sys_usr_profile_utilities('profile.load.from.ALL', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _PrfGUID_SRC, 'not delete', '', '', '');
	END IF;	--	_MODE = 'profile.load.from' 

	IF _MODE = 'profile.load.from.ALL' THEN
	/********************************************************************************************************************************
		Pobieranie pozycji z profilu ALL - czyli przywroc ustawienia fabryczne  (_Param_B = '')
		LUB
		pobieranie z ALL brakującychy (_Param_B <> '')
		CALL _sys_usr_profile_utilities('profile.load.from.ALL', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '_PrfGUID_SRC', '_Name_AS', '', '', '');
		w _PrfGUID GUID profilu do ktorego kopiujemy MUSI ISTNIEC!!!!
		w _Param_A Profil zrodlowy czyli ten z ktorego kopiujemy - NAJCZESCIEJ PUSTY I WTEDY to musi byc ten ALL 
		w _Param_B gdy != '' to w kopiowaniu nie usuwa pozycji profilu - czyli scenariusz synchronizacji gdy nie usuwamy i zastepujemy ale doinsertowujemy z ALL 
	********************************************************************************************************************************/
		SET
			_PrfGUID_SRC = _Param_A		--	Zrodlowy profil
		;
		IF IFNULL(_PrfGUID_SRC, '') = '' THEN
			SET
				_PrfGUID_SRC = IFNULL((
					SELECT
						-- bylo i moze bedzie MD5(CONCAT(LOWER(SUBSTR(p.Typ, 1, 1)), p.Id_Browser)) AS GUID_ALL
						-- md5!!! MD5(CONCAT(p.Typ, p.Re_Id)) AS GUID_ALL 
						MD5_2(p.Typ, p.Re_Id) AS GUID_ALL
						-- IF(p.Typ = 'COLUMNS', MD5(CONCAT('COLUMNS', p.Id_Browser)), IF(p.Typ = 'FILTERS', MD5(CONCAT('FILTERS', p.Id_Browser)), IF(p.Typ = 'PARAMS', MD5(CONCAT('PARAMS', p.Id_Browser)), MD5(CONCAT('CUBE', p.Id_Browser))))) AS GUID_ALL 
					FROM `_sys_usr_profile` p 
					WHERE 
						p.GUID = _PrfGUID
				), '')
			;
		END IF;
		
		IF IFNULL(_PrfGUID_SRC, '') != '' THEN
			CALL _sys_usr_profile_utilities('profile.copy.from', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _PrfGUID_SRC, _Param_B, '', '', '');
		END IF;
	END IF;	--	_MODE = 'profile.load.from.ALL' 

	IF _MODE = 'profile.syns.with.ALL' THEN
	/********************************************************************************************************************************
		Synchronizacja profilu _PrfGUID
		CALL _sys_usr_profile_utilities('profile.syns.with.ALL', _Id_browser, _PrfGUID, _All_PrfGUID, _User, '', '', '', '', '');
		w _PrfGUID GUID profilu ktory synchronizujemy
	********************************************************************************************************************************/
set @_TimeSt_0 = _TimeSt_0, @_PrfGUID = _PrfGUID;
		SET @_PrfGUID.Need.sync = IFNULL((
			SELECT 
				(MAX(p.LastSyncTime) < MAX(IFNULL(pAll.LastSyncTime, _TimeSt_0))) AS NeedSync
			FROM `_sys_usr_profile` p
			-- LEFT JOIN `_sys_usr_profile` pAll ON pAll.GUID = IF(p.Typ = 'COLUMNS', MD5(CONCAT('COLUMNS', p.Id_browser)), IF(p.Typ = 'FILTERS', MD5(CONCAT('FILTERS', p.Id_browser)), MD5(CONCAT('PARAMS', p.Id_browser)))) 
			-- LEFT JOIN `_sys_usr_profile` pAll ON pAll.GUID = MD5(CONCAT(LOWER(SUBSTR(p.Typ, 1, 1)), p.Id_Browser))
			-- LEFT JOIN `_sys_usr_profile` pAll ON pAll.GUID = IF(p.Typ = 'COLUMNS', MD5(CONCAT('COLUMNS', p.Id_Browser)), IF(p.Typ = 'FILTERS', MD5(CONCAT('FILTERS', p.Id_Browser)), IF(p.Typ = 'PARAMS', MD5(CONCAT('PARAMS', p.Id_Browser)), MD5(CONCAT('CUBE', p.Id_Browser))))) 
			-- md5!!! LEFT JOIN `_sys_usr_profile` pAll ON _VarStr(pAll.GUID) = MD5(CONCAT(_VarStr(p.Typ), _VarStr(p.Re_Id)))
			LEFT JOIN `_sys_usr_profile` pAll ON _VarStr(pAll.GUID) = MD5_2(p.Typ, p.Re_Id)
			WHERE
				p.GUID = _PrfGUID
			), 0
			)
		;
		IF @_PrfGUID.Need.sync THEN
		-- synchronizuj
			SET _PrfGUID_SRC = '';
			CALL _sys_usr_profile_utilities('profile.load.from.ALL', _Re_Id, _PrfGUID, _All_PrfGUID, _User, _PrfGUID_SRC, 'not delete', '', '', '');
			UPDATE `_sys_usr_profile` p
			SET 
				p.LastSyncTime = NOW() --  GREATEST(IFNULL((select MAX(pp.ModifyAt) from `_sys_usr_profile_cpf` pp where pp.PrfGUID = p.GUID), p.LastSyncTime), p.LastSyncTime)
			WHERE
				p.GUID = _PrfGUID
			;
		END IF;
	END IF;	--	_MODE = 'profile.syns.with.ALL' 

END
$$


		--	
			DROP FUNCTION IF EXISTS `_GetHashParamList`$$
			CREATE DEFINER=`root`@`localhost` FUNCTION `_GetHashParamList`(
				_MODE VARCHAR(255),
				_InputStr MEDIUMTEXT
			) 
			RETURNS VARCHAR(25500)
				NO SQL
				DETERMINISTIC
			SPROC: BEGIN
			/*
			*/

				IF _InputStr = '' THEN
					RETURN '';
					LEAVE SPROC;
				END IF;
				SET 
					@HashParamList = '',
					@I = 0,
					@Current_Text = _InputStr,
					@X = ''
				;
				SET @ExistHash = ((@Begin_HASH := LOCATE('#', @Current_Text)) > 0);
				WHILE @ExistHash DO
					SET @Current_Param = SUBSTR(@Current_Text, @Begin_HASH + 1, 50000);
					SET @ExistHash = ((@END_HASH := LOCATE('#', @Current_Param)) > 0);
					IF @ExistHash THEN
						SET @Current_Param = SUBSTR(@Current_Param, 1, @END_HASH - 1);
						SET @HashParamList = IF(@HashParamList != '', CONCAT(@HashParamList, ';', @Current_Param), @Current_Param);
						SET @Current_ParamQ = CONCAT('#', @Current_Param, '#');
						SET @Current_Text = REPLACE(@Current_Text, @Current_ParamQ, '');
						SET @ExistHash = ((@Begin_HASH := LOCATE('#', @Current_Text)) > 0);
						
						-- SET @ExistHash = FALSE;
						set @I = @I + 1;
					END IF;
				END WHILE;
					
				
				RETURN @HashParamList;
			END$$

		DROP PROCEDURE IF EXISTS `_PrepareSQLText_with_HashParams`$$
		CREATE DEFINER=`root`@`localhost` PROCEDURE `_PrepareSQLText_with_HashParams`(
			IN _MODE VARCHAR(250),
			INOUT _SQLContent VARCHAR(62000),
			IN _p_Name VARCHAR(250),
			INOUT _f_Value_Down VARCHAR(62000),
			IN _GUID VARCHAR(250),
			OUT _Result VARCHAR(250),
			OUT _ResultMsg VARCHAR(250),
			IN _Param_A VARCHAR(50),
			IN _Param_B VARCHAR(50)	
		)
		/*
		*/

		S_PrepareSQLText_with_HashParams: BEGIN 

			DECLARE _Current_Text MEDIUMTEXT;
			DECLARE _Current_Param, _Current_ParamQ VARCHAR(250);		
			DECLARE _ExistHash BOOLEAN;
			DECLARE _BEGIN_HASH, _END_HASH INTEGER;
			DECLARE _ParamList VARCHAR(250);		--	wartosc docelowa
			DECLARE _PrfGUID_SRC VARCHAR(250);	--	Zrodlowy profil
			DECLARE _sql_text_SELECT MEDIUMTEXT; -- @.sql.text.SELECT
			DECLARE _SQLText, _SQLBuff MEDIUMTEXT;


			IF _MODE = 'init' THEN
				
				/********************************************************************************************************************************
					Temptable
					CALL _PrepareSQLText_with_HashParams('init', @We, '', @_f_Value_Down, _PrfGUID_p, _Result, _ResultMsg, '', '');
					_GUID zawiera _Id_browser				_PrfGUID_p
				********************************************************************************************************************************/
			-- CALL _sys_usr_profile_utilities('get.profil.default.COLUMNS', _Id_browser, _PrfGUID_p, @_All_PrfGUID, _User, '', '', '', '', '');
			-- CALL _PrepareSQLText_with_HashParams('init', @We, '', @_f_Value_Down, _PrfGUID_p, @_Result, @_ResultMsg, '', '');
				--	Nalicz najpierw wartosci parametrow (f_Update_Now = 1)
					UPDATE `v_sys_profile_browser_params` p
					SET
						p.f_UpdateNow = 1
					WHERE 
						p.PrfGUID = _GUID
						AND NOT p.Param_Init_Type IN ('piEditor', 'piFixed') 
					;
					DROP TEMPORARY TABLE IF EXISTS `t_params_setup`;
					CREATE TEMPORARY TABLE `t_params_setup` (
					  `GUID` VARCHAR(38) NOT NULL DEFAULT '',
					  `p_Name` VARCHAR(200) NOT NULL DEFAULT '',
					  `LP` INT(11) NOT NULL DEFAULT '0',
					  `Param_Init_Type` ENUM('piEditor','piCustomSQL','piInitParamSQL','piFixed') NOT NULL DEFAULT 'piEditor',
					  `Param_Init_SQL_GUID` VARCHAR(250) DEFAULT NULL,
					  `f_Value_Down` VARCHAR(250) DEFAULT NULL,
					  `f_sql_Expr` VARCHAR(250) DEFAULT NULL,
					  `_SQLContent` MEDIUMTEXT,
					  `Visit` BOOLEAN DEFAULT FALSE,
					  `OK` BOOLEAN DEFAULT FALSE,
					  PRIMARY KEY (`guid`),
					  UNIQUE KEY `p_Name` (`p_Name`)
					)
					;
					INSERT IGNORE INTO `t_params_setup`
					(GUID, p_Name, LP, Param_Init_Type, f_Value_Down, f_sql_Expr, Param_Init_SQL_GUID, _SQLContent, Visit, OK)
						SELECT 
							p.GUID, p.p_Name, p.LP, p.Param_Init_Type, NULL, p.f_sql_Expr, p.Param_Init_SQL_GUID, s.SQL,
							FALSE AS Visit,
							p.Param_Init_Type IN ('piEditor', 'piFixed') AS OK
						FROM `v_sys_profile_browser_params` p 
						LEFT JOIN `_sys_browsers_sql` s ON s.GUID = p.Param_Init_SQL_GUID
						WHERE 
							p.PrfGUID = _GUID -- 
							AND NOT p.Param_Init_Type IN ('piEditor', 'piFixed') 
					;
					INSERT IGNORE INTO `t_params_setup`
					(GUID, p_Name, LP, Param_Init_Type, f_Value_Down, f_sql_Expr, Param_Init_SQL_GUID, _SQLContent, Visit, OK)
						SELECT 
							p.GUID, p.p_Name, p.LP, p.Param_Init_Type, p.f_Value_Down, p.f_sql_Expr, p.Param_Init_SQL_GUID, s.SQL,
							FALSE AS Visit,
							p.Param_Init_Type IN ('piEditor', 'piFixed') AS OK
						FROM `v_sys_profile_browser_params` p 
						LEFT JOIN `_sys_browsers_sql` s ON s.GUID = p.Param_Init_SQL_GUID
						WHERE 
							p.PrfGUID = _GUID -- 
							AND p.Param_Init_Type IN ('piEditor', 'piFixed') 
					;
			END IF;
			
			IF _MODE = 'Fill.content' THEN
				SET _Result = '', _ResultMsg = '';
				
				IF _SQLContent = '' THEN
					LEAVE S_PrepareSQLText_with_HashParams;
				END IF;
				
				SET 
					_ParamList = '',
					@I = 0,
					_Current_Text = _SQLContent,
					@X = ''
				;
				SET _BEGIN_HASH := LOCATE('#', _Current_Text);
				SET _ExistHash = (_BEGIN_HASH > 0);
				WHILE _ExistHash DO
					SET _Current_Param = SUBSTR(_Current_Text, _BEGIN_HASH + 1, 50000);
					SET _END_HASH := LOCATE('#', _Current_Param);
					SET _ExistHash = (_END_HASH > 0);
					IF _ExistHash THEN
						SET _Current_Param = SUBSTR(_Current_Param, 1, _END_HASH - 1);
						SET _Current_ParamQ = CONCAT('#', _Current_Param, '#');
						SET _ParamList = IF(_ParamList != '', CONCAT(_ParamList, ';', _Current_Param), _Current_Param);
					--	pobierz wartosc	_f_Value_Down
						SET _f_Value_Down = NULL;
	if _Current_Param = 'TABLENAME' THEN
		SET @YYY = concat(@YYY, '', _Current_Param);
	END IF;
						CALL _PrepareSQLText_with_HashParams('Get.ParamValue', @_SQLContent, _Current_Param, _f_Value_Down, '', _Result, _ResultMsg, '', '');
						IF _Result != '' THEN
							LEAVE S_PrepareSQLText_with_HashParams;
						END IF;
						
	if _Current_Param = 'TABLENAME' THEN
		SET @YYY = concat(@YYY, ' wartosc:', IFNULL(_f_Value_Down, 'NULL'));
	END IF;
						
					--	Masz wartość to Zmien _SQLContent
						SET _SQLContent = REPLACE(_SQLContent, _Current_ParamQ, IFNULL(_f_Value_Down, 'NULL'));
						
						SET _Current_Text = REPLACE(_Current_Text, _Current_ParamQ, '');
						SET _BEGIN_HASH := LOCATE('#', _Current_Text);
						SET _ExistHash = (_BEGIN_HASH > 0);
						set @I = @I + 1;
					END IF;
				END WHILE;
				
				set @_ParamList = _ParamList;
				
			END IF;
				
			IF _MODE = 'Get.ParamValue' THEN
				/********************************************************************************************************************************
					Pobranie wartosci parametru _p_Name
					CALL _PrepareSQLText_with_HashParams('Get.ParamValue', @_SQLContent, _Current_Param, _f_Value_Down, '', _Result, _ResultMsg, '', '');
					_p_Name	zawiera nazwe parametru
					zwraca wartosc w _f_Value_Down
				********************************************************************************************************************************/
				SET _Result = '', _ResultMsg = '', _f_Value_Down = NULL;
				if _p_Name = 'TABLENAME' THEN
					SET @XXX = concat(@XXX, 'Wchodze ', IFNULL(_p_Name, 'p_name'));
				END IF;
			--	pobierz wartosc	_f_Value_Down
				SET @pGUID = NULL;	--	sprawdze czy w ogole jest taki rekord - sama wartosc moze byc NULL ale brak rekordu oznacza ze nie ma takiego parametru i wtedy tez Err i exit
				SELECT 
					t.GUID,
					t.f_sql_Expr,
					t._SQLContent,
					t.Visit,
					t.OK
				INTO
					@pGUID, _f_Value_Down, _SQLText, @Visit, @OK
				FROM `t_params_setup` t 
				WHERE
					t.p_Name = _p_Name
				;	
				
				if _p_Name = 'TABLENAME' THEN
					SET @XXX = concat(@XXX, ' -> Select ', IFNULL(_p_Name, 'p_name'), ';', IFNULL(@pGUID, '@pGUID is null'), '; ', IFNULL(_f_Value_Down, '_f_Value_Down = NULL'), '; ', IFNULL(_SQLText, '_SQLText'), '; ', IFNULL(@Visit, '@Visit'), '; ', IFNULL(@OK, '@OK'), '; ');
				END IF;
				
				IF @pGUID IS NULL THEN
				--	w ogole brak takiego rekordu (PARAMETRU) - to oznacza ze nie ma takiego parametru i wtedy tez Err i exit
					SET 	
						_Result = 'Err',
						_ResultMsg = CONCAT('Prak parametru : "#', _p_Name, '#"')
					;
					LEAVE S_PrepareSQLText_with_HashParams;
				END IF;
				
				-- bylo IF (_f_Value_Down IS NULL) AND NOT @OK THEN
				IF NOT @OK THEN
					IF @Visit THEN
						SET 	
							_ExistHash = FALSE,
							_Result = 'Err',
							_ResultMsg = CONCAT('Cirrcular reference - dla: "#', _p_Name, '#"')
						;
						LEAVE S_PrepareSQLText_with_HashParams;
					ELSE
					--	Ustaw ten parametr jako odwiedzamy (gdy w rekursji odwiedzamy parametry które rozpoczely odwiedziny to cirrcular ref. i exit
						CALL _PrepareSQLText_with_HashParams('SET.Visit', _SQLContent, _p_Name, _f_Value_Down, '', _Result, _ResultMsg, 'TRUE', '');
					--	pobierz wypeniona sqlke parametru czyli _SQLText
						CALL _PrepareSQLText_with_HashParams('Fill.content', _SQLText, _p_Name, _f_Value_Down, '', _Result, _ResultMsg, '', '');
						IF _Result != '' THEN
							LEAVE S_PrepareSQLText_with_HashParams;
						END IF;
					--	Ustaw ten parametr jako zakonczenie odwiedzin
						CALL _PrepareSQLText_with_HashParams('SET.Visit', _SQLContent, _p_Name, _f_Value_Down, '', _Result, _ResultMsg, 'FALSE', '');
					--	Teraz mozemy pobrac warosc parametru z _SQLText
						CALL _PrepareSQLText_with_HashParams('Execute.content', _SQLText, _p_Name, _f_Value_Down, '', _Result, _ResultMsg, '', '');
					END IF;
				END IF;
				
			END IF;
			
			IF _MODE = 'Execute.content' THEN
				/********************************************************************************************************************************
					Execute cmd
					CALL _PrepareSQLText_with_HashParams('Execute.content', @_SQLContent, _Current_Param, @_f_Value_Down, '', @_Result, @_ResultMsg, '', '');
					_p_Name	zawiera nazwe parametru
					tytaj dodaj jeszcze INT @_p_Mame
				********************************************************************************************************************************/
				SET _SQLText = _SQLContent;
				IF LOCATE('INTO', _SQLText) = 0 THEN
					IF LOCATE(';', _SQLText) > 0 THEN
						SET _SQLText = REPLACE(_SQLText, ';', ' ');
					END IF;
					SET _SQLText = CONCAT(_SQLText, ' INTO @_f_Value_Down;'); 
				END IF;
				SET @_SQLText = _SQLText;
				CALL _ExecuteCmd(_SQLText, @Error);
			--	zupdatuj `_sys_usr_profile_cpf`
				UPDATE `t_params_setup` t, `_sys_usr_profile_cpf` p 
				SET
					t.OK = TRUE,
					p.f_UpdateNow = 1, 
					p.f_Value_Down = @_f_Value_Down
				WHERE
					t.p_Name = _p_Name
					AND
					p.GUID = t.GUID
				;
			--	zupdatuj `t_params_setup`
				UPDATE `t_params_setup` t, `_sys_usr_profile_cpf` p 
				SET
					t.OK = TRUE,
					t.f_Value_Down = p.f_Value_Down,
					t.f_sql_Expr = p.f_sql_Expr
				WHERE
					t.p_Name = _p_Name
					AND
					p.GUID = t.GUID
				;
				SELECT 
					t.f_sql_Expr
				INTO
					_f_Value_Down
				FROM `t_params_setup` t 
				WHERE
					t.p_Name = _p_Name
				;	
			END IF;
			
			IF _MODE = 'SET.Visit' THEN
				/********************************************************************************************************************************
					Ustawia pole Visit
					CALL _PrepareSQLText_with_HashParams('SET.Visit', _SQLContent, _Current_Param, _f_Value_Down, '', _Result, _ResultMsg, 'TRUE', '');
					CALL _PrepareSQLText_with_HashParams('SET.Visit', _SQLContent, _Current_Param, _f_Value_Down, '', _Result, _ResultMsg, 'FALSE', '');
					_p_Name	zawiera nazwe parametru
					_Param_A	ma TRUE lub FALSE
				********************************************************************************************************************************/
				UPDATE `t_params_setup` 
				SET
					Visit = _Param_A
				WHERE
					p_Name = _p_Name
				;
			END IF;
			
			
			IF _MODE IN ('Execute.Before.After.execute.sql.INIT', 'Execute.Before.After.execute.sql.FINAL') THEN
			/********************************************************************************************************************************
				CALL _PrepareSQLText_with_HashParams('Execute.Before.After.execute.sql.INIT', @nothing, @nothing, @nothing, Id_Browser, @.sql.Err, @.sql.INFO, '', '');
				CALL _PrepareSQLText_with_HashParams('Execute.Before.After.execute.sql.FINAL', @nothing, @nothing, @nothing, Id_Browser, @.sql.Err, @.sql.INFO, '', '');
				w _GUID jest ID_Browser
			********************************************************************************************************************************/
				SET _Result = '', _ResultMsg = '', _f_Value_Down = NULL;
			--	Pętla przetwarzania
				BEGIN
				
					DECLARE done BOOL DEFAULT FALSE;
					DECLARE _SQL_init_final VARCHAR(62000);
				--	Kursor	
					DECLARE c_execute_SQL_init_final CURSOR FOR
						SELECT 
							s.SQL
						FROM `_sys_browsers_sql` s
						WHERE
							s.Id_Browser = _GUID
							AND
							s.Kind = 
								IF(_MODE = 'Execute.Before.After.execute.sql.INIT', 'INIT', 'FINAL')
						;				
					DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				--	3.2 Open Kursor	
					OPEN c_execute_SQL_init_final;
					loop_c_execute_SQL_init_final: LOOP
						FETCH c_execute_SQL_init_final INTO 
							_SQL_init_final
						;
						IF done THEN
							LEAVE loop_c_execute_SQL_init_final;
						END IF;
					--	Uzupelnij sqlke o wart. parametrow o ile sa tam #Para#
						CALL _PrepareSQLText_with_HashParams('Fill.content', _SQL_init_final, '', @_f_Value_Down, '', _Result, _ResultMsg, '', '');
						--	UWAGA te @_Result, @_ResultMsg musze przekazac patrykowi
						IF _Result != '' THEN
							LEAVE loop_c_execute_SQL_init_final;
						END IF;
					--	Wykona SQL-kę
						SET @_SQLText = _SQL_init_final;
						CALL _ExecuteCmd(_SQL_init_final, @Error);
						
					END LOOP;
					CLOSE c_execute_SQL_init_final;
				
				END;
			END IF;
			
			-- for.t_sql.prepare.Fill.ALL.but.Execute.ONLY.Init.Final
			IF _MODE IN ('for.t_sql.prepare.Fill.ALL.but.Execute.ONLY.Init.Final') THEN
			/********************************************************************************************************************************
				CALL _PrepareSQLText_with_HashParams('for.t_sql.prepare.Fill.ALL.but.Execute.ONLY.Init.Final', @nothing, @nothing, @nothing, Id_Browser, @.sql.Err, @.sql.INFO, '', '');
				w _GUID jest ID_Browser
			********************************************************************************************************************************/
				SET _Result = '', _ResultMsg = '', _f_Value_Down = NULL;
			--	Pętla przetwarzania
				BEGIN
				
					DECLARE done BOOL DEFAULT FALSE;
					DECLARE _ID_SECT VARCHAR(38);
					DECLARE _Kind VARCHAR(150);
					DECLARE _SQL_init_final VARCHAR(62000);
				--	Kursor	
					DECLARE c_execute_SQL_init_final CURSOR FOR
						SELECT 
							s.ID_SECT, s.Kind, s.SQLFINAL
						FROM `t_sql.prepare` s
						WHERE
							s._Id_browser = _GUID
							-- AND s.Kind IN ('INIT', 'FINAL')
						;				
					DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
				--	3.2 Open Kursor	
					OPEN c_execute_SQL_init_final;
					loop_c_execute_SQL_init_final: LOOP
						FETCH c_execute_SQL_init_final INTO 
							_ID_SECT,
							_Kind,
							_SQL_init_final
						;
						IF done THEN
							LEAVE loop_c_execute_SQL_init_final;
						END IF;
					--	Uzupelnij sqlke o wart. parametrow o ile sa tam #Para#
						CALL _PrepareSQLText_with_HashParams('Fill.content', _SQL_init_final, '', @_f_Value_Down, '', _Result, _ResultMsg, '', '');
						--	UWAGA te @_Result, @_ResultMsg musze przekazac patrykowi
						IF _Result != '' THEN
							LEAVE loop_c_execute_SQL_init_final;
						END IF;
					--	zwroc SQL ke
						UPDATE `t_sql.prepare` t
						SET
							t.SQLFINAL = _SQL_init_final
						WHERE
							t.ID_SECT = _ID_SECT
						;
					
					--	Wykonaj SQL-kę
						IF _Kind IN ('INIT', 'FINAL') THEN
							SET @_SQLText = _SQL_init_final;
							CALL _ExecuteCmd(_SQL_init_final, @Error);
						END IF;
						
					END LOOP;
					CLOSE c_execute_SQL_init_final;
				
				END;
			END IF;
			
		END$$

		
		DROP PROCEDURE IF EXISTS `_PrepareSQLText`$$
		CREATE DEFINER=`root`@`localhost` PROCEDURE `_PrepareSQLText`(
			IN _MODE VARCHAR(250),
			IN _Id_browser VARCHAR(50),	
			-- IN _User VARCHAR(50),	
			IN _ID_SQL VARCHAR(50),	
			IN _Context VARCHAR(50),	
			INOUT _SQL MEDIUMTEXT,
			IN _Limit VARCHAR(250),	
			IN _Param_A VARCHAR(50),	
			IN _Param_B VARCHAR(50),
			IN _Param_C VARCHAR(50)	
		)
		/*
		*/

		S_PrepareSQLText: BEGIN 

			DECLARE _PrfGUID_c, _PrfGUID_f, _PrfGUID_p, _PrfGUID_d VARCHAR(38);
			DECLARE _Kind VARCHAR(200);
			DECLARE _sql_text_SELECT MEDIUMTEXT; -- @.sql.text.SELECT
			DECLARE _SQLText MEDIUMTEXT;
			SET @@group_concat_max_len = 1024*1024;
			
							IF _MODE = 'SQL.PREPARE.t_sql.prepare' THEN
								DROP TEMPORARY TABLE IF EXISTS `t_sql.prepare`;
								CREATE TEMPORARY TABLE `t_sql.prepare` (
									`ID_SECT` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
									`Kind` VARCHAR(150) NOT NULL DEFAULT '' COMMENT 'Kind z sql',
									`Context` VARCHAR(150) NOT NULL DEFAULT 'select' COMMENT 'np. information_schema',
									`_Id_browser` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz browsera',
									`SQL.Body` MEDIUMTEXT COMMENT 'Sam select',
									`SQL.Body.MaxTime` MEDIUMTEXT COMMENT 'Sam select',
									`SQL.Body.Key` MEDIUMTEXT COMMENT 'Sam select',
									`SQL.Body.Schema` MEDIUMTEXT COMMENT 'Sam select',
									`SQL.Exe` MEDIUMTEXT COMMENT 'Zwykly select / call',
									`SQL.Exe.Temporary` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary.Check` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary.Check` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary.maxtime` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary.maxtime` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary.key` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary.key` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary.information_schema` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary.information_schema` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.DROP.Temporary.TAGS` MEDIUMTEXT COMMENT 'temporarka',
									`SQL.CREATE.Temporary.TAGS` MEDIUMTEXT COMMENT 'temporarka',

									`SQLINIT` MEDIUMTEXT COMMENT 'WHERE',
									`SQLFINAL` MEDIUMTEXT COMMENT 'WHERE',
									`SELECT` MEDIUMTEXT COMMENT 'SELECT',
									`SELECT.AGG` MEDIUMTEXT COMMENT 'SELECT.AGG',
									`FROM` MEDIUMTEXT COMMENT 'FROM',
									`JOIN` MEDIUMTEXT COMMENT 'JOIN',
									`WHERE` MEDIUMTEXT COMMENT 'WHERE',
									`WHERE.P` MEDIUMTEXT COMMENT 'WHERE',
									`WHERE.S` MEDIUMTEXT COMMENT 'WHERE',
									`WHERE.MaxTime` MEDIUMTEXT COMMENT 'WHERE',
									`WHERE.Key` MEDIUMTEXT COMMENT 'WHERE',
									`HAVING` MEDIUMTEXT COMMENT 'HAVING',
									`HAVING.P` MEDIUMTEXT COMMENT 'HAVING',
									`HAVING.S` MEDIUMTEXT COMMENT 'HAVING',
									`GROUP` MEDIUMTEXT COMMENT 'GROUP',
									`GROUP.P` MEDIUMTEXT COMMENT 'GROUP',
									`GROUP.S` MEDIUMTEXT COMMENT 'GROUP',
									`ORDER` MEDIUMTEXT COMMENT 'GROUP',
									`LIMIT` MEDIUMTEXT COMMENT 'LIMIT',
									`_Limit` MEDIUMTEXT COMMENT 'LIMIT wejsciowy',
									`temptable.name` VARCHAR(250) NOT NULL DEFAULT '',
									`temptable.name.check` VARCHAR(250) NOT NULL DEFAULT '',
									`temptable.name.maxtime` VARCHAR(250) NOT NULL DEFAULT '',
									`temptable.name.key` VARCHAR(250) NOT NULL DEFAULT '',
									`temptable.name.information_schema` VARCHAR(250) NOT NULL DEFAULT '',
									`temptable.name.TAGS` VARCHAR(250) NOT NULL DEFAULT '',
									
								--	Pole Key
									`Key_FieldName` VARCHAR(250) NOT NULL DEFAULT '',
									`Key_FieldValue` VARCHAR(250) NOT NULL DEFAULT '',
								--	Pole Localtime 	
									`LocalTime_FieldName` VARCHAR(250) NOT NULL DEFAULT '',
									`LocalTime_FieldValue` VARCHAR(250) NOT NULL DEFAULT '',

									
									`_Param_DEFAULT_WHERE` VARCHAR(150) NOT NULL DEFAULT '',
									`_Param_A` VARCHAR(150) NOT NULL DEFAULT '',
									`_Param_B` VARCHAR(150) NOT NULL DEFAULT '',
									`_Param_C` VARCHAR(150) NOT NULL DEFAULT '',
									`_Param_D` VARCHAR(150) NOT NULL DEFAULT '',
									`_Param_E` VARCHAR(150) NOT NULL DEFAULT '',
									`Is_SQL` BOOLEAN DEFAULT FALSE,
									`Is_information_schema` BOOLEAN DEFAULT FALSE,
									PRIMARY KEY (`ID_SECT`)
								);
							END IF;
			
			IF _MODE LIKE 'SQL.PREPARE.%' THEN
			
				IF _MODE = 'SQL.PREPARE.INIT' THEN
				/********************************************************************************************************************************
					Inicjuje
					CALL _PrepareSQLText('SQL.PREPARE.INIT', 'crm_by_call', '', '_Context', @SQL, '', '', '', '');
					np.
						CALL _PrepareSQLText('SQL.PREPARE.INIT', 'crm_by_call', '', '', @SQL, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.INIT', 'crm_by_call', '', 'information_schema', @SQL, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.INIT', 'crm_by_call', '', 'maxtime', @SQL, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.INIT', 'crm_by_call', '', 'key', @SQL, '', '', '', '');
				********************************************************************************************************************************/
					SET _Context = IF(IFNULL(_Context, '') = '', 'select', _Context);
					IF _Context = 'information_schema' THEN	--	information_schema
						CALL sys_browsers_tools('sqltext.init.by.system', _Id_browser, '', '', '', '', '', '', '');
					ELSE
						CALL sys_browsers_tools('sqltext.init.by.profil', _Id_browser, '', '', '', '', '', '', '');
					END IF;
					--	do @.Prf.GUID wpisywany jest GUID profilu
					CALL _PrepareSQLText('SQL.PREPARE.t_sql.prepare', '', '', '', @SQL, '', '', '', '');
					
					TRUNCATE `t_sql.prepare`;
				END IF;
				
				IF _MODE LIKE 'SQL.PREPARE.ADDSQL.%' THEN
				/********************************************************************************************************************************
					Wstawia SQL-ki
					CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', 'crm_by_call', 'Id_SQL', 'select', @sql.text.MAIN, '', '', '', '');
					CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.INIT.FINAL', 'crm_by_call', 'Id_SQL', 'select', @sql.text.MAIN, '', '', '', '');
					CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.ANY', 'crm_by_call', 'Id_SQL', 'select', @sql.text.template.check.count, '', '', '', '');
				********************************************************************************************************************************/
					set @.trace.X = '!!!!!!!!!!!!!wew.ADDSQL';
					IF _MODE = 'SQL.PREPARE.ADDSQL.INIT.FINAL' THEN
						SET @ID_SQL = 0;
						INSERT IGNORE INTO `t_sql.prepare`
						-- (ID_SECT, Kind, Context, _Id_browser, SQLINIT, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E)
						(ID_SECT, Kind, Context, _Id_browser, SQLINIT, `_Limit`)
							SELECT 
								s.GUID, s.Kind, _Context, _Id_browser, s.SQL, _Limit
							FROM `_sys_browsers_sql` s
							WHERE
								s.Id_browser = _Id_browser
								AND s.Kind IN ('INIT', 'FINAL')
								AND NOT s.Deleted
						;
					ELSE
						IF _MODE = 'SQL.PREPARE.ADDSQL.MAIN' THEN
					set @.trace.X = 'C3.5';
							SET 
								_ID_SQL = 'MAIN',
								_Kind = 'MAIN'
							;
						--	Mimo wszystko moze być wołanie w stylu ,
						--	CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', 'crm_by_call', 'Id_SQL', 'select', @sql.text.MAIN := '', '', '', '', '');
						--	zatem pobierz wtedy sqlke
						--	dodaj sql-ke np. glowna
							IF IFNULL(_SQL, '')  = '' THEN
					set @.trace.X = 'C3.6';
								SELECT
									s.SQL
								INTO
									_SQL
								FROM `_sys_browsers_sql` s
								WHERE
									s.Id_browser = _Id_browser
									AND NOT s.Deleted
									AND s.Kind = 'MAIN'
								LIMIT 1
								;
					set @.trace.X = 'C3.7';
							END IF;
							SET 
								_SQL = 
									IF(IFNULL(_SQL, '')  = '', 
										"SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n-- EXT1\n-- EXT2\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n", 
										_SQL
									)
							;
					set @.trace.X = 'C3.8';
							
						ELSE
							SET _Kind = '?';
						END IF;
					--	WSTAW	
						REPLACE `t_sql.prepare`
						-- (ID_SECT, Kind, `Context`, _Id_browser, SQLINIT, _Param_A, _Param_B, _Param_C, _Param_D, _Param_E)
						(ID_SECT, Kind, `Context`, _Id_browser, SQLINIT, _Limit)
							SELECT 
								_ID_SQL, _Kind, _Context, _Id_browser, _SQL, _Limit
						;
					END IF;
					
					UPDATE `t_sql.prepare` t
					SET 
						-- t.Context = _Param_B,
						t.Is_SQL = LOCATE('SELECT', SQLINIT) + LOCATE('CALL', SQLINIT) > 0,
						t.Is_information_schema = (Context = 'information_schema'),
						t.SQLFINAL = t.SQLINIT
					;
					UPDATE `t_sql.prepare` t
					SET 
						_Param_DEFAULT_WHERE = IF(t.Is_information_schema, 'FALSE', t._Param_DEFAULT_WHERE)	--	dla Is_information_schema zawsze 'FALSE'
					;
				--	Pole Key
					UPDATE `t_sql.prepare` t
					SET 
						t.`WHERE.Key` = '',
						t.Key_FieldName = IFNULL(
							(
								SELECT
									c.sql_colref
								FROM `tx_sys_browsers_col` c
								WHERE
									c.IsKey
									AND NOT c.Deleted
								LIMIT 1
							)
						, '')
					;
				--	Pole Localtime 	
					UPDATE `t_sql.prepare` t
					SET 
						t.`WHERE.MaxTime` = '',
						t.LocalTime_FieldName = IFNULL(
							(
								SELECT
									c.sql_colref
								FROM `tx_sys_browsers_col` c
								WHERE
									c.IsLocalTime
									AND NOT c.Deleted
								LIMIT 1
							)
						, '')
					;
				END IF;	--	IF _MODE LIKE 'SQL.PREPARE.ADDSQL.%' THEN
				
				IF _MODE = 'SQL.PREPARE.GET' THEN
				/********************************************************************************************************************************
					Wstawia i uzupelnia
					CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'Id_SQL', '', @sql, '', '', '', '');
					np.
						CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'check.count', '', @sql, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'MAIN', '', @sql, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'hhhdfghdhgh', '', @sql, '', '', '', '');
					
				********************************************************************************************************************************/
					SET @sql.text.GET = 
						IFNULL(
						(SELECT t.SQLFINAL FROM `t_sql.prepare` t WHERE t.ID_SECT = _Id_SQL LIMIT 1)
						, _SQL
						)
					;
					SET _SQL = @sql.text.GET;
				END IF;
				
				IF _MODE LIKE 'sqltext.init.by.profil%' THEN
				/********************************************************************************************************************************
					Wstawia i uzupelnia
					CALL _PrepareSQLText('SQL.PREPARE.PARSE.WHERE.HAVING...', 'crm_by_call', '', '', @sql, '', '', '', '');
				********************************************************************************************************************************/
					IF _MODE = 'SQL.PREPARE.PARSE.WHERE.HAVING...' THEN
					
					
					--	WHERE	
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE.S` = 
							IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\nAND "), '\nTRUE') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = t._Id_browser
									AND (s.Kind LIKE '%where%')
									AND s.Deleted = 0
							), '')
						WHERE
							t.Is_SQL
						;
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE.P` = 
							IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR "\nAND "), '') AS C_SQLExpr
								FROM `tx_sys_browsers_filters` f 
								WHERE
									f.Included
									AND f.Kind = 'WHERE' 
									AND f.Filter_Active
							), '')
						WHERE
							t.Is_SQL
						;
						
				--	Pole Key
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE.Key` = 
							IFNULL(
								CONCAT('(', t.Key_FieldName, ' = ', QUOTE(t.Key_FieldValue), ')')
							, '')
						WHERE
							t.Is_SQL
							AND
							t.Key_FieldName <> ''
							AND
							t.Key_FieldValue <> ''
						;
				--	Pole Localtime 	
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE.MaxTime` = 
							IFNULL(
								CONCAT('(', t.LocalTime_FieldName, ' = ', QUOTE(t.LocalTime_FieldValue), ')')
							, '')
						WHERE
							t.Is_SQL
							AND
							t.LocalTime_FieldName <> ''
							AND
							t.LocalTime_FieldValue <> ''
						;

						/*
						bylo ...
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE` = 
								IF(t.Context IN ('select', ''),
									_ConcatSTR2(t.`WHERE.S`, t.`WHERE.P`, "\nAND "),
									IF(t.Context IN ('maxtime', 'key', 'information_schema'),
										_ConcatSTR2(t.`WHERE.S`, t._Param_DEFAULT_WHERE, "\nAND "),
										t.`WHERE`
									)
								)
						WHERE
							t.Is_SQL
						;
						... jest */
						UPDATE `t_sql.prepare` t
						SET
							t.`WHERE` = 
								_ConcatSTR2(t.`WHERE.S`, t.`WHERE.P`, "\nAND ")
						WHERE
							t.Is_SQL
						;
						
					--	HAVING
						UPDATE `t_sql.prepare` t
						SET
							t.`HAVING.S` = (
								SELECT 
									IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR " AND "), '') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = t._Id_browser
									AND (s.Kind LIKE '%having%')
									AND s.Deleted = 0
							)
						WHERE
							t.Is_SQL
						;
						UPDATE `t_sql.prepare` t
						SET
							t.`HAVING.P` = (
								SELECT 
									IFNULL(GROUP_CONCAT(f.Filter_FilterExpr ORDER BY f.LP SEPARATOR " AND "), '') AS C_SQLExpr
								FROM `tx_sys_browsers_filters` f 
								WHERE
									f.Included
									AND f.Kind = 'HAVING' 
									AND f.Filter_Active
							)
						WHERE
							t.Is_SQL
						;
						UPDATE `t_sql.prepare` t
						SET
							t.`HAVING` = 
									_ConcatSTR2(t.`HAVING.S`, t.`HAVING.P`, " AND ")
						WHERE
							t.Is_SQL
						;

						UPDATE `t_sql.prepare` t
						SET
							t.SQLFINAL = 
								REPLACE(REPLACE(t.SQLFINAL, "[WHERE]", t.`WHERE`), "[HAVING]", IF(t.`HAVING` != '', CONCAT("\nHAVING \n", t.`HAVING`), ''))
						WHERE
							t.Is_SQL
						;
					END IF;
					LEAVE S_PrepareSQLText;
				END IF;
				
				
				IF _MODE = 'SQL.PREPARE.FILL.main.SQL' THEN
				/********************************************************************************************************************************
					Wstawia i uzupelnia
					CALL _PrepareSQLText('SQL.PREPARE.FILL.main.SQL', 'crm_by_call', '', 'context', @sql, '', '', '', '');
					np.
						CALL _PrepareSQLText('SQL.PREPARE.FILL.main.SQL', 'crm_by_call', '', 'information_schema', @sql, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'MAIN', '', @sql, '', '', '', '');
						CALL _PrepareSQLText('SQL.PREPARE.GET', 'crm_by_call', 'hhhdfghdhgh', '', @sql, '', '', '', '');
					
				********************************************************************************************************************************/
					set @.trace.X = 'FILL.main.SQL.1';
					DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect`; 
					CREATE TEMPORARY TABLE `tx_sys_browsers_sect` 
						SELECT
							s.*,
							_VarInt(
								!(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%') 
								OR
								s.AlwaysIncluded
							) AS Included
						FROM `_sys_browsers_sect` s
						WHERE
							s.Id_browser = _Id_browser
							AND NOT s.Deleted
					;	
					DROP TEMPORARY TABLE IF EXISTS `tx_sys_browsers_sect_need`; 
					CREATE TEMPORARY TABLE `tx_sys_browsers_sect_need` (
					  `Source_sect` VARCHAR(38) NOT NULL DEFAULT '' COMMENT 'Klucz glowny',
					   PRIMARY KEY (`Source_sect`)
					)
					;
					set @.trace.X = 'FILL.main.SQL.3';
					INSERT IGNORE INTO `tx_sys_browsers_sect_need`
						SELECT
							n.Source_sect
						FROM `tx_sys_browsers_col` c, `_sys_browsers_sect_need` n, `_sys_browsers_sect` s
						WHERE
							c.Included
							AND 
							n.GUID = c.def_c_GUID
							AND
							s.GUID = n.Source_sect
							AND
							NOT s.Deleted
					;	
					UPDATE `tx_sys_browsers_sect` s
					SET
						s.Included = EXISTS(SELECT n.Source_sect FROM `tx_sys_browsers_sect_need` n WHERE s.GUID = n.Source_sect)
					WHERE
						(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%' OR s.Kind LIKE '%from%') 
						AND !s.Included
					;
					INSERT IGNORE INTO `tx_sys_browsers_sect_need`
						SELECT
							n.Source_sect
						FROM `tx_sys_browsers_sect` t, `_sys_browsers_sect_need` n, `_sys_browsers_sect` s
						WHERE
							t.Included
							AND 
							n.GUID = t.GUID
							AND
							s.GUID = n.Source_sect
							AND
							NOT s.Deleted
					;	
					set @.trace.X = 'FILL.main.SQL.7';
					UPDATE `tx_sys_browsers_sect` s
					SET
						s.Included = EXISTS(SELECT n.Source_sect FROM `tx_sys_browsers_sect_need` n WHERE s.GUID = n.Source_sect)
					WHERE
						(s.Kind LIKE '%inner%' OR s.Kind LIKE '%left%' OR s.Kind LIKE '%from%') 
						AND !s.Included
					;

				--	Inicjalnie	
					SET @sql.text.CCCCCCCCCCC = '???????';
					SET @sql.text.template = '';
					set @.trace.X = 'FILL.main.SQL........ADDSQL.MAIN';
 					CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', _Id_browser, '', _Context, @sql.text.template, _Limit, '', '', '');
					set @.trace.X = 'FILL.main.SQL....?????';
					
					SET @sql.text.CCCCCCCCCCC = 'XXXXXXXXXXXX';
					/*
					SET @sql.text.template = "SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n-- EXT1\n-- EXT2\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n";
					SELECT
						s.SQL
					FROM `_sys_browsers_sql` s
					WHERE
						s.Id_browser = _Id_browser
						AND NOT s.Deleted
						AND s.Kind = 'MAIN'
					LIMIT 1
					INTO 
						@sql.text.template
					;
					*/
					
					SET @sql.text.CCCCCCCCCCC = '0';
					SET @sql.text = @sql.text.template;
					SET @sql.text.AAAAAAAAAAA = @sql.text.template;
				--	SELECT	
					SELECT 
						IFNULL(GROUP_CONCAT(c.sql_colref_AS ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AS
					INTO
						@.sql.text.SELECT
					FROM `tx_sys_browsers_col` c
					WHERE
						c.Included
					-- JMAM!!! GROUP BY c.Id_browser
					;
					
					--	SELECT
						UPDATE `t_sql.prepare` t
						SET
							t.`SELECT` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(c.sql_colref_AS ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AS
								FROM `tx_sys_browsers_col` c
								WHERE
									c.Included
							), '')
						WHERE
							t.Is_SQL
						;
					--	SELECT AGG
						UPDATE `t_sql.prepare` t
						SET
							t.`SELECT.AGG` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(c.sql_colref_AggFooter ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AggFooter
								FROM `tx_sys_browsers_col` c
								WHERE
									c.Included
									AND
									c.AggFooterType != 'atNone'
							), '')
						WHERE
							t.Is_SQL
						;
					
					set @.trace.X = 'FILL.main.SQL.8';

				--	SELECT.Agg
					SELECT 
						IFNULL(GROUP_CONCAT(c.sql_colref_AggFooter ORDER BY c.LP SEPARATOR ",\n"), '') AS sql_colref_AggFooter
					INTO
						@.sql.text.SELECT.AGG
					FROM `tx_sys_browsers_col` c
					WHERE
						c.Included
						AND
						c.AggFooterType != 'atNone'
					-- JMAM!!! GROUP BY c.Id_browser
					;

					--	FROM
						UPDATE `t_sql.prepare` t
						SET
							t.`FROM` = IFNULL(
							(
								SELECT 
									IFNULL(s.sql_Expr, '') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = _Id_browser
									AND s.Kind LIKE '%from%'
								ORDER BY s.LP
								LIMIT 1
							), '')
						WHERE
							t.Is_SQL
						;
				--	FROM
					SELECT 
						IFNULL(s.sql_Expr, '') AS C_SQLExpr
					INTO
						@.sql.text.FROM
					FROM `_sys_browsers_sect` s
					WHERE
						s.Id_browser = _Id_browser
						AND s.Kind LIKE '%from%'
					ORDER BY s.LP
					LIMIT 1
					;
					
					--	JOINy
						UPDATE `t_sql.prepare` t
						SET
							t.`JOIN` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\n"), '') AS C_SQLExpr
								FROM `tx_sys_browsers_sect` s
								WHERE
									s.Included
									AND (s.Kind LIKE '%left%') OR (s.Kind LIKE '%inner%')
							), '')
						WHERE
							t.Is_SQL
						;
				--	JOINy
					SELECT 
						IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR "\n"), '') AS C_SQLExpr
					INTO
						@.sql.text.JOIN
					FROM `tx_sys_browsers_sect` s
					WHERE
						s.Included
						AND (s.Kind LIKE '%left%') OR (s.Kind LIKE '%inner%')
					;
					SET @sql.text.MAIN = @sql.text.template;
					
					CALL _PrepareSQLText('SQL.PREPARE.PARSE.WHERE.HAVING...', _Id_browser, '', _Context, @sql.text.template, '', '', '', '');
					CALL _PrepareSQLText('SQL.PREPARE.GET', _Id_browser, 'MAIN', _Context, @sql.text.template, '', '', '', '');
					-- SET @sql.text.C = @sql.text.template;
					
					
					--	GROUP.S
						UPDATE `t_sql.prepare` t
						SET
							t.`GROUP.S` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = _Id_browser
									AND (s.Kind LIKE '%GROUP%')
							), '')
						WHERE
							t.Is_SQL
						;
				--	GROUP
					SELECT 
						IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
					INTO
						@.sql.text.GROUP.S
					FROM `_sys_browsers_sect` s
					WHERE
						s.Id_browser = _Id_browser
						AND (s.Kind LIKE '%GROUP%')
					;
					--	GROUP.P
						UPDATE `t_sql.prepare` t
						SET
							t.`GROUP.P` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(IF(IFNULL(c.GROUP_BY_Expr, '') != '', c.GROUP_BY_Expr, IF(IFNULL(c.col_NameAS, '') != '', c.col_NameAS, IF(IFNULL(c.col_Name, '') != '', c.col_Name, ''))) ORDER BY c.LP SEPARATOR ", "), '') AS C_SQLExpr
								FROM `tx_sys_browsers_col` c
								WHERE
									c.Included
									AND c.GROUP_BY_Ord > -1
							), '')
						WHERE
							t.Is_SQL
						;
					SELECT 
						IFNULL(GROUP_CONCAT(IF(IFNULL(c.GROUP_BY_Expr, '') != '', c.GROUP_BY_Expr, IF(IFNULL(c.col_NameAS, '') != '', c.col_NameAS, IF(IFNULL(c.col_Name, '') != '', c.col_Name, ''))) ORDER BY c.LP SEPARATOR ", "), '') AS C_SQLExpr
					INTO
						@.sql.text.GROUP.P
					FROM `tx_sys_browsers_col` c
					WHERE
						c.Included
						AND c.GROUP_BY_Ord > -1
					;
					--	GROUP
						UPDATE `t_sql.prepare` t
						SET
							t.`GROUP` = IFNULL(
							(
								_ConcatSTR2(t.`GROUP.S`, t.`GROUP.P`, ", ")
							), '')
						WHERE
							t.Is_SQL
						;
					
					SET @.sql.text.GROUP = _ConcatSTR2(@.sql.text.GROUP.S, @.sql.text.GROUP.P, ", ");
					
					--	ORDER
						UPDATE `t_sql.prepare` t
						SET
							t.`ORDER` = IFNULL(
							(
								SELECT 
									IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = _Id_browser
									AND (s.Kind LIKE '%ORDER%')
							), '')
						WHERE
							t.Is_SQL
						;
				--	ORDER
					SELECT 
						IFNULL(GROUP_CONCAT(s.sql_Expr ORDER BY s.LP SEPARATOR ", "), '') AS C_SQLExpr
					INTO
						@.sql.text.ORDER
					FROM `_sys_browsers_sect` s
					WHERE
						s.Id_browser = _Id_browser
						AND (s.Kind LIKE '%ORDER%')
					;
					
					--	LIMIT
						UPDATE `t_sql.prepare` t
						SET
							t.`LIMIT` = IFNULL(
							(
								SELECT 
									IFNULL(s.sql_Expr, '') AS C_SQLExpr
								FROM `_sys_browsers_sect` s
								WHERE
									s.Id_browser = _Id_browser
									AND s.Kind LIKE '%limit%'
								ORDER BY s.LP
								LIMIT 1
							), '')
						WHERE
							t.Is_SQL
						;
						UPDATE `t_sql.prepare` t
						SET
							t.`LIMIT` = 
								IF(t.Context IN ('select', ''),
								--	normalne selecty
									UPPER(
										IF(t.`LIMIT` != '', 
											t.`LIMIT`, 
											IF(Locate('Limit', t._Limit) > 0, 
												t._Limit, 
												IF(t._Limit != '', 
													CONCAT('LIMIT ', t._Limit), 
													''
												)
											)
										)
									),
								--	Maxtime, schema etc	
									''
								)
						WHERE
							t.Is_SQL
						;
				--	LIMIT
					SET @.sql.text.LIMIT = '';
					SELECT 
						IFNULL(s.sql_Expr, '') AS C_SQLExpr
					INTO
						@.sql.text.LIMIT
					FROM `_sys_browsers_sect` s
					WHERE
						s.Id_browser = _Id_browser
						AND s.Kind LIKE '%limit%'
					ORDER BY s.LP
					LIMIT 1
					;
					
					--	SELECT 
						UPDATE `t_sql.prepare` t
						SET
							t.`SQL.Body` = 
								REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(t.`SQLINIT`, 
									"[SELECT]", t.SELECT),
									"[FROM]", t.FROM),
									"[JOIN]", t.JOIN),
									-- "[WHERE]", t.WHERE), -- nizej jest
									"[GROUP]", IF(t.GROUP != '', CONCAT("\nGROUP BY ", t.GROUP), '')),
									"[HAVING]", IF(t.HAVING != '', CONCAT("\nHAVING \n", t.HAVING), '')),
									"[ORDER]", IF(t.ORDER != '', CONCAT("\nORDER BY ", t.ORDER), ''))
						WHERE
							t.Is_SQL
						;
						UPDATE `t_sql.prepare` t
						SET
							t.`SQL.Body` = t.`SQL.Body`
						;


									
						
					--	SELECT  LIMIT, WHERE etc
						UPDATE `t_sql.prepare` t
						SET
							t.`SQL.Body.MaxTime` =
								REPLACE(REPLACE(REPLACE(REPLACE(t.`SQL.Body`, 
									"[WHERE]", _ConcatSTR2(t.`WHERE`, t.`WHERE.MaxTime`, "\nAND ")),
									"-- EXT1", CONCAT(', (', IF(t.`WHERE.P` != '', t.`WHERE.P`, 'TRUE'),') AS REC_OK ')),
									"[LIMIT]", ''),
									"[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS'),
									
							t.`SQL.Body.Key` =
								REPLACE(REPLACE(REPLACE(REPLACE(t.`SQL.Body`, 
									"[WHERE]", _ConcatSTR2(t.`WHERE`, t.`WHERE.Key`, "\nAND ")),
									"-- EXT1", CONCAT(', (', IF(t.`WHERE.P` != '', t.`WHERE.P`, 'TRUE'),') AS REC_OK ')),
									"[LIMIT]", ''),
									"[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS'),
									
							t.`SQL.Body.Schema` =
								REPLACE(REPLACE(REPLACE(t.`SQL.Body`, 
									"[WHERE]", 'FALSE'),
									"[LIMIT]", ''),
									"[SQL_CALC_FOUND_ROWS]", ''),

							t.`SQL.Body` = 
								REPLACE(REPLACE(REPLACE(t.`SQL.Body`, 
									"[WHERE]", _ConcatSTR2(t.`WHERE`, 'TRUE', "\nAND ")),
									"[LIMIT]", IF(t.LIMIT <> '', CONCAT('\n', t.LIMIT), '')),
									"[SQL_CALC_FOUND_ROWS]", '')
						WHERE
							t.Is_SQL
						;
						
						SET 
							@SYSTEM.Client.Session.GUID = IFNULL(@SYSTEM.Client.Session.GUID, '');
						SET
							-- md5!!! @t.temptable.md5 = MD5(CONCAT(_Id_browser, @SYSTEM.Client.Session.GUID))
							@t.temptable.md5 = MD5_2(_Id_browser, @SYSTEM.Client.Session.GUID)
						;
						/*
		SET @t.temptable.name = CONCAT('`t_', @t.temptable.md5, '`');
		SET @t.temptable.name.check = CONCAT('`t_check_', @t.temptable.md5, '`');
		SET @t.temptable.name.maxtime = CONCAT('`t_maxtime_', @t.temptable.md5, '`');
		SET @t.temptable.name.key = CONCAT('`t_key_', @t.temptable.md5, '`');
		SET @t.temptable.name.information_schema = CONCAT('`t_information_schema_', @t.temptable.md5, '`');
		SET @t.temptable.name.TAGS = CONCAT('`t_TAGS_', @t.temptable.md5, '`');
						*/
						UPDATE `t_sql.prepare` t
						SET
							t.`temptable.name` = CONCAT('t_', @t.temptable.md5, ''),
							t.`temptable.name.check` = CONCAT('t_check_', @t.temptable.md5, ''),
							t.`temptable.name.maxtime` = CONCAT('t_maxtime_', @t.temptable.md5, ''),
							t.`temptable.name.key` = CONCAT('t_key_', @t.temptable.md5, ''),
							t.`temptable.name.information_schema` = CONCAT('t_information_schema_', @t.temptable.md5, ''),
							t.`temptable.name.TAGS` = CONCAT('t_TAGS_', @t.temptable.md5, '')
						;
						
						UPDATE `t_sql.prepare` t
						SET
							t.`SQL.Exe` = t.`SQL.Body`,
							
							t.`SQL.Exe.Temporary` = 
								REPLACE('SELECT * FROM `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name`),
									
							t.`SQL.DROP.Temporary` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name`),
							t.`SQL.CREATE.Temporary` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name`),
									'#SQL.Body#', t.`SQL.Body`),
									
							t.`SQL.DROP.Temporary.Check` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name.check`),
							t.`SQL.CREATE.Temporary.Check` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name.check`),
									'#SQL.Body#', t.`SQL.Body`),
									
							t.`SQL.DROP.Temporary.maxtime` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name.maxtime`),
							t.`SQL.CREATE.Temporary.maxtime` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name.maxtime`),
									'#SQL.Body#', t.`SQL.Body`),
									
							t.`SQL.DROP.Temporary.key` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name.key`),
							t.`SQL.CREATE.Temporary.key` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name.key`),
									'#SQL.Body#', t.`SQL.Body`),
									
							t.`SQL.DROP.Temporary.information_schema` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name.information_schema`),
							t.`SQL.CREATE.Temporary.information_schema` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name.information_schema`),
									'#SQL.Body#', t.`SQL.Body`),
									
							t.`SQL.DROP.Temporary.TAGS` = 
								REPLACE('DROP TEMPORARY TABLE IF EXISTS `#temptable.name#`;',
									'#temptable.name#', t.`temptable.name.TAGS`),
							t.`SQL.CREATE.Temporary.TAGS` = 
								REPLACE(REPLACE('CREATE TEMPORARY TABLE `#temptable.name#` \n#SQL.Body#',
									'#temptable.name#', t.`temptable.name.TAGS`),
									'#SQL.Body#', t.`SQL.Body`)
									
						;
					/*	
					  `SQL.Body` MEDIUMTEXT COMMENT 'Sam select',
					  `SQL.Exe` MEDIUMTEXT COMMENT 'Zwykly select / call',
					  `SQL.Exe.DROP.Temporary` MEDIUMTEXT COMMENT 'temporarka',
					  `SQL.Exe.CREATE.Temporary` MEDIUMTEXT COMMENT 'temporarka',
					  `SQL.Exe.DROP.Temporary.Check` MEDIUMTEXT COMMENT 'temporarka',
					  `SQL.Exe.CREATE.Temporary.Check` MEDIUMTEXT COMMENT 'temporarka',
					*/	
					SET @sql.text.template = REPLACE(@sql.text.template, "[SELECT]", @.sql.text.SELECT);
					SET @sql.text.template = REPLACE(@sql.text.template, "[FROM]", @.sql.text.FROM);
					SET @sql.text.template = REPLACE(@sql.text.template, "[JOIN]", @.sql.text.JOIN);
					SET @sql.text.template = REPLACE(@sql.text.template, "[WHERE]", @.sql.text.WHERE);
					SET @sql.text.template = REPLACE(@sql.text.template, "[HAVING]", IF(@.sql.text.HAVING != '', CONCAT("\nHAVING \n", @.sql.text.HAVING), ''));
					SET @sql.text.template = REPLACE(@sql.text.template, "[GROUP]", IF(@.sql.text.GROUP != '', CONCAT("\nGROUP BY ", @.sql.text.GROUP), ''));
					SET @sql.text.template = REPLACE(@sql.text.template, "[ORDER]", IF(@.sql.text.ORDER != '', CONCAT("\nORDER BY ", @.sql.text.ORDER), ''));
					
					SET @.sql.text.LIMIT = UPPER(IF(@.sql.text.LIMIT != '', @.sql.text.LIMIT, IF(Locate('Limit', _Limit) > 0, _Limit, IF(_Limit != '', CONCAT('LIMIT ', _Limit), ''))));
					--	"SELECT[SQL_CALC_FOUND_ROWS]\n[SELECT]\n[FROM]\n[JOIN]\nWHERE\n[WHERE][GROUP][HAVING][ORDER][LIMIT]\n"
					SET @sql.text.template = REPLACE(@sql.text.template, "[SELECT]", @.sql.text.SELECT);
					SET @sql.text.template = REPLACE(@sql.text.template, "[FROM]", @.sql.text.FROM);
					SET @sql.text.template = REPLACE(@sql.text.template, "[JOIN]", @.sql.text.JOIN);
					SET @sql.text.template = REPLACE(@sql.text.template, "[WHERE]", @.sql.text.WHERE);
					SET @sql.text.template = REPLACE(@sql.text.template, "[HAVING]", IF(@.sql.text.HAVING != '', CONCAT("\nHAVING \n", @.sql.text.HAVING), ''));
					SET @sql.text.template = REPLACE(@sql.text.template, "[GROUP]", IF(@.sql.text.GROUP != '', CONCAT("\nGROUP BY ", @.sql.text.GROUP), ''));
					SET @sql.text.template = REPLACE(@sql.text.template, "[ORDER]", IF(@.sql.text.ORDER != '', CONCAT("\nORDER BY ", @.sql.text.ORDER), ''));

					SET @sql.text.X = @sql.text.template;

					SET @sql.text.template.check.count = @sql.text.template;
					
					IF _MODE = 'sqltext.build.select' THEN
						SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '');
						SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", IF(@.sql.text.LIMIT != '', CONCAT('\n', @.sql.text.LIMIT), ''));
					ELSEIF _MODE IN ('sqltext.build.maxtime', 'sqltext.build.key') THEN
						SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS');
						SET @sql.text.template = REPLACE(@sql.text.template, "-- EXT1", CONCAT(', (', IF(@.sql.text.WHERE.P != '', @.sql.text.WHERE.P, 'TRUE'),') AS REC_OK '));
						SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", '');
					ELSEIF _MODE IN ('sqltext.build.information_schema') THEN
						SET @sql.text.template = REPLACE(@sql.text.template, "[SQL_CALC_FOUND_ROWS]", '');
						SET @sql.text.template = REPLACE(@sql.text.template, "[LIMIT]", '');
					END IF;
					SET @sql.text.template.check.count = REPLACE(@sql.text.template.check.count, "[LIMIT]", CONCAT('\nLIMIT ', 0));
					SET @sql.text.template.check.count = REPLACE(@sql.text.template.check.count, "[SQL_CALC_FOUND_ROWS]", '\nSQL_CALC_FOUND_ROWS');

					SET @sql.text.MAIN = @sql.text.template;
					SET @sql.text.MAIN.BBBBBBBB = @sql.text.template;
					
					-- ??? poco??? CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.MAIN', _Id_browser, '', _Context, @sql.text.template, '', '', '', '');
					-- ??? poco??? CALL _PrepareSQLText('SQL.PREPARE.ADDSQL.ANY', _Id_browser, 'check.count', _Context, @sql.text.template.check.count, '', '', '', '');
					/*
					IF _Param_A != '' THEN
						select @sql.text.template;
					END IF;
					*/
					LEAVE S_PrepareSQLText;
				END IF;
				
			END IF;
			
			
		END$$
		
DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
UWAGA 
SHOW VARIABLES LIKE '%grou%';

DLA Filtrow 
A)	z searchem ale bez lookupu (konta FK)
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.rec', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.DOWN', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.UP', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');


		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.search', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', 'Fundusz', '', '', '', '');


B)	Z lookupem (wojewodztwa)
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.rec', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.DOWN', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');
		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.DisplayValues.UP', 'f3571b99-10d2-11e4-b6a1-001372373ee4', 'k', 'jmam', '', '', '', '', '', '');

		CALL _sys_usr_profile_tools('SELECT.profiles.FILTERS.get.lookup.search', '29c94605-17ce-11e4-918c-001372373ee4', 'k', 'jmam', '', 'Fundusz', '', '', '', '');

		_sys_usr_profile_f_v
		na
		_sys_usr_profile_cpf_f_v
*/
