	DROP TABLE IF EXISTS tmp.BackorderRegels;
	DROP TEMPORARY TABLE IF EXISTS tmp.BackorderRegels;
	CREATE TEMPORARY TABLE tmp.BackorderRegels (
		Id INT PRIMARY KEY, BestellingId INT, DT DATETIME, Ean CHAR(13),
		BoekStatus INT, Aantal INT, AantalBackorder INT, Geleverd INT,
		Gereserveerd INT, Leverbaar INT, DeelLeverbaar INT, Wacht INT,
		VerstuurCompleteOrder INT,
		
		BeschikbareVoorraad INT, GereserveerdeVoorraad INT, FysiekeVoorraad INT,
		GeprinteVoorraad INT, NogNietGeprint INT,
		
		Bindwijze_voorraadartikel INT, Bindwijze_evenement INT,
		Voorafgaand INT, GenoegVoorraad INT,
		KEY( BestellingId )
	) ENGINE=MEMORY;
	
	CALL Voorraadbeheer.berekenGeprinteVoorraad();
	
	INSERT INTO tmp.BackorderRegels
		SELECT
			A.Id, A.BestellingId, BA.DT, A.Ean, BK.BoekStatus, A.Aantal, A.AantalBackorder,
			IFNULL( B.Geleverd, 0 ) AS Geleverd,
			IF( OP.niet_reserveren, 0, 1 ) AS Gereserveerd, /* Gereserveerd */
			IF( Bindwijze_voorraadartikel, 0 , 1 ) AS Leverbaar, /* Leverbaar */
			0, /* DeelLeverbaar */ 0, /* Wacht */ VerstuurCompleteOrder,
			
			IFNULL( BeschikbareVoorraad, 0 ), IFNULL( GereserveerdeVoorraad, 0 ),
			IFNULL( FysiekeVoorraad, 0 ), IFNULL( GP.GeprintAantal, 0), 
			IFNULL( GP.NogNietGeprint, 0),
			
			IFNULL( Bindwijze_voorraadartikel, 0 ), IFNULL( Bindwijze_evenement, 0 ),
			0, /* Voorafgaand */ IF( Bindwijze_voorraadartikel, 0 , 1 ) /* GenoegVoorraad */
		FROM Bestellingen A 
			JOIN OrderregelStatusPlat OP USING ( Id )                           -- Niet reserveren
			JOIN BestellingAll BA USING ( BestellingId )                        -- Datum
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( A.Ean = V.Ean )            -- Voorraadstanden
			LEFT JOIN tmp.GeprinteVoorraad GP ON ( A.Ean = GP.Ean )             -- Geprinte Voorraad
			LEFT JOIN Managementboek_Boeken.Boeken BK ON ( A.Ean = BK.Ean )     -- Boekstatus
			LEFT JOIN Managementboek_Boeken.Bindwijze USING ( Bindwijze )       -- Bindwijzes
			LEFT JOIN tmp.Backorders B ON ( A.Id = B.BackorderOrigineel )       -- Voor geleverd aantal
			LEFT JOIN BestellingStatus ST
				ON ( ST.Bestellingid = A.BestellingId
					AND ST.StatusId IN ( 33 /* Afgesloten */, 24 /* Geannuleerd */, 16 /* Geannuleerd */ ) )		
		WHERE A.AantalBackorder > 0 
			AND ST.StatusId IS NULL
			AND IFNULL( Geleverd, 0 ) < AantalBackorder
			AND A.Ean NOT IN ( 'IDEAL' )
			AND A.Geannuleerd = 0;
	
	
	-- Voor alles dat NIET gereserveerd is geldt: Het is leverbaar als er genoeg BESCHIKBARE voorraad is.
	/*
	DROP TEMPORARY TABLE IF EXISTS tmp.LeverbareEans;
	CREATE TEMPORARY TABLE tmp.LeverbareEans ENGINE=MEMORY
		SELECT Ean, SUM( AantalBackorder ) AS Totaal, Bindwijze_voorraadartikel, Boekstatus, T.BeschikbareVoorraad  
			FROM tmp.BackorderRegels T WHERE Gereserveerd = 0 AND Bindwijze_voorraadartikel = 1 
			GROUP BY Ean HAVING BeschikbareVoorraad >= Totaal;
	
	UPDATE tmp.BackorderRegels JOIN tmp.LeverbareEans USING ( Ean ) SET GenoegVoorraad = 1, Leverbaar = 1;
	*/
	
	CALL bereken_voorrang_backorderregels();
	
	-- Niet genoeg voorraad -> Dan niet leverbaar.
	UPDATE tmp.BackorderRegels SET Leverbaar = 0 WHERE GenoegVoorraad = 0;
	
	-- Bereken leverbaar; Alles is leverbaar BEHALVE:
	-- a) Orders met ten minste 1 regel waarvoor geldt: VerstuurCompleteOrder = 1 AND Niet genoeg voorraad AND boekstatus != 1, 2, 5
	DROP TEMPORARY TABLE IF EXISTS tmp.NietLeverbareOrders;
	
	CREATE TEMPORARY TABLE tmp.NietLeverbareOrders ENGINE=MEMORY
		SELECT DISTINCT BestellingId
		FROM tmp.BackorderRegels 
		WHERE VerstuurCompleteOrder = 1
			AND GenoegVoorraad = 0
			AND BoekStatus NOT IN ( 1, 2, 5 );
	
	-- Porto's, Bong's & Ideal's.
	DROP TEMPORARY TABLE IF EXISTS tmp.AlleLeverbareOrders;
	CREATE TEMPORARY TABLE tmp.AlleLeverbareOrders ENGINE=MEMORY
		SELECT DISTINCT BestellingId
		FROM tmp.BackorderRegels
		WHERE Leverbaar = 1 AND Ean NOT IN ( 'VOUCHER', 'PORTO', 'BONG', 'IDEAL' );
	
	UPDATE tmp.BackorderRegels
	SET Leverbaar = 0
	WHERE Ean IN ( 'VOUCHER', 'PORTO', 'BONG', 'IDEAL' )
		AND BestellingId NOT IN ( SELECT BestellingId FROM tmp.AlleLeverbareOrders );
	
	-- Zet op niet leveren, behalve die orderregels waarvan boekstatus 5,2,1  is -> 
	UPDATE tmp.BackorderRegels
		JOIN tmp.NietLeverbareOrders USING ( BestellingId )
	SET Leverbaar = 0, Wacht = 1;
	
	END ;;
DELIMITER ;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `BerekenCorrecties` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `BerekenCorrecties`()
BEGIN
	DECLARE CUTOFF DECIMAL( 10, 4 );
	DECLARE DFPick DECIMAL( 10, 4 );
	DECLARE DFBulk DECIMAL( 10, 4 );
	DECLARE DFRol  DECIMAL( 10, 4 );
	DECLARE DFRoq  DECIMAL( 10, 4 );
	DECLARE VF     DECIMAL( 10, 4 );
	DECLARE _DEFAULTROQ INT;
	
	SET SESSION binlog_format=MIXED;
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFPick  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfp';
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFBulk  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfb';
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRol   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfrol';
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRoq   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfroq';
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO CUTOFF  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'cutoff';
	SELECT CAST( `val` AS DECIMAL(10,2) ) INTO VF      FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'vfactor';
	SET CUTOFF = CUTOFF / 100;
	START TRANSACTION;
	
	DELETE FROM LangeTermijnTellingen;
	REPLACE INTO LangeTermijnTellingen
		SELECT 
		  Ean, 'MAN', SUM( Aantal ) 
		FROM
		  Managementboek_Klanten.`Bestellingen_zonder_backorders` 
		  JOIN Managementboek_Klanten.BestellingAll USING (BestellingId) 
		  JOIN Managementboek_Klanten.KlantVinken KV USING ( Klantid )		  
		  JOIN Managementboek_Boeken.Boeken USING ( Ean )
		WHERE 
		DT BETWEEN DATE_SUB( NOW(), INTERVAL 365 DAY ) AND DATE_SUB( NOW(), INTERVAL 90 DAY )
		AND Aantal BETWEEN 0 AND 2
		AND Boekstatus IN ( 0, 2, 5 )
		AND Herkomst NOT IN ( 'NCOI' )
		AND Institutioneel = 0
		GROUP BY Ean;
	
	DELETE FROM Correcties;
	REPLACE INTO Correcties
		SELECT Ean, 
		( `30d` > 0 ) + ( ( `60d` - `30d` ) > 0 ) + ( ( `90d` - `60d` ) > 0 ) + ( ( `year` - `90d` ) > 0 ) AS Punten,
		LEAST( ROUND( ( `30d` > 0 ) + ( ( `60d` - `30d` ) > 0 ) + ( ( `90d` - `60d` ) > 0 ) + ( ( `year` - `90d` ) > 0 ) * ( SUM( Aantal ) ) / 24 ), 5 ) AS Correctie
		FROM LangeTermijnTellingen JOIN Computerboek_Klanten.`Tellingen_Plat` USING ( Ean )
		GROUP BY Ean
		HAVING Correctie > 0;
			
	REPLACE INTO Correcties
		SELECT Ean, 
		( `30d` > 0 ) + ( ( `60d` - `30d` ) > 0 ) + ( ( `90d` - `60d` ) > 0 ) + ( ( `year` - `90d` ) > 0 ) AS Punten,
		LEAST( ROUND( ( `30d` > 0 ) + ( ( `60d` - `30d` ) > 0 ) + ( ( `90d` - `60d` ) > 0 ) + ( ( `year` - `90d` ) > 0 ) * ( SUM( Aantal ) ) / 24 ), 5 ) AS Correctie
		FROM LangeTermijnTellingen JOIN Managementboek_Klanten.`Tellingen_Plat` USING ( Ean )
		GROUP BY Ean
		HAVING Correctie > 0;
	
	-- ALG-5722 : Correcties niet toepassen voor DIO/DUD
	DROP TEMPORARY TABLE IF EXISTS Tmp.ToDelete;
	CREATE TEMPORARY TABLE Tmp.ToDelete SELECT Ean FROM Managementboek_Boeken.Boeken B JOIN Managementboek_Boeken.Uitgevers U ON ( B.`Uitgever` = U.`Uitgeverid` )
		WHERE B.`Bestelwijze` IN ( 'CB DIO', 'CB DUD', 'DIO', 'DUD' );
		
	REPLACE INTO Tmp.ToDelete SELECT Ean FROM Computerboek_Boeken.Boeken B JOIN Computerboek_Boeken.Uitgevers U ON ( B.`Uitgever` = U.`Uitgeverid` )
		WHERE B.`Bestelwijze` IN ( 'CB DIO', 'CB DUD', 'DIO', 'DUD' );
		
	-- [24-04-2014: COM boeken geen LT]
	REPLACE INTO Tmp.ToDelete SELECT Ean FROM Manpo.Boeken WHERE `Computer-boek` = 1 AND LENGTH(Ean)=13;
	
	-- [24-04-2014: JUR boeken geen LT]
	REPLACE INTO Tmp.ToDelete SELECT Ean FROM Managementboek_Boeken.Boeken B WHERE B.`Rubriek` = 'Juridisch';
	
	-- Wis correcties n.a.v. bovenstaande
	DELETE A FROM Correcties A JOIN Tmp.ToDelete USING ( Ean );	
		
	UPDATE Correcties JOIN Managementboek_Boeken.Boeken USING ( Ean ) SET Correctie = Correctie / 2 WHERE `Taalvermelding` = 'EN';
	
	-- VerkopenPerDagPerSite
	DELETE FROM VerkopenPerDagPerSite;
	INSERT INTO VerkopenPerDagPerSite SELECT 
		  'MAN',  
		  DATE(DT),
		  Ean,
		  SUM(Bn.Aantal) AS SAantal,
		  SUM( IF( Bn.Aantal <> 1, 0, 1 ) ) AS GecorrigeerdAantal,
		  GREATEST( ROUND( T1.Aantal * CUTOFF ), 2 ) AS MaxAantal,
		  BK.Boeken_minimalevoorraad,
		  IFNULL( ( 5 - ( IF( ( TO_DAYS( NOW() ) - TO_DAYS( BK.Aanmaakdatum ) ) > 40, 40, TO_DAYS( NOW() ) - TO_DAYS( BK.Aanmaakdatum  )  ) / 10 ) ), 1 ),
		  ( 3 - FLOOR( ( TO_DAYS( NOW() ) - TO_DAYS( DT ) ) / 30 ) ), 
		  IF( Magazijnsoort = 'Bulk', DFBulk, DFPick ),
		  Factor,
		  ( TO_DAYS( NOW() ) - TO_DAYS( BK.Aanmaakdatum ) ) AS DagenOud
		FROM
		  Managementboek_Klanten.Bestelling B 
		  LEFT JOIN Managementboek_Klanten.`BestellingHerkomst` H USING ( BestellingId )
		  JOIN Managementboek_Klanten.Bestellingen_zonder_backorders Bn 
		    ON (Bn.Bestellingid = B.Bestellingid) 
		  JOIN Managementboek_Klanten.`BestellingenExtra` E USING ( Id )
		  JOIN Managementboek_Klanten.KlantVinken KV USING ( Klantid )
		  JOIN Managementboek_Boeken.Boeken BK
		    USING ( Ean )
		  JOIN Mainpress_Globals.HBBFactors
		    ON( Maand = MONTH( NOW() ) )
		  LEFT JOIN Managementboek_Klanten.Tellingen T1 USING (Ean) 
		WHERE T1.Tellingtypeid = 7 
		  AND DT > DATE_SUB(NOW(), INTERVAL 90 DAY ) 
		  AND Bn.Geannuleerd = 0 
		  AND Boekstatus IN ( 0, 2, 5 )
		  AND Herkomst NOT IN ( 'NCOI' )
		  AND H.`Kanaal` NOT IN ( 'SerieABO' )
		  AND Institutioneel = 0
		  AND E.InRamsj=0
		GROUP BY Ean,
		  TO_DAYS(DT) 
		HAVING ABS(SAantal) <= IF( DagenOud > 45, MaxAantal, 999 );
	
	UPDATE VerkopenPerDagPerSite SET GecorrigeerdAantal = Aantal WHERE DagenOud >= 45;
		
	COMMIT;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `berekenGeprinteVoorraad` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `berekenGeprinteVoorraad`()
BEGIN
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp.GeprinteVoorraad (
		Ean CHAR(13) PRIMARY KEY,
		GeprintAantal INT NOT NULL DEFAULT 0,
		NogNietGeprint INT NOT NULL DEFAULT 0
	) ENGINE=MEMORY;
	
	DELETE FROM tmp.GeprinteVoorraad;
	INSERT INTO tmp.GeprinteVoorraad
	SELECT Ean, SUM(Geprint) GeprintAantal,SUM(NietGeprint) NogNietGeprint
	FROM (
		SELECT Ean, 
		IF( vink_geprint = 1, N.`Aantal` + N.`AantalBackorder`, 0 ) AS Geprint,
		IF( vink_nietgeprint = 1, N.`Aantal` + N.`AantalBackorder`, 0 ) AS NietGeprint 
		FROM Managementboek_Klanten.`OrderregelStatusPlat` B JOIN Managementboek_Klanten.Bestellingen N USING ( Id ) WHERE ( vink_geprint=1 OR vink_nietgeprint=1)
		AND Ean NOT IN ( 'IDEAL', 'PORTO' )
	     ) DerT
	GROUP BY Ean;
	
	/* DELETE FROM Voorraadbeheer.GeprinteVoorraad WHERE GeprintAantal=0 AND NogNietGeprint=0;
	INSERT IGNORE INTO Voorraadbeheer.`GeprinteVoorraad` SELECT * FROM tmp.GeprinteVoorraad; */
	
	/*
	-- We doen dit om een iets slappere locking mode te krijgen, 
	-- zodat de inserts via joins minder snel een deadlock veroorzaken.
	-- Daarnaast willen we geen halve resultaten, dus vandaar de transactie.
	-- SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
	START TRANSACTION;
	
	-- Managementboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, GeprintAantal )
		SELECT
			Ean, IFNULL( SUM( B.Aantal ), 0 ) AS Aantal
		FROM Managementboek_Klanten.OrderregelStatusPlat P
			JOIN Managementboek_Klanten.Bestellingen B USING ( Id )
        WHERE P.vink_open = 1
            AND P.bevestigd = 1
            AND ( P.exact_export OR P.factuur_geprint = 1 OR P.gefactureerd = 1 )
            AND ( P.niet_inpakken = 0 )
            AND ( P.ingepakt = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			GeprintAantal = GeprintAantal + VALUES( GeprintAantal );
	
	-- Computerboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, GeprintAantal )
		SELECT
			Ean, IFNULL( SUM( B.Aantal ), 0 ) AS Aantal
		FROM Computerboek_Klanten.OrderregelStatusPlat P
			JOIN Computerboek_Klanten.Bestellingen B USING ( Id )
        WHERE P.vink_open = 1
            AND P.bevestigd = 1
            AND ( P.exact_export OR P.factuur_geprint = 1 OR P.gefactureerd = 1 )
            AND ( P.niet_inpakken = 0 )
            AND ( P.ingepakt = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			GeprintAantal = GeprintAantal + VALUES( GeprintAantal );
	
	-- Juridischboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, GeprintAantal )
		SELECT
			Ean, IFNULL( SUM( B.Aantal ), 0 ) AS Aantal
		FROM Juridischboek_Klanten.OrderregelStatusPlat P
			JOIN Juridischboek_Klanten.Bestellingen B USING ( Id )
        WHERE P.vink_open = 1
            AND P.bevestigd = 1
            AND ( P.exact_export OR P.factuur_geprint = 1 OR P.gefactureerd = 1 )
            AND ( P.niet_inpakken = 0 )
            AND ( P.ingepakt = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			GeprintAantal = GeprintAantal + VALUES( GeprintAantal );
	
	
	-- Managementboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, NogNietGeprint )
		SELECT
			Ean, IFNULL( SUM( B.Aantal + B.AantalBackorder ), 0 ) AS Aantal
		FROM Managementboek_Klanten.OrderregelStatusPlat P
			JOIN Managementboek_Klanten.Bestellingen B USING ( Id )
		WHERE P.vink_open = 1
			AND P.bevestigd = 1
			AND ( P.exact_export = 0 AND P.factuur_geprint = 0 AND P.gefactureerd = 0 AND P.uit_backorder_gehaald = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			NogNietGeprint = NogNietGeprint + VALUES( NogNietGeprint );
	
	-- Computerboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, NogNietGeprint )
		SELECT
			Ean, IFNULL( SUM( B.Aantal + B.AantalBackorder ), 0 ) AS Aantal
		FROM Computerboek_Klanten.OrderregelStatusPlat P
			JOIN Computerboek_Klanten.Bestellingen B USING ( Id )
		WHERE P.vink_open = 1
			AND P.bevestigd = 1
			AND ( P.exact_export = 0 AND P.factuur_geprint = 0 AND P.gefactureerd = 0 AND P.uit_backorder_gehaald = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			NogNietGeprint = NogNietGeprint + VALUES( NogNietGeprint );
	
	-- Juridischboek
	INSERT INTO tmp.GeprinteVoorraad ( Ean, NogNietGeprint )
		SELECT
			Ean, IFNULL( SUM( B.Aantal + B.AantalBackorder ), 0 ) AS Aantal
		FROM Juridischboek_Klanten.OrderregelStatusPlat P
			JOIN Juridischboek_Klanten.Bestellingen B USING ( Id )
		WHERE P.vink_open = 1
			AND P.bevestigd = 1
			AND ( P.exact_export = 0 AND P.factuur_geprint = 0 AND P.gefactureerd = 0 AND P.uit_backorder_gehaald = 0 )
		GROUP BY Ean
		ON DUPLICATE KEY UPDATE 
			NogNietGeprint = NogNietGeprint + VALUES( NogNietGeprint );
	
	
	UPDATE tmp.GeprinteVoorraad SET EAN = EAN WHERE 0;
	*/
	
	CREATE TABLE IF NOT EXISTS tmp.GeprinteVoorraadRun ( DT DATETIME, CI CHAR(3) );
	INSERT INTO tmp.GeprinteVoorraadRun VALUES ( NOW(), @current_initials );
	
	COMMIT;
	
	END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `BerekenInkoopAdvies` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `BerekenInkoopAdvies`()
BEGIN
	DECLARE localEan CHAR(13);
	DECLARE no_more_rows BOOLEAN;
	DECLARE loop_cntr INT DEFAULT 0;
	DECLARE num_rows INT DEFAULT 0;
	
	-- DECLARE C1 CURSOR FOR SELECT DISTINCT Ean FROM Managementboek_Klanten.Bestellingen WHERE DTOrderregel > DATE_SUB( NOW(), INTERVAL 1 DAY ) AND Ean LIKE "978%";
	-- DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
	
	-- Dit soort onzin wegfilteren!
	UPDATE CbBestellingen.`OrderRegels` SET OpenAantal = 0, IsAfgesloten = 1 WHERE OpenAantal < 0;
	-- Tijdelijke tabel, queried sneller dan de view
	DROP TABLE IF EXISTS Tmp.OnderwegPerEan;
	DROP TEMPORARY TABLE IF EXISTS Tmp.Boeken;
	
	CREATE TEMPORARY TABLE IF NOT EXISTS Tmp.OnderwegPerEan ( Ean CHAR(13) PRIMARY KEY, Aantal INT ) ENGINE=MEMORY;
	REPLACE INTO Tmp.OnderwegPerEan SELECT Ean, Aantal FROM CbBestellingen.`OpenBestellingenPerEan`;
	
	CREATE TEMPORARY TABLE Tmp.Boeken ( Ean CHAR(13) PRIMARY KEY, Titel VARCHAR(255), Boekstatus INT, Auteur1 INT, Uitgever INT, Achternaam VARCHAR(255), Minimalebestelhoeveelheid INT ) ENGINE=InnoDB;
	
	-- REPLACE INTO Tmp.Boeken SELECT Ean, Titel, Boeken.BoekStatus, Auteur1, Uitgever, Achternaam, Minimalebestelhoeveelheid FROM Computerboek_Boeken.Boeken JOIN Computerboek_Boeken.Auteurs ON ( Auteur1 = Auteurid ) JOIN Computerboek_Boeken.`Bindwijze` USING ( Bindwijze ) WHERE Bindwijze_voorraadartikel = 1;
	REPLACE INTO Tmp.Boeken SELECT Ean, Titel, Boeken.BoekStatus, Auteur1, Uitgever, Achternaam, Minimalebestelhoeveelheid FROM Managementboek_Boeken.Boeken JOIN Managementboek_Boeken.Auteurs ON ( Auteur1 = Auteurid ) JOIN Managementboek_Boeken.`Bindwijze` USING ( Bindwijze ) WHERE Bindwijze_voorraadartikel = 1;
	REPLACE INTO Tmp.Boeken SELECT `Code`, E.Titel, 999, 0, 0, Auteur, 1 FROM Managementboek_Klanten.`ExactArtikelen` E 
		JOIN Managementboek_Boeken.Boeken K ON (`Code` = Ean) 
		JOIN Managementboek_Boeken.`Bindwijze` B ON (E.Bindwijze = B.`Bindwijze`) WHERE K.Boekstatus = 1 AND Bindwijze_voorraadartikel = 1 AND K.Uitgever IS NULL AND K.IsGewist = 1;
	INSERT IGNORE INTO Tmp.Boeken SELECT `Code`, Titel, IF( Magazijnsoort = 'BEST', 999, 0 ), 0, 0, Auteur, 1 FROM Managementboek_Klanten.`ExactArtikelen` LEFT JOIN Managementboek_Boeken.`Bindwijze` USING ( Bindwijze ) WHERE IFNULL( Bindwijze_voorraadartikel, 1 ) = 1;
	
	-- Update, work-around voor afwijkende beschikbare voorraad
	UPDATE Voorraadbeheer.`Voorraad` SET BeschikbareVoorraad = FysiekeVoorraad - GereserveerdeVoorraad WHERE FysiekeVoorraad - GereserveerdeVoorraad != BeschikbareVoorraad;
	
	-- Maak resultaat
	-- CREATE TABLE IF NOT EXISTS CbBestellingen.Inkoop ( Ean CHAR( 13 ) PRIMARY KEY, Titel VARCHAR( 255 ), Auteur VARCHAR( 255 ), Boekstatus INT, ROL INT, ROQ INT, OrigineleRoq INT, FysiekeVoorraad INT, BeschikbareVoorraad INT, Gewenst INT, Onderweg INT, BestelAdvies INT, KEY( Auteur ) );	
	
	-- Wis boeken die een vervanging hebben...
	DELETE Tmp.Boeken FROM Tmp.Boeken JOIN Managementboek_Boeken.`WinkelkarVervangingen` ON ( Ean = OrigineelEan );
	
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	START TRANSACTION;
	--
	DELETE FROM CbBestellingen.Inkoop;
	INSERT INTO CbBestellingen.Inkoop 
	SELECT Ean, 
		IFNULL( T.Titel, 'Onbekend' ) AS Titel, 
		COALESCE( T.Achternaam, 'Onbekend' ) AS Auteur,
		COALESCE( T.Boekstatus, 0 ) AS Boekstatus, 
		ROL, ROQ, OrigineleRoq, FysiekeVoorraad, BeschikbareVoorraad, ROL+ROQ, IFNULL( Aantal, 0 ) AS Onderweg, 
		IF( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ) > 0, GREATEST( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ), Minimalebestelhoeveelheid ), 0 ) AS BestelAdvies 
		FROM RoqAndRol 
		JOIN Tmp.Boeken T USING ( Ean )		
		JOIN Voorraadbeheer.`Voorraad` USING ( Ean ) 
		LEFT JOIN Tmp.OnderwegPerEan USING ( Ean ) 
		-- LEFT JOIN Managementboek_Boeken.`WinkelkarVervangingen` V ON ( Ean = OrigineelEan )
		WHERE 
		-- V.OrigineelEan IS NULL AND
		IFNULL( T.BoekStatus, 0 ) NOT IN ( 1 )
		AND ( IFNULL( Beschikbarevoorraad, 0 ) + IFNULL(Aantal,0) ) <= IFNULL( ROL, 0 )
		AND IFNULL( T.Uitgever, 0 ) NOT IN ( 433, 849 )
		HAVING Titel NOT LIKE  "%Actiepakket%" 
		AND Titel NOT LIKE "%Combinatiepakket%"
		AND Titel NOT LIKE "Pakket:%"
		AND BestelAdvies > 0
		AND Ean NOT IN ( '' ); 
		
		
	DELETE FROM CbBestellingen.NietLeverbaar;
	INSERT INTO CbBestellingen.NietLeverbaar 
	SELECT Ean, 
		IFNULL( T.Titel, 'Onbekend' ) AS Titel, 
		COALESCE( T.Achternaam, 'Onbekend' ) AS Auteur,
		COALESCE( T.Boekstatus, 0 ) AS Boekstatus, 
		ROL, ROQ, OrigineleRoq, FysiekeVoorraad, BeschikbareVoorraad, ROL+ROQ, IFNULL( Aantal, 0 ) AS Onderweg, 
		IF( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ) > 0, GREATEST( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ), Minimalebestelhoeveelheid ), 0 ) AS BestelAdvies 
		FROM RoqAndRol 
		JOIN Tmp.Boeken T USING ( Ean )		
		JOIN Voorraadbeheer.`Voorraad` USING ( Ean ) 
		LEFT JOIN Tmp.OnderwegPerEan USING ( Ean ) 
		-- LEFT JOIN Managementboek_Boeken.`WinkelkarVervangingen` V ON ( Ean = OrigineelEan )
		WHERE 
		-- V.OrigineelEan IS NULL AND
		IFNULL( T.BoekStatus, 0 ) IN ( 1 )
		AND ( IFNULL( Beschikbarevoorraad, 0 ) + IFNULL(Aantal,0) ) <= IFNULL( ROL, 0 )
		AND IFNULL( T.Uitgever, 0 ) NOT IN ( 433, 849 )
		HAVING Titel NOT LIKE  "%Actiepakket%" 
		AND Titel NOT LIKE "%Combinatiepakket%"
		AND Titel NOT LIKE "Pakket:%"
		AND BestelAdvies > 0; 		
		/* INSERT INTO CbBestellingen.Inkoop		
		SELECT RR.Ean, 
		IFNULL( T.Titel, 'Onbekend' ) AS Titel, 
		COALESCE( T.Achternaam, 'Onbekend' ) AS Auteur,
		COALESCE( T.Boekstatus, 0 ) AS Boekstatus, 
		ROL, ROQ, OrigineleRoq, FysiekeVoorraad, BeschikbareVoorraad, ROL+ROQ, IFNULL( Aantal, 0 ) AS Onderweg, 
		IF( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ) > 0, GREATEST( ( ROL+ROQ ) - ( BeschikbareVoorraad + IFNULL( Aantal, 0 ) ), Minimalebestelhoeveelheid ), 0 ) AS BestelAdvies 
		FROM RoqAndRol RR
		JOIN Manpo.`Mapped_EAN` M ON ( M.`U8` = RR.`Ean` )
		JOIN Voorraadbeheer.`Voorraad` V ON ( M.`L1` = V.`Ean` )
		JOIN Tmp.Boeken T ON ( M.U8 = T.Ean )			
		LEFT JOIN Tmp.OnderwegPerEan O ON( M.`U8` = O.Ean )
		WHERE 
		IFNULL( T.BoekStatus, 0 ) NOT IN ( 1 )
		AND ( IFNULL( Beschikbarevoorraad, 0 ) + IFNULL(Aantal,0) ) <= IFNULL( ROL, 0 )
		AND IFNULL( T.Uitgever, 0 ) NOT IN ( 433, 849 )
		HAVING Titel NOT LIKE  "%Actiepakket%" 
		AND Titel NOT LIKE "%Combinatiepakket%"
		AND Titel NOT LIKE "Pakket:%"
		AND BestelAdvies > 0; */
	COMMIT;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `BerekenRoqAndRol` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `BerekenRoqAndRol`()
BEGIN
	DECLARE CUTOFF DECIMAL( 10, 4 );
	DECLARE DFPick DECIMAL( 10, 4 );
	DECLARE DFBulk DECIMAL( 10, 4 );
	DECLARE DFRol  DECIMAL( 10, 4 );
	DECLARE DFRoq  DECIMAL( 10, 4 );
	DECLARE VF     DECIMAL( 10, 4 );
	DECLARE _DEFAULTROQ INT;
	
	-- Default ROQ -> Kan naar 0.
	SET _DEFAULTROQ=0;
	
	IF GET_LOCK('BerekenRoqAndRol', 60) THEN
		SET SESSION binlog_format=MIXED;
	
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFPick  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfp';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFBulk  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfb';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRol   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfrol';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRoq   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfroq';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO CUTOFF  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'cutoff';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO VF      FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'vfactor';
		SET CUTOFF = CUTOFF / 100;
		
		-- Tijdelijke tabel, deze wordt de echte.
		DROP TABLE IF EXISTS RoqAndRolTmp;
		CREATE TABLE RoqAndRolTmp ( Ean CHAR(13) NOT NULL, 
					   `ROL` INT(3) UNSIGNED NOT NULL, 
					   `ROQ` INT(3) UNSIGNED NOT NULL, 
					   `Minimum` INT(2) UNSIGNED NOT NULL, 
					   `Correctie` INT(1) UNSIGNED NOT NULL,  
					   `OrigineleRoq` INT(3) UNSIGNED NOT NULL, PRIMARY KEY(Ean), KEY(ROL), KEY(ROQ), KEY(Correctie) ) ENGINE=INNODB;
			
		--
		-- REPLACE INTO RoqAndRolTmp SELECT `Code`, 0, 0, 0, 0, 0 FROM Managementboek_Klanten.`ExactArtikelen` JOIN Managementboek_Boeken.Bindwijze USING ( Bindwijze ) WHERE `Code` AND Bindwijze_voorraadartikel;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Voorraadbeheer.`Voorraad`;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Computerboek_Boeken.Boeken WHERE BoekStatus IN ( 0, 2, 5 );
		
		REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Managementboek_Boeken.Boeken WHERE BoekStatus IN ( 0, 2, 5 );		
		REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Manpo.Boeken WHERE BoekStatus IN ( 0, 2, 5 );		
		
		REPLACE INTO RoqAndRolTmp SELECT Ean, 
			MAX( Minimumvoorraad ) + ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRol ) ) ) AS ROL, 
			GREATEST( ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRoq )  ) ), 0 ) AS ROQ,
			MAX( Minimumvoorraad ),
			IFNULL( Correctie, 0 ) AS Correctie,
			GREATEST( ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRoq )  ) ), 0 ) AS OrigineleRoq
			FROM VerkopenPerDagPerSite 
			    LEFT JOIN Correcties USING ( Ean )
			WHERE Aantal > 0 
			AND DT >= DATE_SUB( NOW(), INTERVAL 90 DAY )
			GROUP BY Ean;
		
		UPDATE RoqAndRolTmp SET Correctie = 0 WHERE ROQ >= 5;
		UPDATE RoqAndRolTmp SET ROQ = OrigineleRoq + Correctie;
		UPDATE RoqAndRolTmp SET ROQ = _DEFAULTROQ WHERE ROQ <= 0; -- Was 1
		UPDATE RoqAndRolTmp SET ROL = 0 WHERE ROL <= 0;
		
		-- Engelse boeken OF Juridische boeken; bestel 1 bij en zet rol op 0. (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN Managementboek_Boeken.Boeken USING ( Ean ) 
		 SET Roq = 0, Rol = 0
		 WHERE ( Taalvermelding IN ( 'EN', 'DE', 'FR' ) /* OR Rubriek = 'Juridisch' */ )
		  AND BoekStatus NOT IN ( 1, 99 )
		  AND ( Roq < 10 ); 
		
		-- Niet recent verkochte engelse boeken: NIET MEER BESTELLEN (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN NietRecentVerkocht USING ( Ean ) JOIN Managementboek_Boeken.Boeken USING ( Ean ) 
		 SET Roq = 0, Rol = 0
		 WHERE Taalvermelding IN ( 'EN', 'DE', 'FR' )
		  AND BoekStatus NOT IN ( 1, 99 )
		  AND ( Roq < 8 OR Rol < 4 );
		  
		-- Niet recent verkochte computerboeken: NIET MEER BESTELLEN (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN AlleenComputerboek USING ( Ean ) JOIN NietRecentVerkocht USING ( Ean )
		 SET Roq = 0, Rol = 0
		  WHERE ( Roq < 8 OR Rol < 4 );
		 
		-- Computerboek-boeken (alleen op computerboek, minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN AlleenComputerboek USING ( Ean )
		 SET Roq = IF( Roq >= 4, 4, Roq ), Rol = IF( Rol >= 2, 2, 0 )
		 WHERE ( Roq < 8 OR Rol < 4 );
		
		-- Ruzie
		UPDATE RoqAndRolTmp JOIN Manpo.Boeken USING ( Ean ) JOIN Manpo.`Uitgevers` USING ( UitgeverId ) 
			SET Roq=0, Rol=0 WHERE Ruzie=1;		
		
		-- Overig
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE Boeken_nietmeerbestellen=1;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE BoekStatus IN ( 1, 99 );		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE Voorraadartikel IS NULL;		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE ;		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE Voorraadartikel IS NULL;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE Boeken_nietmeerbestellen=1 OR BoekStatus IN ( 1, 99 );		
				
		REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken B JOIN Manpo.Bindwijze W USING ( Bindwijze ) 
		        WHERE B.BoekStatus IN ( 1, 99 ) 
			OR B.Boeken_nietmeerbestellen=1 OR Bindwijze_voorraadartikel=0;
		
		INSERT IGNORE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Voorraadbeheer.Voorraad; -- WHERE Ean NOT IN ( SELECT Ean FROM RoqAndRolTmp );
					
		-- DEELFACTOR
		IF VF != 1 THEN
			UPDATE RoqAndRolTmp SET Roq = ROUND(VF * Roq), Rol = ROUND(VF * Rol);
		END IF;
		
		-- Minimale voorraad heeft voorrang!
		UPDATE RoqAndRolTmp JOIN Managementboek_Extra.`Minimalevoorraad` USING ( Ean ) SET Rol = Minimalevoorraad WHERE Rol < Minimalevoorraad;
		UPDATE RoqAndRolTmp JOIN Managementboek_Boeken.Boeken USING ( Ean ) SET Rol = Boeken_minimalevoorraad WHERE Rol < Boeken_minimalevoorraad;
		UPDATE RoqAndRolTmp JOIN Manpo.Boeken USING ( Ean ) SET Rol = Boeken_minimalevoorraad WHERE Rol < Boeken_minimalevoorraad;
		
		-- Afwijkende ROQ/ROL in Manpo
		UPDATE Manpo.Boeken BK JOIN RoqAndRolTmp RL USING ( Ean ) SET RL.`ROL` = BK.`Afwijkende_ROL` WHERE NOT Afwijkende_ROL IS NULL;
		UPDATE Manpo.Boeken BK JOIN RoqAndRolTmp RL USING ( Ean ) SET RL.`ROQ` = BK.`Afwijkende_ROQ` WHERE NOT Afwijkende_ROQ IS NULL;
		
		-- ROQ & ROL in MANPO
		UPDATE RoqAndRolTmp JOIN Manpo.Boeken USING ( Ean ) SET Boeken_ROL = ROL, Boeken_ROQ = ROQ;
		
		-- RENAME TABELLEN
		RENAME TABLE RoqAndRol TO RoqAndRolOld, RoqAndRolTmp TO RoqAndRol;
		DROP TABLE RoqAndRolOld; 
		
		-- LOCK 
		DO RELEASE_LOCK('BerekenRoqAndRol');
	END IF;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `BerekenRoqAndRolDebug` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `BerekenRoqAndRolDebug`()
BEGIN
	DECLARE CUTOFF DECIMAL( 10, 4 );
	DECLARE DFPick DECIMAL( 10, 4 );
	DECLARE DFBulk DECIMAL( 10, 4 );
	DECLARE DFRol  DECIMAL( 10, 4 );
	DECLARE DFRoq  DECIMAL( 10, 4 );
	DECLARE VF     DECIMAL( 10, 4 );
	DECLARE _DEFAULTROQ INT;
	
	-- Default ROQ -> Kan naar 0.
	SET _DEFAULTROQ=0;
	
	IF GET_LOCK('BerekenRoqAndRol', 60) THEN
		SET SESSION binlog_format=MIXED;
	
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFPick  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfp';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFBulk  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfb';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRol   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfrol';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO DFRoq   FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'dfroq';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO CUTOFF  FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'cutoff';
		SELECT CAST( `val` AS DECIMAL(10,2) ) INTO VF      FROM Mainpress_Globals.`HBBVars` WHERE `key` = 'vfactor';
		SET CUTOFF = CUTOFF / 100;
		
		-- Tijdelijke tabel, deze wordt de echte.
		DROP TABLE IF EXISTS RoqAndRolTmp;
		CREATE TABLE RoqAndRolTmp ( Ean CHAR(13) NOT NULL, 
					   `ROL` TINYINT(3) UNSIGNED NOT NULL, 
					   `ROQ` TINYINT(3) UNSIGNED NOT NULL, 
					   `Minimum` TINYINT(2) UNSIGNED NOT NULL, 
					   `Correctie` TINYINT(1) UNSIGNED NOT NULL,  
					   `OrigineleRoq` TINYINT(3) UNSIGNED NOT NULL, PRIMARY KEY(Ean), KEY(ROL), KEY(ROQ), KEY(Correctie) ) ENGINE=INNODB;
			
		--
		-- REPLACE INTO RoqAndRolTmp SELECT `Code`, 0, 0, 0, 0, 0 FROM Managementboek_Klanten.`ExactArtikelen` JOIN Managementboek_Boeken.Bindwijze USING ( Bindwijze ) WHERE `Code` AND Bindwijze_voorraadartikel;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Voorraadbeheer.`Voorraad`;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Computerboek_Boeken.Boeken WHERE BoekStatus IN ( 0, 2, 5 );
		
		REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Managementboek_Boeken.Boeken WHERE BoekStatus IN ( 0, 2, 5 );		
		REPLACE INTO RoqAndRolTmp SELECT Ean, Boeken_minimalevoorraad, _DEFAULTROQ, 0, 0, _DEFAULTROQ FROM Manpo.Boeken WHERE BoekStatus IN ( 0, 2, 5 );		
		
		REPLACE INTO RoqAndRolTmp SELECT Ean, 
			MAX( Minimumvoorraad ) + ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRol ) ) ) AS ROL, 
			GREATEST( ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRoq )  ) ), 0 ) AS ROQ,
			MAX( Minimumvoorraad ),
			IFNULL( Correctie, 0 ) AS Correctie,
			GREATEST( ROUND( SUM( FMaand * GecorrigeerdAantal * FBoek * FDT / ( FLocatie * DFRoq )  ) ), 0 ) AS OrigineleRoq
			FROM VerkopenPerDagPerSite 
			    LEFT JOIN Correcties USING ( Ean )
			WHERE Aantal > 0 
			AND DT >= DATE_SUB( NOW(), INTERVAL 90 DAY )
			GROUP BY Ean;
		
		UPDATE RoqAndRolTmp SET Correctie = 0 WHERE ROQ >= 5;
		UPDATE RoqAndRolTmp SET ROQ = OrigineleRoq + Correctie;
		UPDATE RoqAndRolTmp SET ROQ = _DEFAULTROQ WHERE ROQ <= 0; -- Was 1
		UPDATE RoqAndRolTmp SET ROL = 0 WHERE ROL <= 0;
		
		-- Engelse boeken OF Juridische boeken; bestel 1 bij en zet rol op 0. (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN Managementboek_Boeken.Boeken USING ( Ean ) 
		 SET Roq = 0, Rol = 0
		 WHERE ( Taalvermelding = 'EN' /* OR Rubriek = 'Juridisch' */ )
		  AND BoekStatus NOT IN ( 1, 99 )
		  AND ( Roq < 5 ); 
		
		-- Niet recent verkochte engelse boeken: NIET MEER BESTELLEN (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN NietRecentVerkocht USING ( Ean ) JOIN Managementboek_Boeken.Boeken USING ( Ean ) 
		 SET Roq = 0, Rol = 0
		 WHERE Taalvermelding = 'EN'
		  AND BoekStatus NOT IN ( 1, 99 )
		  AND ( Roq < 8 OR Rol < 4 );
		  
		-- Niet recent verkochte computerboeken: NIET MEER BESTELLEN (minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN AlleenComputerboek USING ( Ean ) JOIN NietRecentVerkocht USING ( Ean )
		 SET Roq = 0, Rol = 0
		  WHERE ( Roq < 8 OR Rol < 4 );
		 
		-- Computerboek-boeken (alleen op computerboek, minimum voorraad: verder naar beneden!)
		UPDATE RoqAndRolTmp JOIN AlleenComputerboek USING ( Ean )
		 SET Roq = IF( Roq >= 4, 4, Roq ), Rol = IF( Rol >= 2, 2, 0 )
		 WHERE ( Roq < 8 OR Rol < 4 );
		  
		-- Overig
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE Boeken_nietmeerbestellen=1;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE BoekStatus IN ( 1, 99 );		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE Voorraadartikel IS NULL;		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE ;		
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE Voorraadartikel IS NULL;
		-- REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Computerboek_Boeken.Boeken JOIN AlleenComputerboek USING ( Ean ) WHERE Boeken_nietmeerbestellen=1 OR BoekStatus IN ( 1, 99 );		
				
		REPLACE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Managementboek_Boeken.Boeken WHERE BoekStatus IN ( 1, 99 ) 
			OR Boeken_nietmeerbestellen=1 OR VoorraadArtikel IS NULL OR `Voorraadartikel` = 0;
		
		INSERT IGNORE INTO RoqAndRolTmp SELECT Ean, 0, 0, 0, 0, 0 FROM Voorraadbeheer.Voorraad; -- WHERE Ean NOT IN ( SELECT Ean FROM RoqAndRolTmp );
					
		-- DEELFACTOR
		IF VF != 1 THEN
			UPDATE RoqAndRolTmp SET Roq = ROUND(VF * Roq), Rol = ROUND(VF * Rol);
		END IF;
		
		-- Minimale voorraad heeft voorrang!
		UPDATE RoqAndRolTmp JOIN Managementboek_Extra.`Minimalevoorraad` USING ( Ean ) SET Rol = Minimalevoorraad WHERE Rol < Minimalevoorraad;
		UPDATE RoqAndRolTmp JOIN Managementboek_Boeken.Boeken USING ( Ean ) SET Rol = Boeken_minimalevoorraad WHERE Rol < Boeken_minimalevoorraad;
		-- UPDATE RoqAndRolTmp JOIN Manpo.Boeken USING ( Ean ) SET Rol = Boeken_minimalevoorraad WHERE Rol < Boeken_minimalevoorraad;
					
		-- LOCK 
		DO RELEASE_LOCK('BerekenRoqAndRol');
	END IF;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `bereken_niet_recent_verkocht` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `bereken_niet_recent_verkocht`()
BEGIN
	-- Maak een database met boeken die we willen uitsluiten
	-- d.w.z. niet recent besteld
	-- maar niet boeken die recent zijn aangemaakt
	
	REPLACE INTO Voorraadbeheer.`NietRecentVerkochtPerDatabase` SELECT 'Managementboek', Ean, '1990-01-01' FROM Managementboek_Boeken.Boeken;
	REPLACE INTO Voorraadbeheer.`NietRecentVerkochtPerDatabase` SELECT 'Computerboek', Ean, '1990-01-01'   FROM Computerboek_Boeken.Boeken;
	REPLACE INTO Voorraadbeheer.`NietRecentVerkochtPerDatabase` SELECT 'Juridischboek', Ean, '1990-01-01'  FROM Juridischboek_Boeken.Boeken;
	
	REPLACE INTO Voorraadbeheer.NietRecentVerkochtPerDatabase SELECT 'Managementboek', Ean, MAX(DT) 
	FROM Managementboek_Klanten.Bestellingen JOIN Managementboek_Klanten.Bestelling USING ( BestellingId )
	JOIN Managementboek_Boeken.Boeken USING ( Ean )
	WHERE 
	-- Aanmaakdatum < DATE_SUB( NOW(), INTERVAL 6 MONTH ) AND 
	DT < DATE_SUB( NOW(), INTERVAL 2 DAY )
	GROUP BY Ean;
	REPLACE INTO Voorraadbeheer.NietRecentVerkochtPerDatabase SELECT 'Juridischboek', Ean, MAX(DT) 
	FROM Juridischboek_Klanten.Bestellingen JOIN Juridischboek_Klanten.Bestelling USING ( BestellingId )
	JOIN Juridischboek_Boeken.Boeken USING ( Ean )
	WHERE 
	-- Aanmaakdatum < DATE_SUB( NOW(), INTERVAL 6 MONTH ) AND 
	DT < DATE_SUB( NOW(), INTERVAL 2 DAY )
	GROUP BY Ean;
	REPLACE INTO Voorraadbeheer.NietRecentVerkochtPerDatabase SELECT 'Computerboek', Ean, MAX(DT) 
	FROM Computerboek_Klanten.Bestellingen JOIN Computerboek_Klanten.Bestelling USING ( BestellingId )
	JOIN Computerboek_Boeken.Boeken USING ( Ean )
	WHERE 
	-- Aanmaakdatum < DATE_SUB( NOW(), INTERVAL 6 MONTH ) AND 
	DT < DATE_SUB( NOW(), INTERVAL 2 DAY )
	GROUP BY Ean;
	
	DELETE FROM Voorraadbeheer.`NietRecentVerkocht`;
	REPLACE INTO Voorraadbeheer.`NietRecentVerkocht` SELECT Ean FROM NietRecentVerkochtPerDatabase GROUP BY Ean HAVING MAX(DT) < DATE_SUB( NOW(), INTERVAL 6 MONTH ) AND Ean NOT IN ('');
	
	DELETE FROM Voorraadbeheer.`AlleenComputerboek`;
	INSERT INTO Voorraadbeheer.`AlleenComputerboek` SELECT Ean FROM Computerboek_Boeken.Boeken A LEFT JOIN Managementboek_Boeken.Boeken B USING ( Ean ) WHERE B.Ean IS NULL;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_tekst` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_tekst`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2016-06-23 16:07:47'
begin_cvt:BEGIN

	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_dageinde CHAR(8) DEFAULT "23:00:00";
	DECLARE t_CB_mag_one INT;
	DECLARE t_CB_Levertijd INT;
	DECLARE t_CB INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_AfwijkendeLevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;
	DECLARE t_Feeds INT DEFAULT 0;
	DECLARE t_FeedLevertijd INT;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT DEFAULT 99;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_BW_periodiek INT;
	DECLARE t_BW_incompany INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;
	DECLARE t_inRamsj INT;
	DECLARE t_Gevonden INT;
	DECLARE t_BOV INT;

	SET t_Gevonden=0;

	
	IF i_Aantal = 1 AND i_Waarom = '' THEN

		SELECT EAN, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad
		INTO t_Cache_EAN, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad
		FROM Voorraadbeheer.VBMIH_tekst_cache TC
		WHERE TC.EAN = i_EAN
			AND IFNULL(TC.expires,NOW()) > NOW();

		IF t_Cache_EAN IS NOT NULL THEN
			LEAVE begin_cvt;
		END IF;

	END IF;

	IF i_Waarom = '' THEN
		SET i_Waarom = 'cache fail';
	END IF;


	
	
	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = CONVERT( r_EAN USING latin1 );

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IF( B.Boekstatus = 0,IFNULL( AV.BeschikbareCBVoorraad, 0 ), 0 ) as Voorraad,
		IFNULL( U.mag_one, 1 )
	INTO t_CB_voorraad, t_CB_mag_one
	FROM CbBoeken.Boeken B
		LEFT JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
	WHERE EAN = r_EAN;


	
	SELECT COUNT(DISTINCT P.PromoID) INTO t_c
	FROM Managementboek_Klanten.Promo_eans E
		JOIN Managementboek_Klanten.Promo P USING ( PromoID )
	WHERE ( E.EAN = r_EAN OR P.gratis_boek = r_EAN )
		AND NOW() BETWEEN P.DTstart AND P.DTeind;

	IF t_c > 0 THEN
		SET t_CB_mag_one = 0;
		SET t_CB_voorraad = 0;
	END IF;



	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
		JOIN Manpo.Bindwijze W USING ( Bindwijze )
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" )
			OR W.Bindwijze_periodiek = 1 );

	
	SELECT Levertijd INTO t_FeedLevertijd
		FROM Feeds.Levertijd
		WHERE EAN = r_EAN;

	IF t_FeedLevertijd IS NULL THEN
		SELECT Levertijd INTO t_FeedLevertijd FROM Feeds.DagPrijzen WHERE Ean = r_EAN;
	END IF;

	
	IF t_Manpo > 0 THEN
		SET t_Gevonden=1;

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			W.Bindwijze_periodiek,
			W.Bindwijze_incompany,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			IFNULL(B.Boeken_levertijd,0),
			U.Uitgevers_levertijd,
			B.Boeken_inramsj
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_BW_periodiek, t_BW_incompany, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_AfwijkendeLevertijd, t_UitgeverLevertijd, t_inRamsj
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

		SELECT
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			IFNULL(Levertijd,0)
		INTO t_CB_status, t_CB_Levertijd
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

		SET t_CB = 0;
	ELSE
		
		SELECT COUNT(EAN) INTO t_CB
			FROM CbBoeken.Boeken
			WHERE EAN = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB > 0 THEN
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_BW_periodiek = 0;
		SET t_BW_incompany = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			Levertijd,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_CB_Levertijd, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;
	ELSE
		SELECT COUNT(Ean) INTO t_Feeds
			FROM Feeds.Boeken_gefilterd
			WHERE Ean = r_EAN;

		IF t_Feeds = 0 THEN
			SELECT COUNT(*) INTO t_Feeds FROM Feeds.`BoekenInSiteView` WHERE Ean = r_Ean;
		END IF;
	END IF;

	
	IF t_Manpo = 0 AND t_CB = 0 AND t_Feeds > 0 THEN
		SET t_Bindwijze   = "gebonden";
		SET t_BW_event    = 0;
		SET t_BW_download = 0;
		SET t_BW_incompany = 0;
		SET t_NMB         = 0;
		SET t_Ruzie       = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_Taal
			FROM Feeds.Boeken B JOIN Feeds.DagPrijzen P USING ( Ean, FeedCode )
			WHERE B.EAN = r_EAN;
	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;

	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	
	ELSEIF t_BW_periodiek = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Dit product is helaas niet meer leverbaar";
		ELSE
			SET r_Knoptekst = "abonneren";
			SET r_DT = TIMESTAMP( CURDATE(), "21:00:00" );
			IF t_BW_download = 1 THEN
				SET r_Tekst = "Online abonnement";
			ELSE
				SELECT
					IF(
							b.Periodiek_verschijntonregelmatig=0,
							CONCAT('Verschijnt ',b.Periodiek_frequentie,' keer per jaar'),
							'Verschijnt onregelmatig'
					)
					INTO r_Tekst
				FROM Manpo.Boeken b
					WHERE b.EAN = r_EAN;
		END IF;
	END IF;

	ELSEIF t_BW_incompany = 1 THEN
		SET r_Knoptekst = "Meer informatie";
		SET r_Tekst = "incompany";
		SET r_DT = CURDATE();

		ELSEIF t_BW_event = 1 THEN


		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;


	ELSEIF t_BW_download = 1 THEN

		IF t_Ruzie > 0 THEN
			SET r_Knoptekst = "";
			SET r_Tekst = "Niet meer in assortiment";
		ELSEIF t_Boekstatus = 0 THEN
			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";
		ELSEIF t_Boekstatus = 5 THEN

			

			SET r_Knoptekst = "reserveren";

			IF t_Verschijningsdatum IS NULL OR t_Verschijningsdatum < CURDATE() THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE
	   
		IF t_CB_mag_one = 1 AND t_inRamsj = 1 THEN
			SET t_CB_mag_one = 0;
		END IF;

		
		SELECT COUNT(*) INTO t_BOV FROM Manpo.Boeken M JOIN CbBoeken.Boeken C USING ( Ean )
			JOIN Manpo.`Mapped_EAN` MAP ON ( MAP.L1 = C.Ean )
			JOIN Voorraadbeheer.`VoorraadInclusiefCB` V ON ( V.Ean = MAP.`U8` )
			WHERE C.`CBStatus` = "BOV"
			AND V.`BeschikbareMBVoorraad`<=0
			AND V.`BeschikbareCBVoorraad`>=0
			AND M.Boekstatus=0
			AND V.Ean = r_EAN;

		IF t_Feeds = 1 THEN
			
			SET t_CB_mag_one = 0;
		END IF;

		
		IF t_CB_status = "POD" AND t_CB_Levertijd > 0 THEN
			SET t_Defaultlevertijd = t_CB_Levertijd;
		ELSEIF t_BOV=1 THEN
			SET t_CB_mag_one = 0;

			IF t_CB_Levertijd > 0 THEN
				SET t_Defaultlevertijd = t_CB_Levertijd;
			ELSE
				SET t_Defaultlevertijd = 5;
			END IF;
		ELSEIF t_AfwijkendeLevertijd > 0 THEN
			SET t_DefaultLevertijd = t_AfwijkendeLevertijd;
		ELSEIF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_Feedlevertijd,0) > 1 THEN
			SET t_DefaultLevertijd = t_Feedlevertijd;
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Ruzie = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";

			
			IF t_CB_status = "POD" THEN
				IF r_Voorraad >= i_Aantal THEN
					SET t_CB_dageinde = "21:00:00";
				ELSE
					SET t_CB_dageinde = "17:30:00";
				END IF;
			END IF;

			SET r_Tekst = CONCAT("Vandaag voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, ", Voorraadbeheer.morgen() ," in huis");
			SET r_DT = Voorraadbeheer.werkdag_tijdstip( 0, t_CB_dageinde );
			SET t_Expires = Voorraadbeheer.geldig_tot( t_CB_dageinde );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > t_CB_dageinde
					OR Voorraadbeheer.is_feestdag( CURDATE() ) THEN

				SET r_Tekst = CONCAT("Op werkdagen voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, volgende dag in huis");

			END IF;

			
			IF t_CB_status = "POD" AND t_CB_Levertijd > 0 AND r_Voorraad < i_Aantal THEN
				SET r_Tekst = CONCAT("Verwachte levertijd ongeveer ", t_CB_Levertijd, " werkdagen");
			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			
			IF t_Ruzie > 0 AND (t_CB_mag_one = 0 OR t_BW_download = 1) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in assortiment";

			
			ELSEIF t_NMB = 1 AND ( t_CB_mag_one = 0 OR t_CB_voorraad < 1 ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NOT NULL AND t_Verschijningsdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					ELSEIF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSEIF t_CB_status = 'In bestelling bij uitgever' THEN

						SET r_Tekst = "Verwachte levertijd ongeveer 8 werkdagen";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 13 DAY ), t_Tijdstip );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 AND t_Feeds = 0 AND t_CB = 1 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN
							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
								SET t_Defaultlevertijd = t_CB_Levertijd;
							ELSE
								SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );
							END IF;

						ELSEIF t_CB_status = "BOV" THEN

							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
							ELSE
								SET t_c = 5;
							END IF;

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip( t_c, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip( t_Defaultlevertijd, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN
					IF t_Taal = 'nl' THEN
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					ELSE
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer 8 werkdagen" );
					END IF;
						SET r_DT = Voorraadbeheer.werkdag_tijdstip( t_Defaultlevertijd, '21:00:00' );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );
					SET r_DT = Voorraadbeheer.werkdag_tijdstip( 0, '21:00:00' );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.werkdag_tijdstip( 0, '21:00:00' );
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, ", Voorraadbeheer.morgen() ," in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag( CURDATE() )THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		INSERT INTO Voorraadbeheer.VBMIH_tekst_cache ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad )
		ON DUPLICATE KEY UPDATE updated=VALUES(updated), updated_vanwege=VALUES(updated_vanwege),expires=VALUES(expires),
			Tekst=VALUES(Tekst),Knoptekst=VALUES(Knoptekst),
			Dagen=VALUES(Dagen),DT=VALUES(DT),Ref_EAN=VALUES(Ref_EAN),Voorraad=VALUES(Voorraad);

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_tekst_dev` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_tekst_dev`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2016-06-23 11:23:25'
begin_cvt_dev:BEGIN

	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_dageinde CHAR(8) DEFAULT "23:00:00";
	DECLARE t_CB_mag_one INT;
	DECLARE t_CB_Levertijd INT;
	DECLARE t_CB INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_AfwijkendeLevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;
	DECLARE t_Feeds INT DEFAULT 0;
	DECLARE t_FeedLevertijd INT;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT DEFAULT 99;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_BW_periodiek INT;
	DECLARE t_BW_incompany INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;
	DECLARE t_inRamsj INT;
	DECLARE t_Gevonden INT;
	DECLARE t_BOV INT;

	SET t_Gevonden=0;

	
	IF i_Aantal = 1 AND i_Waarom = '' THEN

		SELECT EAN, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad
		INTO t_Cache_EAN, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad
		FROM Voorraadbeheer.VBMIH_tekst_cache_dev TC
		WHERE TC.EAN = i_EAN
			AND IFNULL(TC.expires,NOW()) > NOW();

		IF t_Cache_EAN IS NOT NULL THEN
			LEAVE begin_cvt_dev;
		END IF;

	END IF;

	IF i_Waarom = '' THEN
		SET i_Waarom = 'cache fail';
	END IF;


	
	
	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = CONVERT( r_EAN USING latin1 );

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IF( B.Boekstatus = 0,IFNULL( AV.BeschikbareCBVoorraad, 0 ), 0 ) as Voorraad,
		IFNULL( U.mag_one, 1 )
	INTO t_CB_voorraad, t_CB_mag_one
	FROM CbBoeken.Boeken B
		LEFT JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
	WHERE EAN = r_EAN;


	
	SELECT COUNT(DISTINCT P.PromoID) INTO t_c
	FROM Managementboek_Klanten.Promo_eans E
		JOIN Managementboek_Klanten.Promo P USING ( PromoID )
	WHERE ( E.EAN = r_EAN OR P.gratis_boek = r_EAN )
		AND NOW() BETWEEN P.DTstart AND P.DTeind;

	IF t_c > 0 THEN
		SET t_CB_mag_one = 0;
		SET t_CB_voorraad = 0;
	END IF;



	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot_dev( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
		JOIN Manpo.Bindwijze W USING ( Bindwijze )
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" )
			OR W.Bindwijze_periodiek = 1 );

	
	SELECT Levertijd INTO t_FeedLevertijd
		FROM Feeds.Levertijd
		WHERE EAN = r_EAN;

	IF t_FeedLevertijd IS NULL THEN
		SELECT Levertijd INTO t_FeedLevertijd FROM Feeds.DagPrijzen WHERE Ean = r_EAN;
	END IF;

	
	IF t_Manpo > 0 THEN
		SET t_Gevonden=1;

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			W.Bindwijze_periodiek,
			W.Bindwijze_incompany,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			IFNULL(B.Boeken_levertijd,0),
			U.Uitgevers_levertijd,
			B.Boeken_inramsj
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_BW_periodiek, t_BW_incompany, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_AfwijkendeLevertijd, t_UitgeverLevertijd, t_inRamsj
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

		SELECT
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			IFNULL(Levertijd,0)
		INTO t_CB_status, t_CB_Levertijd
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

		SET t_CB = 0;
	ELSE
		
		SELECT COUNT(EAN) INTO t_CB
			FROM CbBoeken.Boeken
			WHERE EAN = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB > 0 THEN
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_BW_periodiek = 0;
		SET t_BW_incompany = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			Levertijd,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_CB_Levertijd, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;
	ELSE
		SELECT COUNT(Ean) INTO t_Feeds
			FROM Feeds.Boeken_gefilterd
			WHERE Ean = r_EAN;

		IF t_Feeds = 0 THEN
			SELECT COUNT(*) INTO t_Feeds FROM Feeds.`BoekenInSiteView` WHERE Ean = r_Ean;
		END IF;
	END IF;

	
	IF t_Manpo = 0 AND t_CB = 0 AND t_Feeds > 0 THEN
		SET t_Bindwijze   = "gebonden";
		SET t_BW_event    = 0;
		SET t_BW_download = 0;
		SET t_BW_incompany = 0;
		SET t_NMB         = 0;
		SET t_Ruzie       = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_Taal
			FROM Feeds.Boeken B JOIN Feeds.DagPrijzen P USING ( Ean, FeedCode )
			WHERE B.EAN = r_EAN;
	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;

	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	
	ELSEIF t_BW_periodiek = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Dit product is helaas niet meer leverbaar";
		ELSE
			SET r_Knoptekst = "abonneren";
			SET r_DT = TIMESTAMP( CURDATE(), "21:00:00" );
			IF t_BW_download = 1 THEN
				SET r_Tekst = "Online abonnement";
			ELSE
				SELECT
					IF(
							b.Periodiek_verschijntonregelmatig=0,
							CONCAT('Verschijnt ',b.Periodiek_frequentie,' keer per jaar'),
							'Verschijnt onregelmatig'
					)
					INTO r_Tekst
				FROM Manpo.Boeken b
					WHERE b.EAN = r_EAN;
		END IF;
	END IF;

	ELSEIF t_BW_incompany = 1 THEN
		SET r_Knoptekst = "Meer informatie";
		SET r_Tekst = "incompany";
		SET r_DT = CURDATE();

		ELSEIF t_BW_event = 1 THEN


		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;


	ELSEIF t_BW_download = 1 THEN

		IF t_Ruzie > 0 THEN
			SET r_Knoptekst = "";
			SET r_Tekst = "Niet meer in assortiment";
		ELSEIF t_Boekstatus = 0 THEN
			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";
		ELSEIF t_Boekstatus = 5 THEN

			

			SET r_Knoptekst = "reserveren";

			IF t_Verschijningsdatum IS NULL OR t_Verschijningsdatum < CURDATE() THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE
	   
		IF t_CB_mag_one = 1 AND t_inRamsj = 1 THEN
			SET t_CB_mag_one = 0;
		END IF;

		
		SELECT COUNT(*) INTO t_BOV FROM Manpo.Boeken M JOIN CbBoeken.Boeken C USING ( Ean )
			JOIN Manpo.`Mapped_EAN` MAP ON ( MAP.L1 = C.Ean )
			JOIN Voorraadbeheer.`VoorraadInclusiefCB` V ON ( V.Ean = MAP.`U8` )
			WHERE C.`CBStatus` = "BOV"
			AND V.`BeschikbareMBVoorraad`<=0
			AND V.`BeschikbareCBVoorraad`>=0
			AND M.Boekstatus=0
			AND V.Ean = r_EAN;

		IF t_Feeds = 1 THEN
			
			SET t_CB_mag_one = 0;
		END IF;

		
		IF t_CB_status = "POD" AND t_CB_Levertijd > 0 THEN
			SET t_Defaultlevertijd = t_CB_Levertijd;
		ELSEIF t_BOV=1 THEN
			SET t_CB_mag_one = 0;

			IF t_CB_Levertijd > 0 THEN
				SET t_Defaultlevertijd = t_CB_Levertijd;
			ELSE
				SET t_Defaultlevertijd = 5;
			END IF;
		ELSEIF t_AfwijkendeLevertijd > 0 THEN
			SET t_DefaultLevertijd = t_AfwijkendeLevertijd;
		ELSEIF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_Feedlevertijd,0) > 1 THEN
			SET t_DefaultLevertijd = t_Feedlevertijd;
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Ruzie = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";

			
			IF t_CB_status = "POD" THEN
				IF r_Voorraad >= i_Aantal THEN
					SET t_CB_dageinde = "21:00:00";
				ELSE
					SET t_CB_dageinde = "17:30:00";
				END IF;
			END IF;

			SET r_Tekst = CONCAT("Vandaag voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, ", Voorraadbeheer.morgen_dev() ," in huis");
			SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( 0, t_CB_dageinde );
			SET t_Expires = Voorraadbeheer.geldig_tot_dev( t_CB_dageinde );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > t_CB_dageinde
					OR Voorraadbeheer.is_feestdag_dev( CURDATE() ) THEN

				SET r_Tekst = CONCAT("Op werkdagen voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, volgende dag in huis");

			END IF;

			
			IF t_CB_status = "POD" AND t_CB_Levertijd > 0 AND r_Voorraad < i_Aantal THEN
				SET r_Tekst = CONCAT("Verwachte levertijd ongeveer ", t_CB_Levertijd, " werkdagen");
			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			
			IF t_Ruzie > 0 AND (t_CB_mag_one = 0 OR t_BW_download = 1) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in assortiment";

			
			ELSEIF t_NMB = 1 AND ( t_CB_mag_one = 0 OR t_CB_voorraad < 1 ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NOT NULL AND t_Verschijningsdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					ELSEIF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSEIF t_CB_status = 'In bestelling bij uitgever' THEN

						SET r_Tekst = "Verwachte levertijd ongeveer 8 werkdagen";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 13 DAY ), t_Tijdstip );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 AND t_Feeds = 0 AND t_CB = 1 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN
							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
								SET t_Defaultlevertijd = t_CB_Levertijd;
							ELSE
								SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );
							END IF;

						ELSEIF t_CB_status = "BOV" THEN

							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
							ELSE
								SET t_c = 5;
							END IF;

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( t_c, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( t_Defaultlevertijd, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN
					IF t_Taal = 'nl' THEN
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					ELSE
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer 8 werkdagen" );
					END IF;
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( t_Defaultlevertijd, '21:00:00' );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );
					SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( 0, '21:00:00' );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.werkdag_tijdstip_dev( 0, '21:00:00' );
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, ", Voorraadbeheer.morgen_dev() ," in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag_dev( CURDATE() )THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		INSERT INTO Voorraadbeheer.VBMIH_tekst_cache_dev ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad )
		ON DUPLICATE KEY UPDATE updated=VALUES(updated), updated_vanwege=VALUES(updated_vanwege),expires=VALUES(expires),
			Tekst=VALUES(Tekst),Knoptekst=VALUES(Knoptekst),
			Dagen=VALUES(Dagen),DT=VALUES(DT),Ref_EAN=VALUES(Ref_EAN),Voorraad=VALUES(Voorraad);

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_tekst_k_dennis` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_tekst_k_dennis`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2016-06-21 10:11:52'
begin_cvt_k_dennis:BEGIN

	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_dageinde CHAR(8) DEFAULT "23:00:00";
	DECLARE t_CB_mag_one INT;
	DECLARE t_CB_Levertijd INT;
	DECLARE t_CB INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_AfwijkendeLevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;
	DECLARE t_Feeds INT DEFAULT 0;
	DECLARE t_FeedLevertijd INT;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT DEFAULT 99;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_BW_periodiek INT;
	DECLARE t_BW_incompany INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;
	DECLARE t_inRamsj INT;
	DECLARE t_Gevonden INT;
	DECLARE t_BOV INT;

	SET t_Gevonden=0;

	
	IF i_Aantal = 1 AND i_Waarom = '' THEN

		SELECT EAN, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad
		INTO t_Cache_EAN, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad
		FROM Voorraadbeheer.VBMIH_tekst_cache_k_dennis TC
		WHERE TC.EAN = i_EAN
			AND IFNULL(TC.expires,NOW()) > NOW();

		IF t_Cache_EAN IS NOT NULL THEN
			LEAVE begin_cvt_k_dennis;
		END IF;

	END IF;

	IF i_Waarom = '' THEN
		SET i_Waarom = 'cache fail';
	END IF;


	
	
	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = CONVERT( r_EAN USING latin1 );

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IF( B.Boekstatus = 0,IFNULL( AV.BeschikbareCBVoorraad, 0 ), 0 ) as Voorraad,
		IFNULL( U.mag_one, 1 )
	INTO t_CB_voorraad, t_CB_mag_one
	FROM CbBoeken.Boeken B
		LEFT JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
	WHERE EAN = r_EAN;


	
	SELECT COUNT(DISTINCT P.PromoID) INTO t_c
	FROM Managementboek_Klanten.Promo_eans E
		JOIN Managementboek_Klanten.Promo P USING ( PromoID )
	WHERE ( E.EAN = r_EAN OR P.gratis_boek = r_EAN )
		AND NOW() BETWEEN P.DTstart AND P.DTeind;

	IF t_c > 0 THEN
		SET t_CB_mag_one = 0;
		SET t_CB_voorraad = 0;
	END IF;



	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot_k_dennis( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
		JOIN Manpo.Bindwijze W USING ( Bindwijze )
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" )
			OR W.Bindwijze_periodiek = 1 );

	
	SELECT Levertijd INTO t_FeedLevertijd
		FROM Feeds.Levertijd
		WHERE EAN = r_EAN;

	
	IF t_Manpo > 0 THEN
		SET t_Gevonden=1;

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			W.Bindwijze_periodiek,
			W.Bindwijze_incompany,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			IFNULL(B.Boeken_levertijd,0),
			U.Uitgevers_levertijd,
			B.Boeken_inramsj
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_BW_periodiek, t_BW_incompany, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_AfwijkendeLevertijd, t_UitgeverLevertijd, t_inRamsj
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

		SELECT
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			IFNULL(Levertijd,0)
		INTO t_CB_status, t_CB_Levertijd
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

		SET t_CB = 0;
	ELSE
		
		SELECT COUNT(EAN) INTO t_CB
			FROM CbBoeken.Boeken
			WHERE EAN = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB > 0 THEN
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_BW_periodiek = 0;
		SET t_BW_incompany = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			Levertijd,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_CB_Levertijd, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;
	ELSE
		SELECT COUNT(Ean) INTO t_Feeds
			FROM Feeds.Boeken_gefilterd
			WHERE Ean = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB = 0 AND t_Feeds > 0 THEN
		SET t_Bindwijze   = "gebonden";
		SET t_BW_event    = 0;
		SET t_BW_download = 0;
		SET t_BW_incompany = 0;
		SET t_NMB         = 0;
		SET t_Ruzie       = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_Taal
			FROM Feeds.Boeken_gefilterd B JOIN Feeds.DagPrijzen P USING ( Ean )
			WHERE B.EAN = r_EAN;
	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;

	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	
	ELSEIF t_BW_periodiek = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Dit product is helaas niet meer leverbaar";
		ELSE
			SET r_Knoptekst = "abonneren";
			SET r_DT = TIMESTAMP( CURDATE(), "21:00:00" );
			IF t_BW_download = 1 THEN
				SET r_Tekst = "Online abonnement";
			ELSE
				SELECT
					IF(
							b.Periodiek_verschijntonregelmatig=0,
							CONCAT('Verschijnt ',b.Periodiek_frequentie,' keer per jaar'),
							'Verschijnt onregelmatig'
					)
					INTO r_Tekst
				FROM Manpo.Boeken b
					WHERE b.EAN = r_EAN;
		END IF;
	END IF;

	ELSEIF t_BW_incompany = 1 THEN
		SET r_Knoptekst = "Meer informatie";
		SET r_Tekst = "incompany";
		SET r_DT = NOW();

		ELSEIF t_BW_event = 1 THEN


		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;


	ELSEIF t_BW_download = 1 THEN

		IF t_Ruzie > 0 THEN
			SET r_Knoptekst = "";
			SET r_Tekst = "Niet meer in assortiment";
		ELSEIF t_Boekstatus = 0 THEN
			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";
		ELSEIF t_Boekstatus = 5 THEN

			

			SET r_Knoptekst = "reserveren";

			IF t_Verschijningsdatum IS NULL OR t_Verschijningsdatum < CURDATE() THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE
	   
		IF t_CB_mag_one = 1 AND t_inRamsj = 1 THEN
			SET t_CB_mag_one = 0;
		END IF;

		
		SELECT COUNT(*) INTO t_BOV FROM Manpo.Boeken M JOIN CbBoeken.Boeken C USING ( Ean )
			JOIN Manpo.`Mapped_EAN` MAP ON ( MAP.L1 = C.Ean )
			JOIN Voorraadbeheer.`VoorraadInclusiefCB` V ON ( V.Ean = MAP.`U8` )
			WHERE C.`CBStatus` = "BOV"
			AND V.`BeschikbareMBVoorraad`<=0
			AND V.`BeschikbareCBVoorraad`>=0
			AND M.Boekstatus=0
			AND V.Ean = r_EAN;

		IF t_Feeds = 1 THEN
			
			SET t_CB_mag_one = 0;
		END IF;

		
		IF t_CB_status = "POD" AND t_CB_Levertijd > 0 THEN
			SET t_Defaultlevertijd = t_CB_Levertijd;
		ELSEIF t_BOV=1 THEN
			SET t_CB_mag_one = 0;

			IF t_CB_Levertijd > 0 THEN
				SET t_Defaultlevertijd = t_CB_Levertijd;
			ELSE
				SET t_Defaultlevertijd = 5;
			END IF;
		ELSEIF t_AfwijkendeLevertijd > 0 THEN
			SET t_DefaultLevertijd = t_AfwijkendeLevertijd;
		ELSEIF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_Feedlevertijd,0) > 1 THEN
			SET t_DefaultLevertijd = t_Feedlevertijd;
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Ruzie = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";

			
			IF t_CB_status = "POD" THEN
				IF r_Voorraad >= i_Aantal THEN
					SET t_CB_dageinde = "21:00:00";
				ELSE
					SET t_CB_dageinde = "17:30:00";
				END IF;
			END IF;

			SET r_Tekst = CONCAT("Vandaag voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, ", Voorraadbeheer.morgen_k_dennis() ," in huis");
			SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( 0, t_CB_dageinde );
			SET t_Expires = Voorraadbeheer.geldig_tot_k_dennis( t_CB_dageinde );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > t_CB_dageinde
					OR Voorraadbeheer.is_feestdag_k_dennis( CURDATE() ) THEN

				SET r_Tekst = CONCAT("Op werkdagen voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, volgende dag in huis");

			END IF;

			
			IF t_CB_status = "POD" AND t_CB_Levertijd > 0 AND r_Voorraad < i_Aantal THEN
				SET r_Tekst = CONCAT("Verwachte levertijd ongeveer ", t_CB_Levertijd, " werkdagen");
			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			
			IF t_Ruzie > 0 AND (t_CB_mag_one = 0 OR t_BW_download = 1) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in assortiment";

			
			ELSEIF t_NMB = 1 AND ( t_CB_mag_one = 0 OR t_CB_voorraad < 1 ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NOT NULL AND t_Verschijningsdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					ELSEIF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSEIF t_CB_status = 'In bestelling bij uitgever' THEN

						SET r_Tekst = "Verwachte levertijd ongeveer 8 werkdagen";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 13 DAY ), t_Tijdstip );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 AND t_Feeds = 0 AND t_CB = 1 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN
							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
								SET t_Defaultlevertijd = t_CB_Levertijd;
							ELSE
								SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );
							END IF;

						ELSEIF t_CB_status = "BOV" THEN

							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
							ELSE
								SET t_c = 5;
							END IF;

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( t_c, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( t_Defaultlevertijd, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN
					IF t_Taal = 'nl' THEN
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					ELSE
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer 8 werkdagen" );
					END IF;
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( t_Defaultlevertijd, '21:00:00' );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );
					SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( 0, '21:00:00' );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_dennis( 0, '21:00:00' );
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, ", Voorraadbeheer.morgen_k_dennis() ," in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag_k_dennis( CURDATE() )THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		INSERT INTO Voorraadbeheer.VBMIH_tekst_cache_k_dennis ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad )
		ON DUPLICATE KEY UPDATE updated=VALUES(updated), updated_vanwege=VALUES(updated_vanwege),expires=VALUES(expires),
			Tekst=VALUES(Tekst),Knoptekst=VALUES(Knoptekst),
			Dagen=VALUES(Dagen),DT=VALUES(DT),Ref_EAN=VALUES(Ref_EAN),Voorraad=VALUES(Voorraad);

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_tekst_k_sander` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_tekst_k_sander`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2016-06-24 10:22:54'
begin_cvt_k_sander:BEGIN

	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_dageinde CHAR(8) DEFAULT "23:00:00";
	DECLARE t_CB_mag_one INT;
	DECLARE t_CB_Levertijd INT;
	DECLARE t_CB INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_AfwijkendeLevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;
	DECLARE t_Feeds INT DEFAULT 0;
	DECLARE t_FeedLevertijd INT;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT DEFAULT 99;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_BW_periodiek INT;
	DECLARE t_BW_incompany INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;
	DECLARE t_inRamsj INT;
	DECLARE t_Gevonden INT;
	DECLARE t_BOV INT;

	SET t_Gevonden=0;

	
	IF i_Aantal = 1 AND i_Waarom = '' THEN

		SELECT EAN, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad
		INTO t_Cache_EAN, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad
		FROM Voorraadbeheer.VBMIH_tekst_cache_k_sander TC
		WHERE TC.EAN = i_EAN
			AND IFNULL(TC.expires,NOW()) > NOW();

		IF t_Cache_EAN IS NOT NULL THEN
			LEAVE begin_cvt_k_sander;
		END IF;

	END IF;

	IF i_Waarom = '' THEN
		SET i_Waarom = 'cache fail';
	END IF;


	
	
	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = CONVERT( r_EAN USING latin1 );

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IF( B.Boekstatus = 0,IFNULL( AV.BeschikbareCBVoorraad, 0 ), 0 ) as Voorraad,
		IFNULL( U.mag_one, 1 )
	INTO t_CB_voorraad, t_CB_mag_one
	FROM CbBoeken.Boeken B
		LEFT JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
	WHERE EAN = r_EAN;


	
	SELECT COUNT(DISTINCT P.PromoID) INTO t_c
	FROM Managementboek_Klanten.Promo_eans E
		JOIN Managementboek_Klanten.Promo P USING ( PromoID )
	WHERE ( E.EAN = r_EAN OR P.gratis_boek = r_EAN )
		AND NOW() BETWEEN P.DTstart AND P.DTeind;

	IF t_c > 0 THEN
		SET t_CB_mag_one = 0;
		SET t_CB_voorraad = 0;
	END IF;



	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot_k_sander( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
		JOIN Manpo.Bindwijze W USING ( Bindwijze )
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" )
			OR W.Bindwijze_periodiek = 1 );

	
	SELECT Levertijd INTO t_FeedLevertijd
		FROM Feeds.Levertijd
		WHERE EAN = r_EAN;

	IF t_FeedLevertijd IS NULL THEN
		SELECT Levertijd INTO t_FeedLevertijd FROM Feeds.DagPrijzen WHERE Ean = r_EAN;
	END IF;

	
	IF t_Manpo > 0 THEN
		SET t_Gevonden=1;

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			W.Bindwijze_periodiek,
			W.Bindwijze_incompany,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			IFNULL(B.Boeken_levertijd,0),
			U.Uitgevers_levertijd,
			B.Boeken_inramsj
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_BW_periodiek, t_BW_incompany, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_AfwijkendeLevertijd, t_UitgeverLevertijd, t_inRamsj
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

		SELECT
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			IFNULL(Levertijd,0)
		INTO t_CB_status, t_CB_Levertijd
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

		SET t_CB = 0;
	ELSE
		
		SELECT COUNT(EAN) INTO t_CB
			FROM CbBoeken.Boeken
			WHERE EAN = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB > 0 THEN
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_BW_periodiek = 0;
		SET t_BW_incompany = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			Levertijd,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_CB_Levertijd, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;
	ELSE
		SELECT COUNT(Ean) INTO t_Feeds
			FROM Feeds.Boeken_gefilterd
			WHERE Ean = r_EAN;

		IF t_Feeds = 0 THEN
			SELECT COUNT(*) INTO t_Feeds FROM Feeds.`BoekenInSiteView` WHERE Ean = r_Ean;
		END IF;
	END IF;

	
	IF t_Manpo = 0 AND t_CB = 0 AND t_Feeds > 0 THEN
		SET t_Bindwijze   = "gebonden";
		SET t_BW_event    = 0;
		SET t_BW_download = 0;
		SET t_BW_incompany = 0;
		SET t_NMB         = 0;
		SET t_Ruzie       = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_Taal
			FROM Feeds.Boeken B JOIN Feeds.DagPrijzen P USING ( Ean, FeedCode )
			WHERE B.EAN = r_EAN;
	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;

	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	
	ELSEIF t_BW_periodiek = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Dit product is helaas niet meer leverbaar";
		ELSE
			SET r_Knoptekst = "abonneren";
			SET r_DT = TIMESTAMP( CURDATE(), "21:00:00" );
			IF t_BW_download = 1 THEN
				SET r_Tekst = "Online abonnement";
			ELSE
				SELECT
					IF(
							b.Periodiek_verschijntonregelmatig=0,
							CONCAT('Verschijnt ',b.Periodiek_frequentie,' keer per jaar'),
							'Verschijnt onregelmatig'
					)
					INTO r_Tekst
				FROM Manpo.Boeken b
					WHERE b.EAN = r_EAN;
		END IF;
	END IF;

	ELSEIF t_BW_incompany = 1 THEN
		SET r_Knoptekst = "Meer informatie";
		SET r_Tekst = "incompany";
		SET r_DT = CURDATE();

		ELSEIF t_BW_event = 1 THEN


		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;


	ELSEIF t_BW_download = 1 THEN

		IF t_Ruzie > 0 THEN
			SET r_Knoptekst = "";
			SET r_Tekst = "Niet meer in assortiment";
		ELSEIF t_Boekstatus = 0 THEN
			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";
		ELSEIF t_Boekstatus = 5 THEN

			

			SET r_Knoptekst = "reserveren";

			IF t_Verschijningsdatum IS NULL OR t_Verschijningsdatum < CURDATE() THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE
	   
		IF t_CB_mag_one = 1 AND t_inRamsj = 1 THEN
			SET t_CB_mag_one = 0;
		END IF;

		
		SELECT COUNT(*) INTO t_BOV FROM Manpo.Boeken M JOIN CbBoeken.Boeken C USING ( Ean )
			JOIN Manpo.`Mapped_EAN` MAP ON ( MAP.L1 = C.Ean )
			JOIN Voorraadbeheer.`VoorraadInclusiefCB` V ON ( V.Ean = MAP.`U8` )
			WHERE C.`CBStatus` = "BOV"
			AND V.`BeschikbareMBVoorraad`<=0
			AND V.`BeschikbareCBVoorraad`>=0
			AND M.Boekstatus=0
			AND V.Ean = r_EAN;

		IF t_Feeds = 1 THEN
			
			SET t_CB_mag_one = 0;
		END IF;

		
		IF t_CB_status = "POD" AND t_CB_Levertijd > 0 THEN
			SET t_Defaultlevertijd = t_CB_Levertijd;
		ELSEIF t_BOV=1 THEN
			SET t_CB_mag_one = 0;

			IF t_CB_Levertijd > 0 THEN
				SET t_Defaultlevertijd = t_CB_Levertijd;
			ELSE
				SET t_Defaultlevertijd = 5;
			END IF;
		ELSEIF t_AfwijkendeLevertijd > 0 THEN
			SET t_DefaultLevertijd = t_AfwijkendeLevertijd;
		ELSEIF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_Feedlevertijd,0) > 1 THEN
			SET t_DefaultLevertijd = t_Feedlevertijd;
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Ruzie = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";

			
			IF t_CB_status = "POD" THEN
				IF r_Voorraad >= i_Aantal THEN
					SET t_CB_dageinde = "21:00:00";
				ELSE
					SET t_CB_dageinde = "17:30:00";
				END IF;
			END IF;

			SET r_Tekst = CONCAT("Vandaag voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, ", Voorraadbeheer.morgen_k_sander() ," in huis");
			SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( 0, t_CB_dageinde );
			SET t_Expires = Voorraadbeheer.geldig_tot_k_sander( t_CB_dageinde );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > t_CB_dageinde
					OR Voorraadbeheer.is_feestdag_k_sander( CURDATE() ) THEN

				SET r_Tekst = CONCAT("Op werkdagen voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, volgende dag in huis");

			END IF;

			
			IF t_CB_status = "POD" AND t_CB_Levertijd > 0 AND r_Voorraad < i_Aantal THEN
				SET r_Tekst = CONCAT("Verwachte levertijd ongeveer ", t_CB_Levertijd, " werkdagen");
			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			
			IF t_Ruzie > 0 AND (t_CB_mag_one = 0 OR t_BW_download = 1) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in assortiment";

			
			ELSEIF t_NMB = 1 AND ( t_CB_mag_one = 0 OR t_CB_voorraad < 1 ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NOT NULL AND t_Verschijningsdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					ELSEIF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSEIF t_CB_status = 'In bestelling bij uitgever' THEN

						SET r_Tekst = "Verwachte levertijd ongeveer 8 werkdagen";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 13 DAY ), t_Tijdstip );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 AND t_Feeds = 0 AND t_CB = 1 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN
							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
								SET t_Defaultlevertijd = t_CB_Levertijd;
							ELSE
								SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );
							END IF;

						ELSEIF t_CB_status = "BOV" THEN

							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
							ELSE
								SET t_c = 5;
							END IF;

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( t_c, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( t_Defaultlevertijd, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN
					IF t_Taal = 'nl' THEN
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					ELSE
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer 8 werkdagen" );
					END IF;
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( t_Defaultlevertijd, '21:00:00' );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );
					SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( 0, '21:00:00' );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_sander( 0, '21:00:00' );
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, ", Voorraadbeheer.morgen_k_sander() ," in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag_k_sander( CURDATE() )THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		INSERT INTO Voorraadbeheer.VBMIH_tekst_cache_k_sander ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad )
		ON DUPLICATE KEY UPDATE updated=VALUES(updated), updated_vanwege=VALUES(updated_vanwege),expires=VALUES(expires),
			Tekst=VALUES(Tekst),Knoptekst=VALUES(Knoptekst),
			Dagen=VALUES(Dagen),DT=VALUES(DT),Ref_EAN=VALUES(Ref_EAN),Voorraad=VALUES(Voorraad);

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_tekst_k_thijs` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_tekst_k_thijs`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2016-06-23 11:05:06'
begin_cvt_k_thijs:BEGIN

	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_dageinde CHAR(8) DEFAULT "23:00:00";
	DECLARE t_CB_mag_one INT;
	DECLARE t_CB_Levertijd INT;
	DECLARE t_CB INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_AfwijkendeLevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;
	DECLARE t_Feeds INT DEFAULT 0;
	DECLARE t_FeedLevertijd INT;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT DEFAULT 99;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_BW_periodiek INT;
	DECLARE t_BW_incompany INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;
	DECLARE t_inRamsj INT;
	DECLARE t_Gevonden INT;
	DECLARE t_BOV INT;

	SET t_Gevonden=0;

	
	IF i_Aantal = 1 AND i_Waarom = '' THEN

		SELECT EAN, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad
		INTO t_Cache_EAN, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad
		FROM Voorraadbeheer.VBMIH_tekst_cache_k_thijs TC
		WHERE TC.EAN = i_EAN
			AND IFNULL(TC.expires,NOW()) > NOW();

		IF t_Cache_EAN IS NOT NULL THEN
			LEAVE begin_cvt_k_thijs;
		END IF;

	END IF;

	IF i_Waarom = '' THEN
		SET i_Waarom = 'cache fail';
	END IF;


	
	
	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = CONVERT( r_EAN USING latin1 );

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IF( B.Boekstatus = 0,IFNULL( AV.BeschikbareCBVoorraad, 0 ), 0 ) as Voorraad,
		IFNULL( U.mag_one, 1 )
	INTO t_CB_voorraad, t_CB_mag_one
	FROM CbBoeken.Boeken B
		LEFT JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
	WHERE EAN = r_EAN;


	
	SELECT COUNT(DISTINCT P.PromoID) INTO t_c
	FROM Managementboek_Klanten.Promo_eans E
		JOIN Managementboek_Klanten.Promo P USING ( PromoID )
	WHERE ( E.EAN = r_EAN OR P.gratis_boek = r_EAN )
		AND NOW() BETWEEN P.DTstart AND P.DTeind;

	IF t_c > 0 THEN
		SET t_CB_mag_one = 0;
		SET t_CB_voorraad = 0;
	END IF;



	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot_k_thijs( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
		JOIN Manpo.Bindwijze W USING ( Bindwijze )
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" )
			OR W.Bindwijze_periodiek = 1 );

	
	SELECT Levertijd INTO t_FeedLevertijd
		FROM Feeds.Levertijd
		WHERE EAN = r_EAN;

	
	IF t_Manpo > 0 THEN
		SET t_Gevonden=1;

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			W.Bindwijze_periodiek,
			W.Bindwijze_incompany,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			IFNULL(B.Boeken_levertijd,0),
			U.Uitgevers_levertijd,
			B.Boeken_inramsj
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_BW_periodiek, t_BW_incompany, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_AfwijkendeLevertijd, t_UitgeverLevertijd, t_inRamsj
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

		SELECT
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			IFNULL(Levertijd,0)
		INTO t_CB_status, t_CB_Levertijd
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

		SET t_CB = 0;
	ELSE
		
		SELECT COUNT(EAN) INTO t_CB
			FROM CbBoeken.Boeken
			WHERE EAN = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB > 0 THEN
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_BW_periodiek = 0;
		SET t_BW_incompany = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			IF( PublishingStatus = 4 AND ProductAvailability = 30, 'In bestelling bij uitgever',
				CBstatus ) AS CbStatus,
			Levertijd,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_CB_Levertijd, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;
	ELSE
		SELECT COUNT(Ean) INTO t_Feeds
			FROM Feeds.Boeken_gefilterd
			WHERE Ean = r_EAN;
	END IF;

	
	IF t_Manpo = 0 AND t_CB = 0 AND t_Feeds > 0 THEN
		SET t_Bindwijze   = "gebonden";
		SET t_BW_event    = 0;
		SET t_BW_download = 0;
		SET t_BW_incompany = 0;
		SET t_NMB         = 0;
		SET t_Ruzie       = 0;

		SELECT
			B.Verschijningsdatum,
			B.Boekstatus,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_Boekstatus, t_CB_status, t_Taal
			FROM Feeds.Boeken_gefilterd B JOIN Feeds.DagPrijzen P USING ( Ean )
			WHERE B.EAN = r_EAN;
	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;

	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	
	ELSEIF t_BW_periodiek = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Dit product is helaas niet meer leverbaar";
		ELSE
			SET r_Knoptekst = "abonneren";
			SET r_DT = TIMESTAMP( CURDATE(), "21:00:00" );
			IF t_BW_download = 1 THEN
				SET r_Tekst = "Online abonnement";
			ELSE
				SELECT
					IF(
							b.Periodiek_verschijntonregelmatig=0,
							CONCAT('Verschijnt ',b.Periodiek_frequentie,' keer per jaar'),
							'Verschijnt onregelmatig'
					)
					INTO r_Tekst
				FROM Manpo.Boeken b
					WHERE b.EAN = r_EAN;
		END IF;
	END IF;

	ELSEIF t_BW_incompany = 1 THEN
		SET r_Knoptekst = "Meer informatie";
		SET r_Tekst = "incompany";
		SET r_DT = CURDATE();

		ELSEIF t_BW_event = 1 THEN


		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;


	ELSEIF t_BW_download = 1 THEN

		IF t_Ruzie > 0 THEN
			SET r_Knoptekst = "";
			SET r_Tekst = "Niet meer in assortiment";
		ELSEIF t_Boekstatus = 0 THEN
			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";
		ELSEIF t_Boekstatus = 5 THEN

			

			SET r_Knoptekst = "reserveren";

			IF t_Verschijningsdatum IS NULL OR t_Verschijningsdatum < CURDATE() THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE
	   
		IF t_CB_mag_one = 1 AND t_inRamsj = 1 THEN
			SET t_CB_mag_one = 0;
		END IF;

		
		SELECT COUNT(*) INTO t_BOV FROM Manpo.Boeken M JOIN CbBoeken.Boeken C USING ( Ean )
			JOIN Manpo.`Mapped_EAN` MAP ON ( MAP.L1 = C.Ean )
			JOIN Voorraadbeheer.`VoorraadInclusiefCB` V ON ( V.Ean = MAP.`U8` )
			WHERE C.`CBStatus` = "BOV"
			AND V.`BeschikbareMBVoorraad`<=0
			AND V.`BeschikbareCBVoorraad`>=0
			AND M.Boekstatus=0
			AND V.Ean = r_EAN;

		IF t_Feeds = 1 THEN
			
			SET t_CB_mag_one = 0;
		END IF;

		
		IF t_CB_status = "POD" AND t_CB_Levertijd > 0 THEN
			SET t_Defaultlevertijd = t_CB_Levertijd;
		ELSEIF t_BOV=1 THEN
			SET t_CB_mag_one = 0;

			IF t_CB_Levertijd > 0 THEN
				SET t_Defaultlevertijd = t_CB_Levertijd;
			ELSE
				SET t_Defaultlevertijd = 5;
			END IF;
		ELSEIF t_AfwijkendeLevertijd > 0 THEN
			SET t_DefaultLevertijd = t_AfwijkendeLevertijd;
		ELSEIF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_Feedlevertijd,0) > 1 THEN
			SET t_DefaultLevertijd = t_Feedlevertijd;
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Ruzie = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";

			
			IF t_CB_status = "POD" THEN
				IF r_Voorraad >= i_Aantal THEN
					SET t_CB_dageinde = "21:00:00";
				ELSE
					SET t_CB_dageinde = "17:30:00";
				END IF;
			END IF;

			SET r_Tekst = CONCAT("Vandaag voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, ", Voorraadbeheer.morgen_k_thijs() ," in huis");
			SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( 0, t_CB_dageinde );
			SET t_Expires = Voorraadbeheer.geldig_tot_k_thijs( t_CB_dageinde );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > t_CB_dageinde
					OR Voorraadbeheer.is_feestdag_k_thijs( CURDATE() ) THEN

				SET r_Tekst = CONCAT("Op werkdagen voor ", SUBSTR(t_CB_dageinde,1,5), " uur besteld, volgende dag in huis");

			END IF;

			
			IF t_CB_status = "POD" AND t_CB_Levertijd > 0 AND r_Voorraad < i_Aantal THEN
				SET r_Tekst = CONCAT("Verwachte levertijd ongeveer ", t_CB_Levertijd, " werkdagen");
			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			
			IF t_Ruzie > 0 AND (t_CB_mag_one = 0 OR t_BW_download = 1) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in assortiment";

			
			ELSEIF t_NMB = 1 AND ( t_CB_mag_one = 0 OR t_CB_voorraad < 1 ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NOT NULL AND t_Verschijningsdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					ELSEIF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND t_Herdrukdatum > CURDATE() THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSEIF t_CB_status = 'In bestelling bij uitgever' THEN

						SET r_Tekst = "Verwachte levertijd ongeveer 8 werkdagen";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 13 DAY ), t_Tijdstip );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 AND t_Feeds = 0 AND t_CB = 1 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN
							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
								SET t_Defaultlevertijd = t_CB_Levertijd;
							ELSE
								SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );
							END IF;

						ELSEIF t_CB_status = "BOV" THEN

							IF t_CB_Levertijd > 0 THEN
								SET t_c = t_CB_Levertijd;
							ELSE
								SET t_c = 5;
							END IF;

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( t_c, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( t_Defaultlevertijd, '21:00:00' );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN
					IF t_Taal = 'nl' THEN
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					ELSE
						SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer 8 werkdagen" );
					END IF;
						SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( t_Defaultlevertijd, '21:00:00' );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );
					SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( 0, '21:00:00' );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.werkdag_tijdstip_k_thijs( 0, '21:00:00' );
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, ", Voorraadbeheer.morgen_k_thijs() ," in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag_k_thijs( CURDATE() )THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, volgende dag in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		INSERT INTO Voorraadbeheer.VBMIH_tekst_cache_k_thijs ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad )
		ON DUPLICATE KEY UPDATE updated=VALUES(updated), updated_vanwege=VALUES(updated_vanwege),expires=VALUES(expires),
			Tekst=VALUES(Tekst),Knoptekst=VALUES(Knoptekst),
			Dagen=VALUES(Dagen),DT=VALUES(DT),Ref_EAN=VALUES(Ref_EAN),Voorraad=VALUES(Voorraad);

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `calc_vbmih_ttekst_k_thijs` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `calc_vbmih_ttekst_k_thijs`(
		IN i_EAN CHAR(13),
		IN i_Aantal INT,
		IN i_Waarom CHAR(50),

		OUT r_Tekst VARCHAR(255) CHARSET UTF8,
		OUT r_Knoptekst VARCHAR(50) CHARSET UTF8,
		OUT r_Dagen INT(11),
		OUT r_DT DATETIME,
		OUT r_EAN CHAR(13) CHARSET UTF8,
		OUT r_Voorraad INT
		)
    COMMENT 'Last updated at 2014-08-26 12:08:29'
BEGIN
	DECLARE t_c INT;
	DECLARE t_CB_voorraad INT;
	DECLARE t_CB_status VARCHAR(32);
	DECLARE t_CB_mag_one INT;
	DECLARE t_Defaultlevertijd INT;
	DECLARE t_UitgeverLevertijd INT;
	DECLARE t_Manpo INT;
	DECLARE t_min_voorraad INT;
	DECLARE t_Na VARCHAR(128);
	DECLARE t_Tijdstip TIME;
	DECLARE t_Voor VARCHAR(128);
	DECLARE t_Expires TIMESTAMP;

	DECLARE t_Bindwijze VARCHAR(50) CHARSET UTF8;
	DECLARE t_Boekstatus INT;
	DECLARE t_BW_download INT;
	DECLARE t_BW_event INT;
	DECLARE t_Cache_EAN CHAR(13);
	DECLARE t_Herdrukdatum DATE;
	DECLARE t_Magazijnsoort VARCHAR(8);
	DECLARE t_NMB INT;
	DECLARE t_Ruzie INT;
	DECLARE t_Taal VARCHAR(8);
	DECLARE t_Verschijningsdatum DATE;

	
	

	SELECT COUNT(WV.VervangendEan), WV.VervangendEan   INTO t_c, r_EAN
	FROM Managementboek_Boeken.WinkelkarVervangingen WV
		INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
		INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
		INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
	WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1;

	IF t_c = 0 THEN
		SET r_EAN = i_EAN;
	ELSEIF t_c > 1 THEN
		SELECT WV.VervangendEan   INTO r_EAN
		FROM Managementboek_Boeken.WinkelkarVervangingen WV
			LEFT JOIN Voorraadbeheer.Voorraad V ON ( V.EAN = WV.VervangendEan )
			INNER JOIN Manpo.Mapped_EAN M ON ( VervangendEan = M.L1 )
			INNER JOIN Manpo.Boeken B ON ( B.EAN = M.U8 )
			INNER JOIN Manpo.Bindwijze USING ( Bindwijze )
		WHERE WV.OrigineelEan = i_EAN AND Bindwijze_voorraadartikel = 1
		ORDER BY IFNULL(V.Beschikbarevoorraad,0) ASC LIMIT 1;
	END IF;



	SELECT Beschikbarevoorraad INTO r_Voorraad
	FROM Voorraadbeheer.Voorraad WHERE EAN = r_EAN;

	IF r_Voorraad IS NULL THEN
		SET r_Voorraad = 0;
	END IF;


	SELECT
		IFNULL( AV.Voorraad, 0 ) as Voorraad,
		U.mag_one,
		MPU.Uitgevers_levertijd
	INTO t_CB_voorraad, t_CB_mag_one, t_UitgeverLevertijd
	FROM CbBoeken.Boeken B
		JOIN CbBoeken.Uitgevers U ON ( U.cb_id = B.Uitgever_cbid )
		LEFT JOIN CbBoeken.ActueleVoorraad AV USING ( EAN )
		LEFT JOIN CbBoeken.Uitgevers_cb_mb USING ( cb_id )
		LEFT JOIN Manpo.Uitgevers MPU USING ( UitgeverID )
	WHERE EAN = r_EAN;




	
	SET t_Tijdstip = '21:00:00';
	SET r_Dagen = 0;

	
	SET t_Expires = Voorraadbeheer.geldig_tot_k_thijs( '21:00:00' );


	
	SELECT COUNT(EAN) INTO t_Manpo
	FROM Manpo.Boeken
	WHERE EAN = r_EAN AND ( Boeken_verborgenboek = 0
			OR Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk", "magazine" ) );

	
	IF t_Manpo > 0 THEN

		SELECT
			B.Boekstatus,
			B.Bindwijze,
			W.Bindwijze_evenement,
			W.Bindwijze_download,
			B.Herdrukdatum,
			B.Verschijningsdatum,
			B.Magazijnsoort,
			B.Boeken_nietmeerbestellen,
			U.Ruzie,
			B.Taalvermelding,
			U.Uitgevers_levertijd
		INTO t_Boekstatus, t_Bindwijze, t_BW_event, t_BW_download, t_Herdrukdatum, t_Verschijningsdatum, t_Magazijnsoort, t_NMB, t_Ruzie, t_Taal, t_UitgeverLevertijd
		FROM Manpo.Boeken B
			INNER JOIN Manpo.Bindwijze W USING ( Bindwijze )
			INNER JOIN Manpo.Uitgevers U USING ( UitgeverID )
		WHERE B.EAN = r_EAN;
			
			

	ELSE

		SET t_Boekstatus = 0;
		SET t_Bindwijze = "gebonden";
		SET t_BW_event = 0;
		SET t_BW_download = 0;
		SET t_NMB = 0;
		SET t_Ruzie = 0;

		SELECT
			B.Verschijningsdatum,
			CBstatus,
			CASE B.Taalvermelding
				WHEN "dut" THEN "nl"
				WHEN "nl" THEN "nl"
				WHEN "en" THEN "en"
				ELSE NULL
			END
		INTO t_Verschijningsdatum, t_CB_status, t_Taal
		FROM CbBoeken.Boeken B
		WHERE B.EAN = r_EAN;

	END IF;

	IF IFNULL(YEAR(t_Verschijningsdatum),0) < 1000 THEN
		SET t_Verschijningsdatum = NULL;
	END IF;


	
	IF t_Bindwijze IN ( "boekenweekgeschenk", "e-boekenweekgeschenk" ) THEN

		SET r_Tekst = "Gratis tijdens de Boekenweek bij aankoop van €12,50 aan Nederlandse boeken. Niet los te bestellen.";

	ELSEIF t_Bindwijze = "magazine" AND t_Boekstatus IN ( 1, 99 ) THEN

		SET r_Knoptekst = "";
		SET r_Tekst = "Niet los verkrijgbaar";

	ELSEIF t_BW_event = 1 THEN

		IF t_Boekstatus IN ( 1, 99 ) THEN
			SET r_Tekst = "Uitverkocht";
		ELSE
			SET r_Knoptekst = "aanmelden";
			SET r_Tekst = CONCAT( "Dit event vindt plaats op ",
				DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
			SET r_DT = TIMESTAMP( t_Verschijningsdatum, "21:00:00" );
			SET t_Expires = TIMESTAMP( t_Verschijningsdatum, "00:00:00" );
			SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );
		END IF;

	ELSEIF t_BW_download = 1 THEN

		IF t_Boekstatus = 0 THEN

			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Direct te downloaden";

		ELSEIF t_Boekstatus = 5 THEN

			
			IF t_Verschijningsdatum IS NULL THEN
				SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
				SET r_Knoptekst = "reserveren";
				SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );
			ELSE
				SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
					DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
				SET r_DT = t_Verschijningsdatum;
			END IF;

		ELSE

			SET r_Tekst = "Leverdatum onbekend.";

		END IF;
	ELSE

		

		IF IFNULL(t_CB_mag_one,0) = 1 THEN
			SET t_Defaultlevertijd = 2;  
		ELSEIF IFNULL(t_UitgeverLevertijd,0) >= 2 THEN
			SET t_Defaultlevertijd = t_UitgeverLevertijd;
		ELSEIF t_Taal = "nl" THEN
			SET t_Defaultlevertijd = 4; 
		ELSE
			SET t_Defaultlevertijd = 8; 
		END IF;


		IF t_Magazijnsoort = "pick" THEN
			SET t_min_voorraad = 1; 
		ELSEIF t_Magazijnsoort = "topx" THEN
			SET t_min_voorraad = 1; 
		ELSE
			SET t_min_voorraad = 1; 
		END IF;
		IF t_min_voorraad IS NULL THEN SET t_min_voorraad = 1; END IF;



		IF t_Boekstatus = 0 AND IFNULL(t_CB_mag_one,0) = 1 AND t_CB_voorraad >= i_Aantal THEN

			

			SET r_Knoptekst = "bestellen";
			SET r_Tekst = "Vandaag voor 23:00 besteld, morgen in huis";
			SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs(0);
			SET t_Expires = Voorraadbeheer.geldig_tot_k_thijs( '23:00:00' );

			IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '23:00:00'
					OR Voorraadbeheer.is_feestdag_k_thijs( CURDATE() )
					OR Voorraadbeheer.is_feestdag_k_thijs( DATE_ADD( CURDATE(), INTERVAL 1 DAY ) ) THEN

				SET r_Tekst = "Op werkdagen voor 23:00 besteld, morgen in huis";

			END IF;


		ELSEIF r_Voorraad < t_min_voorraad OR r_Voorraad <= 0 THEN

			


			IF t_Ruzie > 0 AND ( t_NMB = 1 OR t_Boekstatus IN ( 1, 99 ) ) THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Niet meer in ons assortiment";

			ELSEIF t_NMB = 1 THEN

				SET r_Knoptekst = "";
				SET r_Tekst = "Dit product is niet meer leverbaar";

			ELSE

				

				IF t_Boekstatus = 5 THEN

					
					SET r_Knoptekst = "reserveren";

					IF t_Verschijningsdatum IS NULL OR YEAR(t_Verschijningsdatum) < 1900 THEN

						SET r_Tekst = "Nog niet verschenen, verschijningsdatum onbekend";
						SET r_DT = DATE_ADD( NOW(), INTERVAL 1 YEAR );

					ELSEIF t_Herdrukdatum IS NOT NULL AND YEAR(t_Herdrukdatum) > 1900 THEN

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = CONCAT( "Nog niet verschenen, verwacht op ",
							DATE_FORMAT( t_Verschijningsdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Verschijningsdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Verschijningsdatum, '00:00:00' );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus = 2 THEN

					SET r_Knoptekst = "bestellen";

					IF t_Herdrukdatum IS NOT NULL AND YEAR(t_Herdrukdatum) > 1900 THEN

						SET r_Tekst = CONCAT( "In herdruk, verwacht op ",
							DATE_FORMAT( t_Herdrukdatum, "%d-%m-%Y" ) );
						SET r_DT = TIMESTAMP( t_Herdrukdatum, t_Tijdstip );
						SET t_Expires = TIMESTAMP( t_Herdrukdatum, '00:00:00' );

					ELSE

						SET r_Tekst = "In herdruk, verschijningsdatum onbekend";
						SET r_DT = TIMESTAMP( DATE_ADD( NOW(), INTERVAL 1 YEAR ), t_Tijdstip );

					END IF;

					SET t_Expires = GREATEST( t_Expires, TIMESTAMP( CURDATE(), "23:59:59" ) );

				ELSEIF t_Boekstatus IN ( 1, 99 ) THEN

					SET r_Knoptekst = "";
					SET r_Tekst = "Niet meer leverbaar";

				ELSE

					
					IF t_Manpo = 0 THEN

						SET t_c = IF( t_CB_voorraad > 0 AND t_CB_mag_one = 1, 2, t_Defaultlevertijd );

						
						IF t_CB_status = "POD" THEN

							SET t_c = IF( HOUR(NOW()) < 18, 2, 3 );

						END IF;

						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_c, " werkdagen" );
						SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs( t_c );
						SET r_Knoptekst = "bestellen";

					ELSE

						
						
						SET r_Tekst = CONCAT( "Verwachte levertijd ongeveer ", t_Defaultlevertijd, " werkdagen" );
						SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs( t_Defaultlevertijd );
						SET r_Knoptekst = "bestellen";

					END IF;
				END IF;
			END IF;
		ELSE
			

			SET r_Knoptekst = "bestellen";

			
			IF r_Voorraad < i_Aantal AND i_Aantal > 1 THEN

				
				IF WEEKDAY(NOW()) < 5 AND CURTIME() < '21:00:00' THEN

					SET r_Tekst = CONCAT( "Verwachte levertijd voor meerdere exemplaren ongeveer ", t_Defaultlevertijd, " werkdagen" );
					SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs( t_Defaultlevertijd );

				ELSE

					
					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, morgen in huis" );
					SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs( 0 );

				END IF;
			ELSE

				

				SET r_DT = Voorraadbeheer.vbmih_belofte_k_thijs(0);
				SET r_Tekst = CONCAT( "Vandaag voor 21:00 uur besteld, morgen in huis" );

				IF WEEKDAY(NOW()) >= 5 OR CURTIME() > '21:00:00'
						OR Voorraadbeheer.is_feestdag_k_thijs( CURDATE() )
						OR Voorraadbeheer.is_feestdag_k_thijs( DATE_ADD( CURDATE(), INTERVAL 1 DAY ) ) THEN

					SET r_Tekst = CONCAT( "Op werkdagen voor 21:00 uur besteld, morgen in huis" );

				END IF;

			END IF;

		END IF;

	END IF;


	
	IF i_Aantal = 1 THEN

		REPLACE INTO Voorraadbeheer.VBMIH_tekst_cache_k_thijs ( EAN, updated, updated_vanwege, expires, Tekst, Knoptekst, Dagen, DT, Ref_EAN, Voorraad )
		VALUES ( i_EAN, NOW(), i_Waarom, t_Expires, r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	END IF;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `HerberekenGeprinteVoorraad` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `HerberekenGeprinteVoorraad`()
BEGIN
	START TRANSACTION;
	CALL Voorraadbeheer.`berekenGeprinteVoorraad`;
	
	DELETE FROM Voorraadbeheer.`GeprinteVoorraad`;
	INSERT INTO Voorraadbeheer.`GeprinteVoorraad` SELECT * FROM tmp.GeprinteVoorraad;
	COMMIT;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `herbereken_eerderereserveringen` */;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `herbereken_eerderereserveringen`( myEan CHAR(13) )
BEGIN
	
	SET @c = 0;
	UPDATE OpenPerOrderregel SET EerdereReserveringen = -Saldo + ( @c := ( Saldo + @c ) ) WHERE Ean = myEan ORDER BY DT;
    END ;;
DELIMITER ;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `herbereken_openperregel` */;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `herbereken_openperregel`()
BEGIN
	  -- Declare variables used just for cursor and loop control
	  DECLARE curEan CHAR( 13 );
	  DECLARE no_more_rows BOOLEAN;
	  DECLARE loop_cntr INT DEFAULT 0;
	  DECLARE num_rows INT DEFAULT 0;
	  DECLARE cur CURSOR FOR SELECT DISTINCT Ean FROM OpenPerOrderregel;
	  -- Declare 'handlers' for exceptions
	  DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
	TRUNCATE OpenPerOrderregel;
	INSERT IGNORE INTO OpenPerOrderregel SELECT Administratie, OrderregelId,  M.Ean, IF( COUNT( ST.StatusId ) + COUNT( OT.StatusId ) = 0, SUM(Mutatie), 0 ) AS Mutatie, 0, MIN(M.DT) AS DT FROM Voorraadreserveringen M
	JOIN Managementboek_Boeken.Boeken USING ( Ean ) JOIN Managementboek_Boeken.`Bindwijze` USING ( Bindwijze )
	JOIN Managementboek_Klanten.BestellingAll A ON ( IF( M.`OrigineelBestellingId` > 0, M.`OrigineelBestellingId`, M.`Bestellingid` ) = A.`Bestellingid` )
	LEFT JOIN Managementboek_Klanten.BestellingStatus OT ON ( A.`Bestellingid` = OT.BestellingId AND OT.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	LEFT JOIN Managementboek_Klanten.`OrderregelStatus` ST ON ( M.`Orderregelid` = ST.`Id` AND ST.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	WHERE 
	OrderRegelId > 0 
	AND Bindwijze_voorraadartikel = 1
	AND Administratie = 'Managementboek'
	GROUP BY OrderregelId 
	HAVING Mutatie > 0;
	INSERT IGNORE INTO OpenPerOrderregel SELECT Administratie, OrderregelId,  M.Ean, IF( COUNT( ST.StatusId ) + COUNT( OT.StatusId ) = 0, SUM(Mutatie), 0 ) AS Mutatie, 0, MIN(M.DT) AS DT FROM Voorraadreserveringen M
	JOIN Computerboek_Boeken.Boeken USING ( Ean ) JOIN Computerboek_Boeken.`Bindwijze` USING ( Bindwijze )
	JOIN Computerboek_Klanten.BestellingAll A ON ( IF( M.`OrigineelBestellingId` > 0, M.`OrigineelBestellingId`, M.`Bestellingid` ) = A.`Bestellingid` )
	LEFT JOIN Computerboek_Klanten.BestellingStatus OT ON ( A.`Bestellingid` = OT.BestellingId AND OT.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	LEFT JOIN Computerboek_Klanten.`OrderregelStatus` ST ON ( M.`Orderregelid` = ST.`Id` AND ST.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	WHERE 
	OrderRegelId > 0 
	AND Bindwijze_voorraadartikel = 1
	AND Administratie = 'Computerboek'
	GROUP BY OrderregelId 
	HAVING Mutatie > 0;
	INSERT IGNORE INTO OpenPerOrderregel  SELECT Administratie, OrderregelId,  M.Ean, IF( COUNT( ST.StatusId ) + COUNT( OT.StatusId ) = 0, SUM(Mutatie), 0 ) AS Mutatie, 0, MIN(M.DT) AS DT FROM Voorraadreserveringen M
	JOIN Juridischboek_Boeken.Boeken USING ( Ean ) JOIN Juridischboek_Boeken.`Bindwijze` USING ( Bindwijze )
	JOIN Juridischboek_Klanten.BestellingAll A ON ( IF( M.`OrigineelBestellingId` > 0, M.`OrigineelBestellingId`, M.`Bestellingid` ) = A.`Bestellingid` )
	LEFT JOIN Juridischboek_Klanten.BestellingStatus OT ON ( A.`Bestellingid` = OT.BestellingId AND OT.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	LEFT JOIN Juridischboek_Klanten.`OrderregelStatus` ST ON ( M.`Orderregelid` = ST.`Id` AND ST.`StatusId` IN ( 15, 33, 30, 29, 16, 24 ) )
	WHERE 
	OrderRegelId > 0 
	AND Bindwijze_voorraadartikel = 1
	AND Administratie = 'Juridischboek'
	GROUP BY OrderregelId 
	HAVING Mutatie > 0;
	OPEN cur;
	
	the_loop: LOOP
	    FETCH  cur  INTO  curEan;
	    IF no_more_rows THEN
		CLOSE cur;
		LEAVE the_loop;
	    END IF;
	    
	    CALL herbereken_eerderereserveringen( curEan );
	  END LOOP the_loop;	
    END ;;
DELIMITER ;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET utf8 COLLATE utf8_general_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `resetReservering` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `resetReservering`( myAdministratie VARCHAR(50), myBestellingid INT )
BEGIN
	DECLARE A INT;
	SELECT 
	  IFNULL( SUM(  Mutatie  ), 0 ) INTO A
	FROM
	  Voorraadreserveringen 
	WHERE Administratie = myAdministratie 
	  AND BestellingId = myBestellingid;
	
	IF A > 0 THEN
		INSERT INTO Voorraadreserveringen ( EAN, Mutatie, DT, Orderregelid, Gebruiker, Debug, Klantid, `Type`, Bestellingid, Administratie, OrigineelBestellingID, Omschrijving )
		SELECT 
		  Ean,
		  - SUM( Mutatie ),
		  NOW(3),
		  Orderregelid,
		  @current_initials,
		  Debug,
		  Klantid,
		  'gecorrigeerd',
		  BestellingId,
		  Administratie,
		  OrigineelBestellingId,
		  Omschrijving 
		FROM
		  Voorraadreserveringen 
		WHERE Administratie = myAdministratie 
		  AND BestellingId = myBestellingid 
		  GROUP BY Ean, Orderregelid;	
	END IF;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `update_geprintevoorraad` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `update_geprintevoorraad`( _ean CHAR(13) )
BEGIN
	DECLARE _geprint INT;
	DECLARE _nietgeprint INT;
		
	SELECT
		IFNULL( SUM( IF( vink_geprint = 1 and (levering = 1 OR IFNULL(FactuurId,0)>0 ), N.Aantal + N.AantalBackorder, 0 ) ), 0 ) as geprint, 
		IFNULL( SUM( IF( vink_nietgeprint = 1 AND levering = 0, N.Aantal + N.AantalBackorder - Managementboek_Klanten.orderregel_geleverd_voorraadsysteem(Id) , 0 ) ), 0 ) as nietgeprint
	INTO _geprint, _nietgeprint
	FROM Managementboek_Klanten.OrderregelStatusPlat B
		JOIN Managementboek_Klanten.Bestellingen N USING ( Id )
	WHERE ( vink_geprint = 1 OR vink_nietgeprint = 1 )
		AND Ean = _ean;
	
	IF _geprint = 0 AND _nietgeprint = 0 THEN
		DELETE FROM Voorraadbeheer.GeprinteVoorraad WHERE Ean = _ean;
	ELSE
		INSERT INTO Voorraadbeheer.GeprinteVoorraad SET GeprintAantal = IFNULL(_geprint,0), NogNietGeprint = IFNULL(_nietgeprint,0), Ean = _ean 
			ON DUPLICATE KEY UPDATE GeprintAantal = VALUES(GeprintAantal), NogNietGeprint = VALUES(NogNietGeprint);
	END IF;
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
    COMMENT 'Last updated at 2016-06-23 16:07:47'
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst_dev` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst_dev`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
    COMMENT 'Last updated at 2016-06-23 11:23:25'
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst_dev( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst_k_dennis` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst_k_dennis`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
    COMMENT 'Last updated at 2016-06-21 10:11:52'
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst_k_dennis( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst_k_sander` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst_k_sander`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
    COMMENT 'Last updated at 2016-06-24 10:22:54'
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst_k_sander( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst_k_thijs` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst_k_thijs`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
    COMMENT 'Last updated at 2016-06-23 11:05:06'
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst_k_thijs( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `vbmih_tekst_thijs` */;
DELIMITER ;;
CREATE DEFINER=`thijs`@`%` PROCEDURE `vbmih_tekst_thijs`( i_EAN CHAR(13), i_Aantal INT, i_Waarom CHAR(50) )
BEGIN

	DECLARE r_Tekst VARCHAR(255) CHARSET UTF8;
	DECLARE r_Knoptekst VARCHAR(50) CHARSET UTF8;
	DECLARE r_Dagen INT(11);
	DECLARE r_DT DATETIME;
	DECLARE r_EAN CHAR(13) CHARSET UTF8;
	DECLARE r_Voorraad INT;

	CALL Voorraadbeheer.calc_vbmih_tekst_thijs( i_EAN, i_Aantal, i_Waarom,
		r_Tekst, r_Knoptekst, r_Dagen, r_DT, r_EAN, r_Voorraad );

	SELECT r_Tekst AS tekst, r_Knoptekst AS knoptekst, r_Dagen AS dagen, r_DT AS dt, r_EAN AS ean, r_Voorraad AS voorraad;

END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `verwerk_plankVoorraad_wijziging` */;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
DELIMITER ;;
CREATE DEFINER=`pieter`@`%` PROCEDURE `verwerk_plankVoorraad_wijziging`(EanInput VARCHAR(13),AantalInput INT(11))
BEGIN
	DECLARE huidigeVoorraad INT(11);
	SELECT voorraad(EanInput) INTO huidigeVoorraad;
	SET @omschrijving = (SELECT artikelOmschrijving(EanInput));
	INSERT IGNORE INTO Voorraadmutaties SET
		`Ean`=EanInput,
		Mutatie=AantalInput-huidigeVoorraad,
		DT=NOW(),
		Orderregelid=null,
		Gebruiker=@initials,
		`Type`='hertelling',
		Omschrijving=@omschrijving;
    END ;;
DELIMITER ;
ALTER DATABASE `Voorraadbeheer` CHARACTER SET utf8 COLLATE utf8_general_ci ;

--
-- Current Database: `Voorraadbeheer_temp`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `Voorraadbeheer_temp` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `Voorraadbeheer_temp`;

--
-- Table structure for table `Voorraadmutaties`
--

CREATE TABLE `Voorraadmutaties` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Ean` char(13) CHARACTER SET utf8 DEFAULT NULL,
  `Mutatie` int(11) DEFAULT NULL,
  `DT` datetime DEFAULT NULL,
  `Orderregelid` int(11) DEFAULT NULL,
  `Type` enum('ingepakt','ingeklaard','gecorrigeerd','uitgeklaard') DEFAULT NULL,
  `Voorraad` int(11) DEFAULT NULL,
  `Gebruiker` char(5) DEFAULT NULL,
  `PlankVoorraad` int(11) DEFAULT NULL,
  `GereserveerdeVoorraad` int(11) DEFAULT NULL,
  `VoorraadOud` int(11) DEFAULT NULL,
  `BeschikbareVoorraad` int(11) DEFAULT NULL,
  `Bestellingid` int(11) DEFAULT NULL,
  `Administratie` varchar(50) NOT NULL,
  `OrigineelBestellingId` int(11) DEFAULT NULL,
  `Omschrijving` varchar(255) DEFAULT NULL,
  `Reden` enum('cadeau','beschadigd','nieuw','retour uitgever','eigen gebruik','recensie','boekevent','overige','ncoi') DEFAULT NULL,
  PRIMARY KEY (`Id`),
  KEY `ean` (`Ean`),
  KEY `orderregelid` (`Orderregelid`)
) ENGINE=InnoDB AUTO_INCREMENT=109020 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED;

--
-- Table structure for table `Voorraadreserveringen`
--

CREATE TABLE `Voorraadreserveringen` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Ean` char(13) CHARACTER SET utf8 DEFAULT NULL,
  `Mutatie` int(11) DEFAULT NULL,
  `DT` datetime DEFAULT NULL,
  `Orderregelid` int(11) DEFAULT NULL,
  `Gebruiker` char(5) DEFAULT NULL,
  `Voorraad` int(11) DEFAULT NULL,
  `Debug` varchar(255) DEFAULT NULL,
  `Klantid` int(11) DEFAULT NULL,
  `Type` enum('besteld','geannuleerd','gecorrigeerd','ingepakt','uit backorder','toegevoegd','gecrediteerd','verwijderd','niet inpakken','niet inpakken ongedaan') DEFAULT NULL,
  `Bestellingid` int(11) DEFAULT NULL,
  `VoorraadOud` int(11) DEFAULT NULL,
  `FysiekeVoorraad` int(11) DEFAULT NULL,
  `BeschikbareVoorraad` int(11) DEFAULT NULL,
  `Administratie` varchar(50) NOT NULL,
  `OrigineelBestellingId` int(11) DEFAULT NULL,
  `Omschrijving` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  KEY `Ean` (`Ean`),
  KEY `orderregelid` (`Orderregelid`)
) ENGINE=InnoDB AUTO_INCREMENT=172153 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

--
-- Dumping routines for database 'Voorraadbeheer_temp'
--

--
-- Current Database: `Zendingen`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `Zendingen` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `Zendingen`;

--
-- Table structure for table `Itpw`
--

CREATE TABLE `Itpw` (
  `Factuurnr` int(11) NOT NULL,
  `Debtor` int(11) NOT NULL,
  `Regel1` varchar(100) DEFAULT NULL,
  `Regel2` varchar(100) DEFAULT NULL,
  `Aanhef` varchar(100) DEFAULT NULL,
  `Adres` varchar(100) DEFAULT NULL,
  `Huisnr` int(11) DEFAULT NULL,
  `Toevoeging` varchar(20) DEFAULT NULL,
  `Postcode` varchar(10) DEFAULT NULL,
  `Plaats` varchar(35) DEFAULT NULL,
  `DT` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Factuurnr`,`Debtor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `MeercolliVolgnummers`
--

CREATE TABLE `MeercolliVolgnummers` (
  `Volgnummer` int(11) NOT NULL AUTO_INCREMENT,
  `Database` char(30) NOT NULL,
  `Bestellingid` int(11) NOT NULL,
  `Collinr` int(11) NOT NULL,
  `DT` datetime NOT NULL,
  PRIMARY KEY (`Volgnummer`)
) ENGINE=InnoDB AUTO_INCREMENT=40981 DEFAULT CHARSET=latin1;

--
-- Table structure for table `StatusCodes`
--

CREATE TABLE `StatusCodes` (
  `V60` char(1) NOT NULL,
  `V70` int(11) NOT NULL,
  `Code` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`V60`,`V70`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `TerugmeldBestanden`
--

CREATE TABLE `TerugmeldBestanden` (
  `Filename` varchar(255) NOT NULL,
  `DT` datetime NOT NULL,
  `File` mediumtext NOT NULL,
  `Processed` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Filename`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `Terugmeldingen`
--

CREATE TABLE `Terugmeldingen` (
  `TerugmeldId` decimal(12,0) NOT NULL,
  `Barcode` char(16) NOT NULL,
  `DT` datetime NOT NULL,
  `Referentie` char(35) NOT NULL,
  `ID` int(11) NOT NULL,
  `V60` char(1) NOT NULL,
  `V70` int(11) NOT NULL,
  `Gewicht` int(11) NOT NULL,
  `Locatie` char(35) NOT NULL,
  `Proces` char(35) NOT NULL,
  PRIMARY KEY (`TerugmeldId`,`Barcode`),
  KEY `NewIndex1` (`Barcode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER DATABASE `Zendingen` CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`sander`@`%`*/ /*!50003 TRIGGER `after_insert_terugmeldigen` AFTER INSERT ON `Terugmeldingen` 
    FOR EACH ROW BEGIN
	IF NEW.V60 = 'I' AND NEW.V70 <> '8' THEN
		UPDATE Zendingen.Zendingen SET DTAflevering = NEW.DT, Afgeleverd = 1 WHERE Barcode = NEW.Barcode;
	END IF;
	IF NEW.V60 = 'K' AND NEW.V70 = '70' THEN
		UPDATE Zendingen.Zendingen SET DTAflevering = NEW.DT, Afgeleverd = 1 WHERE Barcode = NEW.Barcode;
	END IF;
	
    END */;;
DELIMITER ;
ALTER DATABASE `Zendingen` CHARACTER SET utf8 COLLATE utf8_general_ci ;

--
-- Table structure for table `Volgnummers`
--

CREATE TABLE `Volgnummers` (
  `key` char(30) NOT NULL,
  `value` int(11) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `VoormeldBestanden`
--

CREATE TABLE `VoormeldBestanden` (
  `Filename` varchar(255) NOT NULL,
  `DT` datetime NOT NULL,
  `File` mediumtext NOT NULL,
  PRIMARY KEY (`Filename`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `Zendingen`
--

CREATE TABLE `Zendingen` (
  `Barcode` char(20) NOT NULL,
  `Database` enum('handmatig','Managementboek_Klanten','Juridischboek_Klanten','Computerboek_Klanten','Test_Klanten','itpw','Klant_Managementboek','Klant_Computerboek','Klant_Juridischboek') DEFAULT NULL,
  `BestellingId` int(11) DEFAULT '0',
  `DTAanmaak` datetime DEFAULT '0000-00-00 00:00:00',
  `DTVoormelding` datetime DEFAULT '0000-00-00 00:00:00',
  `DTAflevering` datetime DEFAULT '0000-00-00 00:00:00',
  `Voorgemeld` tinyint(1) DEFAULT '0',
  `Afgeleverd` tinyint(1) DEFAULT '0',
  `ColliNr` tinyint(4) NOT NULL DEFAULT '1',
  `AantalColli` tinyint(4) NOT NULL DEFAULT '1',
  `EersteCollo` char(20) NOT NULL,
  `MailedTNT` tinyint(4) NOT NULL DEFAULT '0',
  `ZendingPostcode` char(7) NOT NULL,
  `ZendingHuisnummer` int(11) NOT NULL DEFAULT '0',
  `ZendingHuisnummerToevoeging` char(5) NOT NULL,
  PRIMARY KEY (`Barcode`),
  KEY `NewIndex1` (`BestellingId`,`Database`),
  KEY `MailedTNT` (`MailedTNT`),
  KEY `Voorgemeld` (`Voorgemeld`,`DTAanmaak`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping routines for database 'Zendingen'
--

--
-- Current Database: `apache`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `apache` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `apache`;

--
-- Table structure for table `vhosts`
--

CREATE TABLE `vhosts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  `container` text CHARACTER SET utf8 NOT NULL,
  `name` varchar(25) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`),
  KEY `active` (`active`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

--
-- Dumping routines for database 'apache'
--

--
-- Current Database: `boom`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `boom` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `boom`;

--
-- Table structure for table `boom`
--

CREATE TABLE `boom` (
  `ean` varchar(13) DEFAULT NULL,
  `ISBN13` varchar(255) NOT NULL,
  `TITEL` varchar(255) DEFAULT NULL,
  `ONDERTITEL` varchar(255) DEFAULT NULL,
  `AUTEURS` varchar(255) DEFAULT NULL,
  `DRUK` varchar(255) DEFAULT NULL,
  `JAAR` varchar(255) DEFAULT NULL,
  `PAGINA'S` varchar(255) DEFAULT NULL,
  `PRIJS` varchar(255) DEFAULT NULL,
  `Vernietig-ingsdatum` varchar(255) DEFAULT NULL,
  `OPMERKINGEN` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ISBN13`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `boom_copy`
--

CREATE TABLE `boom_copy` (
  `ean` varchar(13) DEFAULT NULL,
  `ISBN13` varchar(255) NOT NULL,
  `TITEL` varchar(255) DEFAULT NULL,
  `ONDERTITEL` varchar(255) DEFAULT NULL,
  `AUTEURS` varchar(255) DEFAULT NULL,
  `DRUK` varchar(255) DEFAULT NULL,
  `JAAR` varchar(255) DEFAULT NULL,
  `PAGINA'S` varchar(255) DEFAULT NULL,
  `PRIJS` varchar(255) DEFAULT NULL,
  `Vernietig-ingsdatum` varchar(255) DEFAULT NULL,
  `OPMERKINGEN` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`ISBN13`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping routines for database 'boom'
--

--
-- Current Database: `cms2`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cms2` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `cms2`;

--
-- Table structure for table `Banners`
--

CREATE TABLE `Banners` (
  `banner` varchar(100) NOT NULL,
  `url` text NOT NULL,
  `img` text NOT NULL,
  PRIMARY KEY (`banner`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `content_params`
--

CREATE TABLE `content_params` (
  `content_param_id` int(10) unsigned NOT NULL,
  `content_id` int(10) unsigned NOT NULL,
  `param_name` varchar(255) NOT NULL,
  `param_value` text,
  `value_order` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`content_id`,`param_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

--
-- Temporary table structure for view `page_content_params`
--

/*!50001 DROP VIEW IF EXISTS `page_content_params`*/;
/*!50001 CREATE TABLE `page_content_params` (
  `content_id` tinyint NOT NULL,
  `page_id` tinyint NOT NULL,
  `content_param_id` tinyint NOT NULL,
  `param_name` tinyint NOT NULL,
  `param_value` tinyint NOT NULL,
  `value_order` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `page_contents`
--

CREATE TABLE `page_contents` (
  `page_id` int(10) unsigned NOT NULL,
  `content_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`content_id`)
) ENGINE=InnoDB AUTO_INCREMENT=19424 DEFAULT CHARSET=latin1;

--
-- Table structure for table `page_params`
--

CREATE TABLE `page_params` (
  `page_id` int(10) unsigned NOT NULL,
  `param_name` varchar(255) NOT NULL,
  `param_value` text,
  `value_order` int(10) unsigned NOT NULL,
  PRIMARY KEY (`page_id`,`param_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `pages`
--

CREATE TABLE `pages` (
  `page_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `page_name` varchar(255) NOT NULL,
  `published` tinyint(1) DEFAULT '1',
  `start_dt` date DEFAULT NULL,
  `end_dt` date DEFAULT NULL,
  PRIMARY KEY (`page_id`)
) ENGINE=InnoDB AUTO_INCREMENT=19234 DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `pages_totaal`
--

/*!50001 DROP VIEW IF EXISTS `pages_totaal`*/;
/*!50001 CREATE TABLE `pages_totaal` (
  `page_id` tinyint NOT NULL,
  `site_id` tinyint NOT NULL,
  `site_name` tinyint NOT NULL,
  `site_domain` tinyint NOT NULL,
  `site_directory` tinyint NOT NULL,
  `publishes_to` tinyint NOT NULL,
  `klantendb` tinyint NOT NULL,
  `boekendb` tinyint NOT NULL,
  `page_name` tinyint NOT NULL,
  `published` tinyint NOT NULL,
  `start_dt` tinyint NOT NULL,
  `end_dt` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `redirects`
--

CREATE TABLE `redirects` (
  `fromurl` varchar(255) NOT NULL,
  `tourl` varchar(255) NOT NULL,
  `siteid` int(11) NOT NULL DEFAULT '1005',
  PRIMARY KEY (`fromurl`,`siteid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `site_pages`
--

CREATE TABLE `site_pages` (
  `site_id` int(10) unsigned NOT NULL,
  `page_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`site_id`,`page_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Table structure for table `site_params`
--

CREATE TABLE `site_params` (
  `site_param_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `site_id` int(10) unsigned NOT NULL,
  `param_name` varchar(255) DEFAULT NULL,
  `param_value` text,
  `value_order` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`site_param_id`)
) ENGINE=InnoDB AUTO_INCREMENT=794 DEFAULT CHARSET=latin1;

--
-- Table structure for table `sites`
--

CREATE TABLE `sites` (
  `site_id` int(11) NOT NULL,
  `site_name` varchar(255) DEFAULT NULL,
  `site_domain` varchar(255) DEFAULT NULL,
  `site_directory` varchar(255) DEFAULT NULL,
  `publishes_to` int(11) DEFAULT NULL,
  `klantendb` varchar(255) DEFAULT NULL,
  `boekendb` varchar(255) DEFAULT NULL,
  `show` int(1) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`site_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;

--
-- Dumping routines for database 'cms2'
--

--
-- Current Database: `common_schema`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `common_schema` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `common_schema`;

--
-- Temporary table structure for view `_bare_grantee_grants`
--

/*!50001 DROP VIEW IF EXISTS `_bare_grantee_grants`*/;
/*!50001 CREATE TABLE `_bare_grantee_grants` (
  `GRANTEE` tinyint NOT NULL,
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `sql_grants` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_columns_privileges`
--

/*!50001 DROP VIEW IF EXISTS `_columns_privileges`*/;
/*!50001 CREATE TABLE `_columns_privileges` (
  `GRANTEE` tinyint NOT NULL,
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `IS_GRANTABLE` tinyint NOT NULL,
  `column_privileges` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_flattened_keys`
--

/*!50001 DROP VIEW IF EXISTS `_flattened_keys`*/;
/*!50001 CREATE TABLE `_flattened_keys` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `INDEX_NAME` tinyint NOT NULL,
  `non_unique` tinyint NOT NULL,
  `subpart_exists` tinyint NOT NULL,
  `index_columns` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `_global_qs_variables`
--

CREATE TABLE `_global_qs_variables` (
  `server_id` int(10) unsigned NOT NULL,
  `session_id` int(10) unsigned NOT NULL,
  `variable_name` varchar(65) CHARACTER SET ascii NOT NULL,
  `mapped_user_defined_variable_name` varchar(65) CHARACTER SET ascii NOT NULL,
  `declaration_depth` int(10) unsigned NOT NULL,
  `declaration_id` int(10) unsigned NOT NULL,
  `scope_end_id` int(10) unsigned NOT NULL,
  `value_snapshot` text,
  PRIMARY KEY (`server_id`,`session_id`,`variable_name`),
  KEY `declaration_depth` (`declaration_depth`),
  KEY `declaration_id` (`declaration_id`),
  KEY `scope_end_id` (`scope_end_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `_global_script_report_data`
--

CREATE TABLE `_global_script_report_data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `info` text,
  `server_id` int(10) unsigned NOT NULL,
  `session_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`,`server_id`,`session_id`),
  KEY `server_id` (`server_id`,`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `_global_split_column_names_table`
--

CREATE TABLE `_global_split_column_names_table` (
  `server_id` int(10) unsigned NOT NULL,
  `session_id` int(10) unsigned NOT NULL,
  `column_order` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `split_table_name` varchar(128) DEFAULT NULL,
  `split_index_name` varchar(128) DEFAULT NULL,
  `column_name` varchar(128) DEFAULT NULL,
  `min_variable_name` varchar(128) DEFAULT NULL,
  `max_variable_name` varchar(128) DEFAULT NULL,
  `range_start_variable_name` varchar(128) DEFAULT NULL,
  `range_end_variable_name` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`server_id`,`session_id`,`column_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `_global_sql_tokens`
--

CREATE TABLE `_global_sql_tokens` (
  `server_id` int(10) unsigned NOT NULL,
  `session_id` int(10) unsigned NOT NULL DEFAULT '0',
  `id` int(10) unsigned NOT NULL DEFAULT '0',
  `start` int(10) unsigned NOT NULL,
  `level` int(11) NOT NULL,
  `token` text,
  `state` text NOT NULL,
  PRIMARY KEY (`server_id`,`session_id`,`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `_global_status_sleep`
--

/*!50001 DROP VIEW IF EXISTS `_global_status_sleep`*/;
/*!50001 CREATE TABLE `_global_status_sleep` (
  `VARIABLE_NAME` tinyint NOT NULL,
  `VARIABLE_VALUE` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_global_status_wrapper`
--

/*!50001 DROP VIEW IF EXISTS `_global_status_wrapper`*/;
/*!50001 CREATE TABLE `_global_status_wrapper` (
  `VARIABLE_NAME` tinyint NOT NULL,
  `VARIABLE_VALUE` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `_known_thread_states`
--

CREATE TABLE `_known_thread_states` (
  `state` varchar(128) CHARACTER SET ascii NOT NULL,
  `state_type` enum('replication_sql_thread','replication_io_thread','unknown') DEFAULT NULL,
  PRIMARY KEY (`state`),
  KEY `state_type` (`state_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `_named_scripts`
--

CREATE TABLE `_named_scripts` (
  `script_name` varchar(64) CHARACTER SET ascii NOT NULL,
  `script_text` text,
  PRIMARY KEY (`script_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `_processlist_grantees_exploded`
--

/*!50001 DROP VIEW IF EXISTS `_processlist_grantees_exploded`*/;
/*!50001 CREATE TABLE `_processlist_grantees_exploded` (
  `id` tinyint NOT NULL,
  `sql_kill_query` tinyint NOT NULL,
  `sql_kill_connection` tinyint NOT NULL,
  `grantee` tinyint NOT NULL,
  `unqualified_grantee` tinyint NOT NULL,
  `grantee_host` tinyint NOT NULL,
  `grantee_user` tinyint NOT NULL,
  `qualified_user_host` tinyint NOT NULL,
  `unqualified_user_host` tinyint NOT NULL,
  `hostname` tinyint NOT NULL,
  `user` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_qs_variables`
--

/*!50001 DROP VIEW IF EXISTS `_qs_variables`*/;
/*!50001 CREATE TABLE `_qs_variables` (
  `server_id` tinyint NOT NULL,
  `session_id` tinyint NOT NULL,
  `variable_name` tinyint NOT NULL,
  `mapped_user_defined_variable_name` tinyint NOT NULL,
  `declaration_depth` tinyint NOT NULL,
  `declaration_id` tinyint NOT NULL,
  `scope_end_id` tinyint NOT NULL,
  `value_snapshot` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_query_profiling_minmax`
--

/*!50001 DROP VIEW IF EXISTS `_query_profiling_minmax`*/;
/*!50001 CREATE TABLE `_query_profiling_minmax` (
  `min_query_id` tinyint NOT NULL,
  `max_query_id` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_query_profiling_summary`
--

/*!50001 DROP VIEW IF EXISTS `_query_profiling_summary`*/;
/*!50001 CREATE TABLE `_query_profiling_summary` (
  `QUERY_ID` tinyint NOT NULL,
  `count_state_calls` tinyint NOT NULL,
  `count_distinct_states` tinyint NOT NULL,
  `sum_duration` tinyint NOT NULL,
  `sum_cpu_user` tinyint NOT NULL,
  `sum_cpu_system` tinyint NOT NULL,
  `sum_swpas` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `_rdebug_breakpoint_hints`
--

CREATE TABLE `_rdebug_breakpoint_hints` (
  `worker_id` bigint(20) unsigned NOT NULL,
  `routine_schema` varchar(64) NOT NULL DEFAULT '',
  `routine_name` varchar(64) NOT NULL DEFAULT '',
  `statement_id` int(10) unsigned NOT NULL DEFAULT '0',
  `conditional_expression` text,
  PRIMARY KEY (`worker_id`,`routine_schema`,`routine_name`,`statement_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_routine_statements`
--

CREATE TABLE `_rdebug_routine_statements` (
  `routine_schema` varchar(64) NOT NULL,
  `routine_name` varchar(64) NOT NULL,
  `statement_id` int(10) unsigned NOT NULL,
  `statement_start_pos` int(10) unsigned DEFAULT '0',
  `statement_end_pos` int(10) unsigned DEFAULT '0',
  PRIMARY KEY (`routine_schema`,`routine_name`,`statement_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_routine_variables`
--

CREATE TABLE `_rdebug_routine_variables` (
  `routine_schema` varchar(64) NOT NULL,
  `routine_name` varchar(64) NOT NULL,
  `variable_name` varchar(128) NOT NULL,
  `variable_scope_id_start` int(10) unsigned NOT NULL DEFAULT '0',
  `variable_scope_id_end` int(10) unsigned DEFAULT '0',
  `variable_type` enum('param','local','user_defined') NOT NULL,
  PRIMARY KEY (`routine_schema`,`routine_name`,`variable_name`,`variable_scope_id_start`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_routine_variables_state`
--

CREATE TABLE `_rdebug_routine_variables_state` (
  `worker_id` bigint(20) unsigned NOT NULL,
  `stack_level` int(10) unsigned NOT NULL,
  `routine_schema` varchar(64) NOT NULL,
  `routine_name` varchar(64) NOT NULL,
  `variable_name` varchar(128) NOT NULL,
  `variable_value` blob,
  `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`worker_id`,`stack_level`,`routine_schema`,`routine_name`,`variable_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_stack_state`
--

CREATE TABLE `_rdebug_stack_state` (
  `worker_id` bigint(20) unsigned NOT NULL,
  `stack_level` int(10) unsigned NOT NULL,
  `routine_schema` varchar(64) NOT NULL,
  `routine_name` varchar(64) NOT NULL,
  `statement_id` int(10) unsigned NOT NULL,
  `entry_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`worker_id`,`stack_level`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_stats`
--

CREATE TABLE `_rdebug_stats` (
  `worker_id` bigint(20) unsigned NOT NULL,
  `routine_schema` varchar(64) NOT NULL,
  `routine_name` varchar(64) NOT NULL,
  `statement_id` int(10) unsigned NOT NULL DEFAULT '0',
  `count_visits` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`worker_id`,`routine_schema`,`routine_name`,`statement_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Table structure for table `_rdebug_step_hints`
--

CREATE TABLE `_rdebug_step_hints` (
  `worker_id` bigint(20) unsigned NOT NULL,
  `hint_type` enum('step_into','step_over','step_out','run') NOT NULL DEFAULT 'step_into',
  `stack_level` int(10) unsigned DEFAULT NULL,
  `is_consumed` tinyint(3) unsigned DEFAULT '0',
  PRIMARY KEY (`worker_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `_script_report_data`
--

/*!50001 DROP VIEW IF EXISTS `_script_report_data`*/;
/*!50001 CREATE TABLE `_script_report_data` (
  `id` tinyint NOT NULL,
  `info` tinyint NOT NULL,
  `server_id` tinyint NOT NULL,
  `session_id` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `_script_statements`
--

CREATE TABLE `_script_statements` (
  `statement` varchar(16) CHARACTER SET ascii NOT NULL,
  `statement_type` enum('sql','script','script,sql','unknown') DEFAULT NULL,
  PRIMARY KEY (`statement`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `_split_column_names_table`
--

/*!50001 DROP VIEW IF EXISTS `_split_column_names_table`*/;
/*!50001 CREATE TABLE `_split_column_names_table` (
  `server_id` tinyint NOT NULL,
  `session_id` tinyint NOT NULL,
  `column_order` tinyint NOT NULL,
  `split_table_name` tinyint NOT NULL,
  `split_index_name` tinyint NOT NULL,
  `column_name` tinyint NOT NULL,
  `min_variable_name` tinyint NOT NULL,
  `max_variable_name` tinyint NOT NULL,
  `range_start_variable_name` tinyint NOT NULL,
  `range_end_variable_name` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_accounts_base`
--

/*!50001 DROP VIEW IF EXISTS `_sql_accounts_base`*/;
/*!50001 CREATE TABLE `_sql_accounts_base` (
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `grantee` tinyint NOT NULL,
  `password` tinyint NOT NULL,
  `is_empty_password` tinyint NOT NULL,
  `is_new_password` tinyint NOT NULL,
  `is_old_password` tinyint NOT NULL,
  `is_blocked` tinyint NOT NULL,
  `reversed_password` tinyint NOT NULL,
  `untiled_password` tinyint NOT NULL,
  `tiled_password` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_accounts_password`
--

/*!50001 DROP VIEW IF EXISTS `_sql_accounts_password`*/;
/*!50001 CREATE TABLE `_sql_accounts_password` (
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `grantee` tinyint NOT NULL,
  `password` tinyint NOT NULL,
  `is_empty_password` tinyint NOT NULL,
  `is_new_password` tinyint NOT NULL,
  `is_old_password` tinyint NOT NULL,
  `is_blocked` tinyint NOT NULL,
  `reversed_password` tinyint NOT NULL,
  `untiled_password` tinyint NOT NULL,
  `tiled_password` tinyint NOT NULL,
  `password_for_sql_block_account` tinyint NOT NULL,
  `password_for_sql_release_account` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_alter_table_tokudb_internal`
--

/*!50001 DROP VIEW IF EXISTS `_sql_alter_table_tokudb_internal`*/;
/*!50001 CREATE TABLE `_sql_alter_table_tokudb_internal` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `ENGINE` tinyint NOT NULL,
  `alter_fast_clause` tinyint NOT NULL,
  `alter_small_clause` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_grants_components`
--

/*!50001 DROP VIEW IF EXISTS `_sql_grants_components`*/;
/*!50001 CREATE TABLE `_sql_grants_components` (
  `GRANTEE` tinyint NOT NULL,
  `priv_level` tinyint NOT NULL,
  `priv_level_name` tinyint NOT NULL,
  `object_type` tinyint NOT NULL,
  `object_schema` tinyint NOT NULL,
  `object_name` tinyint NOT NULL,
  `current_privileges` tinyint NOT NULL,
  `IS_GRANTABLE` tinyint NOT NULL,
  `result_order` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_range_partitions_analysis`
--

/*!50001 DROP VIEW IF EXISTS `_sql_range_partitions_analysis`*/;
/*!50001 CREATE TABLE `_sql_range_partitions_analysis` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `count_partitions` tinyint NOT NULL,
  `count_past_timestamp` tinyint NOT NULL,
  `count_future_timestamp` tinyint NOT NULL,
  `count_past_from_unixtime` tinyint NOT NULL,
  `count_future_from_unixtime` tinyint NOT NULL,
  `count_past_from_days` tinyint NOT NULL,
  `count_future_from_days` tinyint NOT NULL,
  `first_partition_name` tinyint NOT NULL,
  `first_partition_name_skipping_zero` tinyint NOT NULL,
  `last_partition_name` tinyint NOT NULL,
  `has_maxvalue` tinyint NOT NULL,
  `maxvalue_partition_name` tinyint NOT NULL,
  `max_partition_description` tinyint NOT NULL,
  `next_partition_description` tinyint NOT NULL,
  `next_partition_human_description` tinyint NOT NULL,
  `count_past_partitions` tinyint NOT NULL,
  `count_future_partitions` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_range_partitions_base`
--

/*!50001 DROP VIEW IF EXISTS `_sql_range_partitions_base`*/;
/*!50001 CREATE TABLE `_sql_range_partitions_base` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `unquoted_description` tinyint NOT NULL,
  `valid_from_days` tinyint NOT NULL,
  `diff` tinyint NOT NULL,
  `diff_day` tinyint NOT NULL,
  `diff_week` tinyint NOT NULL,
  `diff_month` tinyint NOT NULL,
  `diff_year` tinyint NOT NULL,
  `diff_day_from_unixtime` tinyint NOT NULL,
  `diff_week_from_unixtime` tinyint NOT NULL,
  `diff_month_from_unixtime` tinyint NOT NULL,
  `diff_year_from_unixtime` tinyint NOT NULL,
  `diff_day_from_days` tinyint NOT NULL,
  `diff_week_from_days` tinyint NOT NULL,
  `diff_month_from_days` tinyint NOT NULL,
  `diff_year_from_days` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_range_partitions_beautified`
--

/*!50001 DROP VIEW IF EXISTS `_sql_range_partitions_beautified`*/;
/*!50001 CREATE TABLE `_sql_range_partitions_beautified` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `count_partitions` tinyint NOT NULL,
  `count_past_timestamp` tinyint NOT NULL,
  `count_future_timestamp` tinyint NOT NULL,
  `count_past_from_unixtime` tinyint NOT NULL,
  `count_future_from_unixtime` tinyint NOT NULL,
  `count_past_from_days` tinyint NOT NULL,
  `count_future_from_days` tinyint NOT NULL,
  `first_partition_name` tinyint NOT NULL,
  `first_partition_name_skipping_zero` tinyint NOT NULL,
  `last_partition_name` tinyint NOT NULL,
  `has_maxvalue` tinyint NOT NULL,
  `maxvalue_partition_name` tinyint NOT NULL,
  `max_partition_description` tinyint NOT NULL,
  `next_partition_description` tinyint NOT NULL,
  `next_partition_human_description` tinyint NOT NULL,
  `count_past_partitions` tinyint NOT NULL,
  `count_future_partitions` tinyint NOT NULL,
  `next_partition_name` tinyint NOT NULL,
  `next_partition_human_description_is_datetime` tinyint NOT NULL,
  `next_partition_human_description_comment` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_range_partitions_diff`
--

/*!50001 DROP VIEW IF EXISTS `_sql_range_partitions_diff`*/;
/*!50001 CREATE TABLE `_sql_range_partitions_diff` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `diff` tinyint NOT NULL,
  `diff_day` tinyint NOT NULL,
  `diff_week` tinyint NOT NULL,
  `diff_month` tinyint NOT NULL,
  `diff_year` tinyint NOT NULL,
  `diff_day_from_unixtime` tinyint NOT NULL,
  `diff_week_from_unixtime` tinyint NOT NULL,
  `diff_month_from_unixtime` tinyint NOT NULL,
  `diff_year_from_unixtime` tinyint NOT NULL,
  `diff_day_from_days` tinyint NOT NULL,
  `diff_week_from_days` tinyint NOT NULL,
  `diff_month_from_days` tinyint NOT NULL,
  `diff_year_from_days` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_range_partitions_summary`
--

/*!50001 DROP VIEW IF EXISTS `_sql_range_partitions_summary`*/;
/*!50001 CREATE TABLE `_sql_range_partitions_summary` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `count_partitions` tinyint NOT NULL,
  `count_past_timestamp` tinyint NOT NULL,
  `count_future_timestamp` tinyint NOT NULL,
  `count_past_from_unixtime` tinyint NOT NULL,
  `count_future_from_unixtime` tinyint NOT NULL,
  `count_past_from_days` tinyint NOT NULL,
  `count_future_from_days` tinyint NOT NULL,
  `first_partition_name` tinyint NOT NULL,
  `first_partition_name_skipping_zero` tinyint NOT NULL,
  `last_partition_name` tinyint NOT NULL,
  `has_maxvalue` tinyint NOT NULL,
  `maxvalue_partition_name` tinyint NOT NULL,
  `max_partition_description` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_table_keys`
--

/*!50001 DROP VIEW IF EXISTS `_sql_table_keys`*/;
/*!50001 CREATE TABLE `_sql_table_keys` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `INDEX_NAME` tinyint NOT NULL,
  `sql_index_definition` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_sql_tokens`
--

/*!50001 DROP VIEW IF EXISTS `_sql_tokens`*/;
/*!50001 CREATE TABLE `_sql_tokens` (
  `server_id` tinyint NOT NULL,
  `session_id` tinyint NOT NULL,
  `id` tinyint NOT NULL,
  `start` tinyint NOT NULL,
  `level` tinyint NOT NULL,
  `token` tinyint NOT NULL,
  `state` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `_unique_keys`
--

/*!50001 DROP VIEW IF EXISTS `_unique_keys`*/;
/*!50001 CREATE TABLE `_unique_keys` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `INDEX_NAME` tinyint NOT NULL,
  `COUNT_COLUMN_IN_INDEX` tinyint NOT NULL,
  `has_nullable` tinyint NOT NULL,
  `is_primary` tinyint NOT NULL,
  `COLUMN_NAMES` tinyint NOT NULL,
  `FIRST_COLUMN_NAME` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `_waits`
--

CREATE TABLE `_waits` (
  `wait_name` varchar(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
  `wait_value` bigint(20) unsigned NOT NULL,
  `first_entry_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `last_entry_time` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`wait_name`),
  KEY `last_entry_time` (`last_entry_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `auto_increment_columns`
--

/*!50001 DROP VIEW IF EXISTS `auto_increment_columns`*/;
/*!50001 CREATE TABLE `auto_increment_columns` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `COLUMN_NAME` tinyint NOT NULL,
  `DATA_TYPE` tinyint NOT NULL,
  `COLUMN_TYPE` tinyint NOT NULL,
  `is_signed` tinyint NOT NULL,
  `is_unsigned` tinyint NOT NULL,
  `max_value` tinyint NOT NULL,
  `AUTO_INCREMENT` tinyint NOT NULL,
  `auto_increment_ratio` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `candidate_keys`
--

/*!50001 DROP VIEW IF EXISTS `candidate_keys`*/;
/*!50001 CREATE TABLE `candidate_keys` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `index_name` tinyint NOT NULL,
  `has_nullable` tinyint NOT NULL,
  `is_primary` tinyint NOT NULL,
  `column_names` tinyint NOT NULL,
  `count_column_in_index` tinyint NOT NULL,
  `data_type` tinyint NOT NULL,
  `character_set_name` tinyint NOT NULL,
  `candidate_key_rank_in_table` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `candidate_keys_recommended`
--

/*!50001 DROP VIEW IF EXISTS `candidate_keys_recommended`*/;
/*!50001 CREATE TABLE `candidate_keys_recommended` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `recommended_index_name` tinyint NOT NULL,
  `has_nullable` tinyint NOT NULL,
  `is_primary` tinyint NOT NULL,
  `count_column_in_index` tinyint NOT NULL,
  `column_names` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `data_size_per_engine`
--

/*!50001 DROP VIEW IF EXISTS `data_size_per_engine`*/;
/*!50001 CREATE TABLE `data_size_per_engine` (
  `ENGINE` tinyint NOT NULL,
  `count_tables` tinyint NOT NULL,
  `data_size` tinyint NOT NULL,
  `index_size` tinyint NOT NULL,
  `total_size` tinyint NOT NULL,
  `largest_table` tinyint NOT NULL,
  `largest_table_size` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `data_size_per_schema`
--

/*!50001 DROP VIEW IF EXISTS `data_size_per_schema`*/;
/*!50001 CREATE TABLE `data_size_per_schema` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `count_tables` tinyint NOT NULL,
  `count_views` tinyint NOT NULL,
  `distinct_engines` tinyint NOT NULL,
  `data_size` tinyint NOT NULL,
  `index_size` tinyint NOT NULL,
  `total_size` tinyint NOT NULL,
  `largest_table` tinyint NOT NULL,
  `largest_table_size` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `debugged_routines`
--

/*!50001 DROP VIEW IF EXISTS `debugged_routines`*/;
/*!50001 CREATE TABLE `debugged_routines` (
  `ROUTINE_SCHEMA` tinyint NOT NULL,
  `ROUTINE_NAME` tinyint NOT NULL,
  `ROUTINE_TYPE` tinyint NOT NULL,
  `sql_undebug_routine` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `global_status_diff`
--

/*!50001 DROP VIEW IF EXISTS `global_status_diff`*/;
/*!50001 CREATE TABLE `global_status_diff` (
  `variable_name` tinyint NOT NULL,
  `variable_value_0` tinyint NOT NULL,
  `variable_value_1` tinyint NOT NULL,
  `variable_value_diff` tinyint NOT NULL,
  `variable_value_psec` tinyint NOT NULL,
  `variable_value_pminute` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `global_status_diff_clean`
--

/*!50001 DROP VIEW IF EXISTS `global_status_diff_clean`*/;
/*!50001 CREATE TABLE `global_status_diff_clean` (
  `variable_name` tinyint NOT NULL,
  `variable_value_0` tinyint NOT NULL,
  `variable_value_1` tinyint NOT NULL,
  `variable_value_diff` tinyint NOT NULL,
  `variable_value_psec` tinyint NOT NULL,
  `variable_value_pminute` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `global_status_diff_nonzero`
--

/*!50001 DROP VIEW IF EXISTS `global_status_diff_nonzero`*/;
/*!50001 CREATE TABLE `global_status_diff_nonzero` (
  `variable_name` tinyint NOT NULL,
  `variable_value_0` tinyint NOT NULL,
  `variable_value_1` tinyint NOT NULL,
  `variable_value_diff` tinyint NOT NULL,
  `variable_value_psec` tinyint NOT NULL,
  `variable_value_pminute` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `help_content`
--

CREATE TABLE `help_content` (
  `topic` varchar(32) CHARACTER SET ascii NOT NULL,
  `help_message` text NOT NULL,
  PRIMARY KEY (`topic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `innodb_locked_transactions`
--

/*!50001 DROP VIEW IF EXISTS `innodb_locked_transactions`*/;
/*!50001 CREATE TABLE `innodb_locked_transactions` (
  `locked_trx_id` tinyint NOT NULL,
  `locked_trx_started` tinyint NOT NULL,
  `locked_trx_wait_started` tinyint NOT NULL,
  `locked_trx_mysql_thread_id` tinyint NOT NULL,
  `locked_trx_query` tinyint NOT NULL,
  `requested_lock_id` tinyint NOT NULL,
  `blocking_lock_id` tinyint NOT NULL,
  `locking_trx_id` tinyint NOT NULL,
  `locking_trx_started` tinyint NOT NULL,
  `locking_trx_wait_started` tinyint NOT NULL,
  `locking_trx_mysql_thread_id` tinyint NOT NULL,
  `locking_trx_query` tinyint NOT NULL,
  `trx_wait_seconds` tinyint NOT NULL,
  `sql_kill_blocking_query` tinyint NOT NULL,
  `sql_kill_blocking_connection` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `innodb_simple_locks`
--

/*!50001 DROP VIEW IF EXISTS `innodb_simple_locks`*/;
/*!50001 CREATE TABLE `innodb_simple_locks` (
  `lock_id` tinyint NOT NULL,
  `lock_trx_id` tinyint NOT NULL,
  `lock_type` tinyint NOT NULL,
  `lock_table` tinyint NOT NULL,
  `lock_index` tinyint NOT NULL,
  `lock_data` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `innodb_transactions`
--

/*!50001 DROP VIEW IF EXISTS `innodb_transactions`*/;
/*!50001 CREATE TABLE `innodb_transactions` (
  `trx_id` tinyint NOT NULL,
  `trx_state` tinyint NOT NULL,
  `trx_started` tinyint NOT NULL,
  `trx_requested_lock_id` tinyint NOT NULL,
  `trx_wait_started` tinyint NOT NULL,
  `trx_weight` tinyint NOT NULL,
  `trx_mysql_thread_id` tinyint NOT NULL,
  `trx_query` tinyint NOT NULL,
  `trx_operation_state` tinyint NOT NULL,
  `trx_tables_in_use` tinyint NOT NULL,
  `trx_tables_locked` tinyint NOT NULL,
  `trx_lock_structs` tinyint NOT NULL,
  `trx_lock_memory_bytes` tinyint NOT NULL,
  `trx_rows_locked` tinyint NOT NULL,
  `trx_rows_modified` tinyint NOT NULL,
  `trx_concurrency_tickets` tinyint NOT NULL,
  `trx_isolation_level` tinyint NOT NULL,
  `trx_unique_checks` tinyint NOT NULL,
  `trx_foreign_key_checks` tinyint NOT NULL,
  `trx_last_foreign_key_error` tinyint NOT NULL,
  `trx_adaptive_hash_latched` tinyint NOT NULL,
  `trx_adaptive_hash_timeout` tinyint NOT NULL,
  `trx_is_read_only` tinyint NOT NULL,
  `trx_autocommit_non_locking` tinyint NOT NULL,
  `INFO` tinyint NOT NULL,
  `trx_runtime_seconds` tinyint NOT NULL,
  `trx_wait_seconds` tinyint NOT NULL,
  `trx_idle_seconds` tinyint NOT NULL,
  `sql_kill_query` tinyint NOT NULL,
  `sql_kill_connection` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `innodb_transactions_summary`
--

/*!50001 DROP VIEW IF EXISTS `innodb_transactions_summary`*/;
/*!50001 CREATE TABLE `innodb_transactions_summary` (
  `count_transactions` tinyint NOT NULL,
  `running_transactions` tinyint NOT NULL,
  `locked_transactions` tinyint NOT NULL,
  `distinct_locks` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `last_query_profiling`
--

/*!50001 DROP VIEW IF EXISTS `last_query_profiling`*/;
/*!50001 CREATE TABLE `last_query_profiling` (
  `QUERY_ID` tinyint NOT NULL,
  `STATE` tinyint NOT NULL,
  `state_calls` tinyint NOT NULL,
  `state_sum_duration` tinyint NOT NULL,
  `state_duration_per_call` tinyint NOT NULL,
  `state_duration_pct` tinyint NOT NULL,
  `state_seqs` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `metadata`
--

CREATE TABLE `metadata` (
  `attribute_name` varchar(64) CHARACTER SET ascii NOT NULL,
  `attribute_value` varchar(2048) NOT NULL,
  PRIMARY KEY (`attribute_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `no_pk_innodb_tables`
--

/*!50001 DROP VIEW IF EXISTS `no_pk_innodb_tables`*/;
/*!50001 CREATE TABLE `no_pk_innodb_tables` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `ENGINE` tinyint NOT NULL,
  `candidate_keys` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Table structure for table `numbers`
--

CREATE TABLE `numbers` (
  `n` smallint(5) unsigned NOT NULL,
  PRIMARY KEY (`n`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Temporary table structure for view `processlist_grantees`
--

/*!50001 DROP VIEW IF EXISTS `processlist_grantees`*/;
/*!50001 CREATE TABLE `processlist_grantees` (
  `ID` tinyint NOT NULL,
  `USER` tinyint NOT NULL,
  `HOST` tinyint NOT NULL,
  `DB` tinyint NOT NULL,
  `COMMAND` tinyint NOT NULL,
  `TIME` tinyint NOT NULL,
  `STATE` tinyint NOT NULL,
  `INFO` tinyint NOT NULL,
  `GRANTEE` tinyint NOT NULL,
  `grantee_user` tinyint NOT NULL,
  `grantee_host` tinyint NOT NULL,
  `is_super` tinyint NOT NULL,
  `is_repl` tinyint NOT NULL,
  `is_current` tinyint NOT NULL,
  `sql_kill_query` tinyint NOT NULL,
  `sql_kill_connection` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `processlist_per_userhost`
--

/*!50001 DROP VIEW IF EXISTS `processlist_per_userhost`*/;
/*!50001 CREATE TABLE `processlist_per_userhost` (
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `count_processes` tinyint NOT NULL,
  `active_processes` tinyint NOT NULL,
  `median_active_time` tinyint NOT NULL,
  `median_95pct_active_time` tinyint NOT NULL,
  `max_active_time` tinyint NOT NULL,
  `average_active_time` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `processlist_repl`
--

/*!50001 DROP VIEW IF EXISTS `processlist_repl`*/;
/*!50001 CREATE TABLE `processlist_repl` (
  `ID` tinyint NOT NULL,
  `USER` tinyint NOT NULL,
  `HOST` tinyint NOT NULL,
  `DB` tinyint NOT NULL,
  `COMMAND` tinyint NOT NULL,
  `TIME` tinyint NOT NULL,
  `STATE` tinyint NOT NULL,
  `INFO` tinyint NOT NULL,
  `TIME_MS` tinyint NOT NULL,
  `STAGE` tinyint NOT NULL,
  `MAX_STAGE` tinyint NOT NULL,
  `PROGRESS` tinyint NOT NULL,
  `MEMORY_USED` tinyint NOT NULL,
  `EXAMINED_ROWS` tinyint NOT NULL,
  `QUERY_ID` tinyint NOT NULL,
  `is_system` tinyint NOT NULL,
  `is_io_thread` tinyint NOT NULL,
  `is_sql_thread` tinyint NOT NULL,
  `is_slave` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `processlist_states`
--

/*!50001 DROP VIEW IF EXISTS `processlist_states`*/;
/*!50001 CREATE TABLE `processlist_states` (
  `state` tinyint NOT NULL,
  `count_processes` tinyint NOT NULL,
  `median_state_time` tinyint NOT NULL,
  `median_95pct_state_time` tinyint NOT NULL,
  `max_state_time` tinyint NOT NULL,
  `sum_state_time` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `processlist_summary`
--

/*!50001 DROP VIEW IF EXISTS `processlist_summary`*/;
/*!50001 CREATE TABLE `processlist_summary` (
  `count_processes` tinyint NOT NULL,
  `active_processes` tinyint NOT NULL,
  `sleeping_processes` tinyint NOT NULL,
  `active_queries` tinyint NOT NULL,
  `num_queries_over_1_sec` tinyint NOT NULL,
  `num_queries_over_10_sec` tinyint NOT NULL,
  `num_queries_over_60_sec` tinyint NOT NULL,
  `average_active_time` tinyint NOT NULL,
  `median_95pct_active_time` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `processlist_top`
--

/*!50001 DROP VIEW IF EXISTS `processlist_top`*/;
/*!50001 CREATE TABLE `processlist_top` (
  `ID` tinyint NOT NULL,
  `USER` tinyint NOT NULL,
  `HOST` tinyint NOT NULL,
  `DB` tinyint NOT NULL,
  `COMMAND` tinyint NOT NULL,
  `TIME` tinyint NOT NULL,
  `STATE` tinyint NOT NULL,
  `INFO` tinyint NOT NULL,
  `TIME_MS` tinyint NOT NULL,
  `STAGE` tinyint NOT NULL,
  `MAX_STAGE` tinyint NOT NULL,
  `PROGRESS` tinyint NOT NULL,
  `MEMORY_USED` tinyint NOT NULL,
  `EXAMINED_ROWS` tinyint NOT NULL,
  `QUERY_ID` tinyint NOT NULL,
  `sql_kill_query` tinyint NOT NULL,
  `sql_kill_connection` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `query_profiling`
--

/*!50001 DROP VIEW IF EXISTS `query_profiling`*/;
/*!50001 CREATE TABLE `query_profiling` (
  `QUERY_ID` tinyint NOT NULL,
  `STATE` tinyint NOT NULL,
  `state_calls` tinyint NOT NULL,
  `state_sum_duration` tinyint NOT NULL,
  `state_duration_per_call` tinyint NOT NULL,
  `state_duration_pct` tinyint NOT NULL,
  `state_seqs` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `redundant_keys`
--

/*!50001 DROP VIEW IF EXISTS `redundant_keys`*/;
/*!50001 CREATE TABLE `redundant_keys` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `redundant_index_name` tinyint NOT NULL,
  `redundant_index_columns` tinyint NOT NULL,
  `redundant_index_non_unique` tinyint NOT NULL,
  `dominant_index_name` tinyint NOT NULL,
  `dominant_index_columns` tinyint NOT NULL,
  `dominant_index_non_unique` tinyint NOT NULL,
  `subpart_exists` tinyint NOT NULL,
  `sql_drop_index` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `routine_privileges`
--

/*!50001 DROP VIEW IF EXISTS `routine_privileges`*/;
/*!50001 CREATE TABLE `routine_privileges` (
  `GRANTEE` tinyint NOT NULL,
  `ROUTINE_CATALOG` tinyint NOT NULL,
  `ROUTINE_SCHEMA` tinyint NOT NULL,
  `ROUTINE_NAME` tinyint NOT NULL,
  `ROUTINE_TYPE` tinyint NOT NULL,
  `PRIVILEGE_TYPE` tinyint NOT NULL,
  `IS_GRANTABLE` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `routines`
--

/*!50001 DROP VIEW IF EXISTS `routines`*/;
/*!50001 CREATE TABLE `routines` (
  `SPECIFIC_NAME` tinyint NOT NULL,
  `ROUTINE_CATALOG` tinyint NOT NULL,
  `ROUTINE_SCHEMA` tinyint NOT NULL,
  `ROUTINE_NAME` tinyint NOT NULL,
  `ROUTINE_TYPE` tinyint NOT NULL,
  `DATA_TYPE` tinyint NOT NULL,
  `CHARACTER_MAXIMUM_LENGTH` tinyint NOT NULL,
  `CHARACTER_OCTET_LENGTH` tinyint NOT NULL,
  `NUMERIC_PRECISION` tinyint NOT NULL,
  `NUMERIC_SCALE` tinyint NOT NULL,
  `DATETIME_PRECISION` tinyint NOT NULL,
  `CHARACTER_SET_NAME` tinyint NOT NULL,
  `COLLATION_NAME` tinyint NOT NULL,
  `DTD_IDENTIFIER` tinyint NOT NULL,
  `ROUTINE_BODY` tinyint NOT NULL,
  `ROUTINE_DEFINITION` tinyint NOT NULL,
  `EXTERNAL_NAME` tinyint NOT NULL,
  `EXTERNAL_LANGUAGE` tinyint NOT NULL,
  `PARAMETER_STYLE` tinyint NOT NULL,
  `IS_DETERMINISTIC` tinyint NOT NULL,
  `SQL_DATA_ACCESS` tinyint NOT NULL,
  `SQL_PATH` tinyint NOT NULL,
  `SECURITY_TYPE` tinyint NOT NULL,
  `CREATED` tinyint NOT NULL,
  `LAST_ALTERED` tinyint NOT NULL,
  `SQL_MODE` tinyint NOT NULL,
  `ROUTINE_COMMENT` tinyint NOT NULL,
  `DEFINER` tinyint NOT NULL,
  `CHARACTER_SET_CLIENT` tinyint NOT NULL,
  `COLLATION_CONNECTION` tinyint NOT NULL,
  `DATABASE_COLLATION` tinyint NOT NULL,
  `param_list` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `similar_grants`
--

/*!50001 DROP VIEW IF EXISTS `similar_grants`*/;
/*!50001 CREATE TABLE `similar_grants` (
  `sample_grantee` tinyint NOT NULL,
  `count_grantees` tinyint NOT NULL,
  `similar_grantees` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `slave_hosts`
--

/*!50001 DROP VIEW IF EXISTS `slave_hosts`*/;
/*!50001 CREATE TABLE `slave_hosts` (
  `host` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `slave_status`
--

/*!50001 DROP VIEW IF EXISTS `slave_status`*/;
/*!50001 CREATE TABLE `slave_status` (
  `Slave_Connected_time` tinyint NOT NULL,
  `Slave_IO_Running` tinyint NOT NULL,
  `Slave_SQL_Running` tinyint NOT NULL,
  `Slave_Running` tinyint NOT NULL,
  `Seconds_Behind_Master` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_accounts`
--

/*!50001 DROP VIEW IF EXISTS `sql_accounts`*/;
/*!50001 CREATE TABLE `sql_accounts` (
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `grantee` tinyint NOT NULL,
  `password` tinyint NOT NULL,
  `is_empty_password` tinyint NOT NULL,
  `is_new_password` tinyint NOT NULL,
  `is_old_password` tinyint NOT NULL,
  `is_blocked` tinyint NOT NULL,
  `sql_block_account` tinyint NOT NULL,
  `sql_release_account` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_alter_table`
--

/*!50001 DROP VIEW IF EXISTS `sql_alter_table`*/;
/*!50001 CREATE TABLE `sql_alter_table` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `ENGINE` tinyint NOT NULL,
  `sql_drop_keys` tinyint NOT NULL,
  `sql_add_keys` tinyint NOT NULL,
  `table_options` tinyint NOT NULL,
  `alter_statement` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_alter_table_tokudb`
--

/*!50001 DROP VIEW IF EXISTS `sql_alter_table_tokudb`*/;
/*!50001 CREATE TABLE `sql_alter_table_tokudb` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `ENGINE` tinyint NOT NULL,
  `alter_fast_clause` tinyint NOT NULL,
  `sql_alter_fast` tinyint NOT NULL,
  `alter_small_clause` tinyint NOT NULL,
  `sql_alter_small` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_foreign_keys`
--

/*!50001 DROP VIEW IF EXISTS `sql_foreign_keys`*/;
/*!50001 CREATE TABLE `sql_foreign_keys` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `CONSTRAINT_NAME` tinyint NOT NULL,
  `drop_statement` tinyint NOT NULL,
  `create_statement` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_grants`
--

/*!50001 DROP VIEW IF EXISTS `sql_grants`*/;
/*!50001 CREATE TABLE `sql_grants` (
  `GRANTEE` tinyint NOT NULL,
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `priv_level` tinyint NOT NULL,
  `priv_level_name` tinyint NOT NULL,
  `object_schema` tinyint NOT NULL,
  `object_name` tinyint NOT NULL,
  `current_privileges` tinyint NOT NULL,
  `IS_GRANTABLE` tinyint NOT NULL,
  `sql_grant` tinyint NOT NULL,
  `sql_revoke` tinyint NOT NULL,
  `sql_drop_user` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_range_partitions`
--

/*!50001 DROP VIEW IF EXISTS `sql_range_partitions`*/;
/*!50001 CREATE TABLE `sql_range_partitions` (
  `table_schema` tinyint NOT NULL,
  `table_name` tinyint NOT NULL,
  `count_partitions` tinyint NOT NULL,
  `count_past_partitions` tinyint NOT NULL,
  `count_future_partitions` tinyint NOT NULL,
  `has_maxvalue` tinyint NOT NULL,
  `sql_drop_first_partition` tinyint NOT NULL,
  `sql_add_next_partition` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_show_grants`
--

/*!50001 DROP VIEW IF EXISTS `sql_show_grants`*/;
/*!50001 CREATE TABLE `sql_show_grants` (
  `GRANTEE` tinyint NOT NULL,
  `user` tinyint NOT NULL,
  `host` tinyint NOT NULL,
  `sql_grants` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `sql_table_keys`
--

/*!50001 DROP VIEW IF EXISTS `sql_table_keys`*/;
/*!50001 CREATE TABLE `sql_table_keys` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `INDEX_NAME` tinyint NOT NULL,
  `sql_drop_key` tinyint NOT NULL,
  `sql_add_key` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `status`
--

/*!50001 DROP VIEW IF EXISTS `status`*/;
/*!50001 CREATE TABLE `status` (
  `project_name` tinyint NOT NULL,
  `version` tinyint NOT NULL,
  `revision` tinyint NOT NULL,
  `install_time` tinyint NOT NULL,
  `install_success` tinyint NOT NULL,
  `base_components_installed` tinyint NOT NULL,
  `innodb_plugin_components_installed` tinyint NOT NULL,
  `percona_server_components_installed` tinyint NOT NULL,
  `install_mysql_version` tinyint NOT NULL,
  `install_sql_mode` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `table_charset`
--

/*!50001 DROP VIEW IF EXISTS `table_charset`*/;
/*!50001 CREATE TABLE `table_charset` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `CHARACTER_SET_NAME` tinyint NOT NULL,
  `TABLE_COLLATION` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Temporary table structure for view `text_columns`
--

/*!50001 DROP VIEW IF EXISTS `text_columns`*/;
/*!50001 CREATE TABLE `text_columns` (
  `TABLE_SCHEMA` tinyint NOT NULL,
  `TABLE_NAME` tinyint NOT NULL,
  `COLUMN_NAME` tinyint NOT NULL,
  `COLUMN_TYPE` tinyint NOT NULL,
  `CHARACTER_SET_NAME` tinyint NOT NULL,
  `COLLATION_NAME` tinyint NOT NULL
) ENGINE=MyISAM */;

--
-- Dumping routines for database 'common_schema'
--
/*!50003 DROP FUNCTION IF EXISTS `crc64` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `crc64`(data LONGTEXT CHARSET utf8) RETURNS bigint(20) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return a 64 bit CRC of given input, as unsigned big integer'
BEGIN
  RETURN CONV(LEFT(MD5(data), 16), 16, 10);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `decode_xml` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `decode_xml`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Decode escaped XML'
begin
  set txt := REPLACE(txt, '&apos;', '''');
  set txt := REPLACE(txt, '&quot;', '"');
  set txt := REPLACE(txt, '&gt;', '>');
  set txt := REPLACE(txt, '&lt;', '<');
  set txt := REPLACE(txt, '&amp;', '&');
  
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `easter_day` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `easter_day`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns date of easter day for given year'
BEGIN
    DECLARE p_year    SMALLINT DEFAULT YEAR(dt);
    DECLARE a    SMALLINT DEFAULT p_year % 19;
    DECLARE b    SMALLINT DEFAULT p_year DIV 100;
    DECLARE c    SMALLINT DEFAULT p_year % 100;
    DECLARE e    SMALLINT DEFAULT b % 4;
    DECLARE h    SMALLINT DEFAULT (19*a + b - (b DIV 4) - ((b - ((b + 8) DIV 25) + 1) DIV 3) + 15) % 30;
    DECLARE L    SMALLINT DEFAULT (32 + 2*e + 2*(c DIV 4) - h - (c % 4)) % 7;
    DECLARE v100 SMALLINT DEFAULT h + L - 7*((a + 11*h + 22*L) DIV 451) + 114;

    RETURN STR_TO_DATE(
                CONCAT(
                    p_year
                ,   '-'
                ,    v100 DIV 31
                ,   '-'
                ,   (v100 % 31) + 1
                )
            ,   '%Y-%c-%e'
            );
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `encode_xml` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `encode_xml`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Encode (escape) given text for XML'
begin
  set txt := REPLACE(txt, '&', '&amp;');
  set txt := REPLACE(txt, '<', '&lt;');
  set txt := REPLACE(txt, '>', '&gt;');
  set txt := REPLACE(txt, '"', '&quot;');
  set txt := REPLACE(txt, '''', '&apos;');
  
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `extract_json_value` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `extract_json_value`(
    json_text text charset utf8,
    xpath text charset utf8
) RETURNS text CHARSET utf8
    MODIFIES SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Extracts JSON value via XPath'
begin
  return ExtractValue(json_to_xml(json_text), xpath);	
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `get_num_tokens` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `get_num_tokens`(txt TEXT CHARSET utf8, delimiter_text VARCHAR(255) CHARSET utf8) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return number of tokens in delimited text'
begin
  if CHAR_LENGTH(txt) = 0 then
    return 0;
  end if;
  if CHAR_LENGTH(delimiter_text) = 0 then
    return CHAR_LENGTH(txt);
  else
    return (CHAR_LENGTH(txt) - CHAR_LENGTH(REPLACE(txt, delimiter_text, '')))/CHAR_LENGTH(delimiter_text) + 1;
  end if;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `get_option` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `get_option`(options TEXT CHARSET utf8, key_name VARCHAR(255) CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return value of option in JS options format'
begin
  declare options_delimiter VARCHAR(64) CHARSET ascii DEFAULT NULL;
  declare num_options INT UNSIGNED DEFAULT 0;
  declare options_counter INT UNSIGNED DEFAULT 0;
  declare current_option TEXT CHARSET utf8 DEFAULT ''; 
  declare current_option_delimiter VARCHAR(64) CHARSET ascii DEFAULT NULL;
  declare current_key TEXT CHARSET utf8 DEFAULT ''; 
  declare current_value TEXT CHARSET utf8 DEFAULT ''; 
  
  if not _is_options_format(options) then
    return null;
  end if;
  
  set key_name := unquote(key_name);

  
  set options := _retokenized_text(unwrap(trim_wspace(options)), ',', '"''`', TRUE, 'error');
  set options_delimiter := @common_schema_retokenized_delimiter;
  set num_options := @common_schema_retokenized_count;
  set options_counter := 1;
  while options_counter <= num_options do
    
    set current_option := split_token(options, options_delimiter, options_counter);
    set current_option = _retokenized_text(current_option, ':', '"''`', TRUE, 'error');

    set current_option_delimiter := @common_schema_retokenized_delimiter;
    if (@common_schema_retokenized_count != 2) then
      return NULL;
    end if;
    set current_key := split_token(current_option, current_option_delimiter, 1);
    set current_key := unquote(current_key);
    if current_key = key_name then
      set current_value := split_token(current_option, current_option_delimiter, 2);
      if current_value = 'NULL' then
        return NULL;
      end if;
      set current_value := unquote(current_value);
      return current_value;
    end if;
    set options_counter := options_counter + 1;
  end while;    
  return NULL;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `is_datetime` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `is_datetime`(txt TINYTEXT) RETURNS tinyint(3) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Checks whether given txt is a valid DATETIME.'
BEGIN
  RETURN (_as_datetime(txt) is not null);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `json_to_xml` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `json_to_xml`(
    json_text text charset utf8
) RETURNS text CHARSET utf8
    MODIFIES SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Transforms JSON to XML'
begin
    declare v_from, v_old_from int unsigned;
    declare v_token text;
    declare v_level int;
    declare v_state, expect_state varchar(255);
    declare _json_tokens_id int unsigned default 0;
    declare is_lvalue, is_rvalue tinyint unsigned;
    declare scope_stack text charset ascii;
    declare xml text charset utf8;
    declare xml_nodes, xml_node text charset utf8;
    
    set json_text := trim_wspace(json_text);
    
    set expect_state := 'object_begin';
    set is_lvalue := true;
    set is_rvalue := false;
    set scope_stack := '';
    set xml_nodes := '';
    set xml_node := '';
    set xml := '';
    get_token_loop: repeat 
        set v_old_from = v_from;
        call _get_json_token(json_text, v_from, v_level, v_token, 1, v_state);
        set _json_tokens_id := _json_tokens_id + 1;
        if v_state = 'whitespace' then
          iterate get_token_loop;
        end if;
        if v_level < 0 then
          return null;
          
        end if;
        if v_state = 'start' and scope_stack = '' then
          leave get_token_loop;
        end if;
        if FIND_IN_SET(v_state, expect_state) = 0 then
          return null;
          
        end if;
        if v_state = 'array_end' and left(scope_stack, 1) = 'o' then
          return null;
          
        end if;
        if v_state = 'object_end' and left(scope_stack, 1) = 'a' then
          return null;
          
        end if;
        if v_state = 'alpha' and lower(v_token) not in ('true', 'false', 'null') then
          return null;
          
        end if;
        set is_rvalue := false;
        case 
          when v_state = 'object_begin' then set expect_state := 'string', scope_stack := concat('o', scope_stack), is_lvalue := true;
          when v_state = 'array_begin' then set expect_state := 'string,object_begin', scope_stack := concat('a', scope_stack), is_lvalue := false;
          when v_state = 'string' and is_lvalue then set expect_state := 'colon', xml_node := v_token;
          when v_state = 'colon' then set expect_state := 'string,number,alpha,object_begin,array_begin', is_lvalue := false;
          when FIND_IN_SET(v_state, 'string,number,alpha') and not is_lvalue then set expect_state := 'comma,object_end,array_end', is_rvalue := true;
          when v_state = 'object_end' then set expect_state := 'comma,object_end,array_end', scope_stack := substring(scope_stack, 2);
          when v_state = 'array_end' then set expect_state := 'comma,object_end,array_end', scope_stack := substring(scope_stack, 2);
          when v_state = 'comma' and left(scope_stack, 1) = 'o' then set expect_state := 'string', is_lvalue := true;
          when v_state = 'comma' and left(scope_stack, 1) = 'a' then set expect_state := 'string,object_begin', is_lvalue := false;
        end case;
        set xml_node := unquote(xml_node);
        if v_state = 'object_begin' then 
          if substring_index(xml_nodes, ',', 1) != '' then
            set xml := concat(xml, '<', substring_index(xml_nodes, ',', 1), '>');
          end if;
          set xml_nodes := concat(',', xml_nodes);
        end if;
        if v_state = 'string' and is_lvalue then
          if left(xml_nodes, 1) = ',' then
            set xml_nodes := concat(xml_node, xml_nodes);
          else
            set xml_nodes := concat(xml_node, substring(xml_nodes, locate(',', xml_nodes)));
          end if;
        end if;
        if is_rvalue then
          set xml := concat(xml, '<', xml_node, '>', encode_xml(unquote(v_token)), '</', xml_node, '>');
        end if;
        if v_state = 'object_end' then 
          set xml_nodes := substring(xml_nodes, locate(',', xml_nodes) + 1);
          if substring_index(xml_nodes, ',', 1) != '' then
            set xml := concat(xml, '</', substring_index(xml_nodes, ',', 1), '>');
          end if;
        end if;
    until 
        v_old_from = v_from
    end repeat;
    return xml;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `like_to_rlike` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `like_to_rlike`(expression TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Convert a LIKE expression to an RLIKE expression'
begin
  set expression := REPLACE(expression, '.', '[.]');
  set expression := REPLACE(expression, '*', '[*]');
  set expression := REPLACE(expression, '_', '.');
  set expression := REPLACE(expression, '%', '.*');
  set expression := CONCAT('^', expression, '$');
  return expression;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `match_grantee` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `match_grantee`(connection_user char(16) CHARSET utf8, connection_host char(70) CHARSET utf8) RETURNS varchar(100) CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Match an account based on user+host'
BEGIN
  DECLARE grantee_user char(16) CHARSET utf8 DEFAULT NULL;
  DECLARE grantee_host char(60) CHARSET utf8 DEFAULT NULL;

  SELECT
    MAX(user), MAX(host)
  FROM (
    SELECT
      user, host
    FROM
      mysql.user
    WHERE
      connection_user RLIKE
        CONCAT('^',
          REPLACE(
            user,
            '%', '.*'),
          '$')
      AND SUBSTRING_INDEX(connection_host, ':', 1) RLIKE
        CONCAT('^',
          REPLACE(
          REPLACE(
            host,
            '.', '\\.'),
            '%', '.*'),
          '$')
    ORDER BY
      CHAR_LENGTH(host) - CHAR_LENGTH(REPLACE(host, '%', '')) ASC,
      CHAR_LENGTH(host) - CHAR_LENGTH(REPLACE(host, '.', '')) DESC,
      host ASC,
      CHAR_LENGTH(user) - CHAR_LENGTH(REPLACE(user, '%', '')) ASC,
      user ASC
    LIMIT 1
  ) select_matching_account
  INTO 
    grantee_user, grantee_host;
    
    
  RETURN CONCAT('''', grantee_user, '''@''', grantee_host, '''');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `mysql_grantee` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `mysql_grantee`(mysql_user char(16) CHARSET utf8, mysql_host char(60) CHARSET utf8) RETURNS varchar(100) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return a qualified MySQL grantee name'
BEGIN
  RETURN CONCAT('''', mysql_user, '''@''', mysql_host, '''');
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `mysql_qualify` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `mysql_qualify`(name TINYTEXT CHARSET utf8) RETURNS tinytext CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return a qualified MySQL name from given text'
begin
  if name RLIKE '^`[^`]*`$' then
    return name;
  end if;
  return CONCAT('`', REPLACE(name, '`', '``'), '`');
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `query_laptime` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `query_laptime`() RETURNS double
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return current query runtime'
begin
  declare time_right_now TIMESTAMP;
  declare query_time_now TIMESTAMP;
  declare time_diff DOUBLE;
  
  set time_right_now := SYSDATE();	
  set query_time_now := NOW();	
  
  
  
  
  if @_common_schema_laptime_lap_start is null then
    set @_common_schema_laptime_lap_start := query_time_now;
  else
    set @_common_schema_laptime_lap_start := GREATEST(@_common_schema_laptime_lap_start, query_time_now);
  end if;
  set time_diff := TIMESTAMPDIFF(MICROSECOND, @_common_schema_laptime_lap_start, time_right_now) / 1000000.0;
  set @_common_schema_laptime_lap_start := time_right_now;
  
  return time_diff;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `query_runtime` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `query_runtime`() RETURNS double
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return current query runtime'
BEGIN
  return TIMESTAMPDIFF(MICROSECOND, NOW(), SYSDATE()) / 1000000.0;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `random_hash` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `random_hash`() RETURNS char(40) CHARSET ascii
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Generate random hash string'
begin
	declare result CHAR(40) CHARSET ascii;
	select 
	  SHA1(
	    CONCAT_WS(',', @@server_id, SYSDATE(), RAND(), GROUP_CONCAT(VARIABLE_VALUE))
	  )
	from
	  INFORMATION_SCHEMA.GLOBAL_STATUS
	into result;
	return result;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `rdebug_get_variable` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `rdebug_get_variable`(
    rdebug_variable_name varchar(128)
  ) RETURNS blob
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  declare result blob default null;
  select 
      variable_value
    from 
      (select * from _rdebug_stack_state where worker_id = @_rdebug_recipient_id
       order by stack_level desc limit 1) select_current_stack_state
      join _rdebug_routine_variables using (routine_schema, routine_name)
      join _rdebug_routine_variables_state using (worker_id, stack_level, routine_schema, routine_name, variable_name)
    where
      statement_id between variable_scope_id_start and variable_scope_id_end
      and variable_name = rdebug_variable_name
    into result;
  return result;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `replace_all` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `replace_all`(txt TEXT CHARSET utf8, from_characters VARCHAR(1024) CHARSET utf8, to_str TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Replace any char in from_characters with to_str'
begin
  declare counter SMALLINT UNSIGNED DEFAULT 1;

  while counter <= CHAR_LENGTH(from_characters) do
    set txt := REPLACE(txt, SUBSTRING(from_characters, counter, 1), to_str);
    set counter := counter + 1;
  end while;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `replace_sections` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `replace_sections`(
  txt TEXT CHARSET utf8, 
  section_start TEXT charset utf8,
  section_end TEXT charset utf8,
  replacement_text TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Replace start-end sections with given text'
main_body: begin
  declare next_start_pos int unsigned default 1;
  declare next_end_pos int unsigned default 1;
  declare tmp_prefix, tmp_suffix, replaced_text text charset utf8;
  
  if txt is null then
    return null;
  end if;
  while true do
    set next_start_pos := LOCATE(section_start, txt, next_start_pos);
    if not next_start_pos then
      return txt;
    end if;
    set next_end_pos := LOCATE(section_end, txt, next_start_pos + char_length(section_start));
    if not next_end_pos then
      return txt;
    end if;
    set replaced_text := substring(txt, next_start_pos + char_length(section_start), (next_end_pos - next_start_pos) - char_length(section_start));
    set tmp_prefix := LEFT(txt, next_start_pos - 1);
    set tmp_suffix := SUBSTRING(txt, next_end_pos + CHAR_LENGTH(section_end));
    set txt := concat(tmp_prefix, replace(replacement_text, '\\0', replaced_text));
    set next_start_pos := char_length(txt);
    set txt := concat(txt, tmp_suffix);
  end while;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `script_runtime` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `script_runtime`() RETURNS double
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return current script runtime seconds'
BEGIN
  return TIMESTAMPDIFF(MICROSECOND, @_common_schema_script_start_timestamp, SYSDATE()) / 1000000.0;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `session_unique_id` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `session_unique_id`() RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns unique ID within this session'
BEGIN
  set @_common_schema_session_unique_id := IFNULL(@_common_schema_session_unique_id, 0) + 1;
  return @_common_schema_session_unique_id;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `shorttime_to_seconds` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `shorttime_to_seconds`(shorttime VARCHAR(16) CHARSET ascii) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return a 64 bit CRC of given input, as unsigned big integer'
begin
  declare numeric_value INT UNSIGNED DEFAULT NULL;
  
  if shorttime is NULL then
    return NULL;
  end if;
  if not shorttime rlike '^[0-9]+[smh]$' then
    return NULL;
  end if;

  set numeric_value := CAST(LEFT(shorttime, CHAR_LENGTH(shorttime) - 1) AS UNSIGNED);
  case RIGHT(shorttime, 1)
    when 's' then set numeric_value := numeric_value*1;
    when 'm' then set numeric_value := numeric_value*60;
    when 'h' then set numeric_value := numeric_value*60*60;
  end case;
  return numeric_value;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `split_token` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `split_token`(txt TEXT CHARSET utf8, delimiter_text VARCHAR(255) CHARSET utf8, token_index INT UNSIGNED) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return substring by index in delimited text'
begin
  if CHAR_LENGTH(delimiter_text) = '' then
    return SUBSTRING(txt, token_index, 1);
  else
    return SUBSTRING_INDEX(SUBSTRING_INDEX(txt, delimiter_text, token_index), delimiter_text, -1);
  end if;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `starts_with` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `starts_with`(txt TEXT CHARSET utf8, prefix TEXT CHARSET utf8) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return substring by index in delimited text'
begin
  if left(txt, CHAR_LENGTH(prefix)) = prefix then
    return CHAR_LENGTH(prefix);
  end if;
  return 0;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_hour` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_hour`(dt DATETIME) RETURNS datetime
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns DATETIME of beginning of round hour of given DATETIME.'
BEGIN
  RETURN DATE(dt) + INTERVAL HOUR(dt) HOUR;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_month` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_month`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns first day of month of given datetime, as DATE object'
BEGIN
  RETURN DATE(dt) - INTERVAL (DAYOFMONTH(dt) - 1) DAY;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_quarter` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_quarter`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns first day of quarter of given datetime, as DATE object'
BEGIN
  RETURN DATE(dt) - INTERVAL (MONTH(dt) -1) MONTH - INTERVAL (DAYOFMONTH(dt) - 1) DAY + INTERVAL (QUARTER(dt) - 1) QUARTER;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_week` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_week`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns Monday-based first day of week of given datetime'
BEGIN
  RETURN DATE(dt) - INTERVAL WEEKDAY(dt) DAY;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_week_sunday` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_week_sunday`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns Sunday-based first day of week of given datetime'
BEGIN
  RETURN DATE(dt) - INTERVAL (WEEKDAY(dt) + 1) DAY;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `start_of_year` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `start_of_year`(dt DATETIME) RETURNS date
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns first day of month of given datetime, as DATE object'
BEGIN
  RETURN DATE(dt) - INTERVAL (MONTH(dt) -1) MONTH - INTERVAL (DAYOFMONTH(dt) - 1) DAY;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `strip_urls` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `strip_urls`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Strips URLs from given text'
begin
  declare end_pos INT UNSIGNED DEFAULT 0;
  declare done TINYINT UNSIGNED DEFAULT 0;
  
  while ((@_strip_urls_url_pos := LOCATE('http://', txt)) > 0) do
    set end_pos := @_strip_urls_url_pos;
    while (SUBSTRING(txt, end_pos, 1) not in (' ', '\n', '\r', '<', '')) do
      set end_pos := end_pos + 1;
    end while;
    set txt := CONCAT(LEFT(txt, @_strip_urls_url_pos - 1), SUBSTRING(txt, end_pos));
  end while;
  while ((@_strip_urls_url_pos := LOCATE('https://', txt)) > 0) do
    set end_pos := @_strip_urls_url_pos;
    while (SUBSTRING(txt, end_pos, 1) not in (' ', '\n', '\r', '<', '')) do
      set end_pos := end_pos + 1;
    end while;
    set txt := CONCAT(LEFT(txt, @_strip_urls_url_pos - 1), SUBSTRING(txt, end_pos));
  end while;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `table_exists` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `table_exists`(
  lookup_table_schema varchar(64) charset utf8, 
  lookup_table_name varchar(64) charset utf8) RETURNS tinyint(3) unsigned
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Check if specified table exists'
BEGIN
  return (select count(*) from INFORMATION_SCHEMA.TABLES 
    where TABLE_SCHEMA = lookup_table_schema AND TABLE_NAME = lookup_table_name);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `this_query` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `this_query`() RETURNS longtext CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return current query'
BEGIN
  return (SELECT INFO FROM INFORMATION_SCHEMA.PROCESSLIST WHERE ID = CONNECTION_ID());
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `throttle` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `throttle`(throttle_ratio DOUBLE) RETURNS double
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  set @_common_schema_throttle_counter := IFNULL(@_common_schema_throttle_counter, 0) + 1;
  
  if @_common_schema_throttle_counter % 1000 = 0 then
    set @_common_schema_throttle_counter := 0;
    set @_common_schema_throttle_sysdate := SYSDATE();
    
    
    
    
    set @_common_schema_throttle_chunk_start := IFNULL(@_common_schema_throttle_chunk_start, NOW());
    set @_common_schema_throttle_chunk_start := GREATEST(@_common_schema_throttle_chunk_start, NOW());
    set @_common_schema_throttle_timediff := TIMESTAMPDIFF(SECOND, @_common_schema_throttle_chunk_start, @_common_schema_throttle_sysdate);
    set @_common_schema_throttle_sleep_time := @_common_schema_throttle_timediff * throttle_ratio;
    
    if @_common_schema_throttle_sleep_time > 0 then
      DO SLEEP(@_common_schema_throttle_sleep_time);
      set @_common_schema_throttle_chunk_start := SYSDATE();
      return @_common_schema_throttle_sleep_time;
    end if;
  end if;
  
  return 0;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `trim_wspace` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `trim_wspace`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Trim whitespace characters on both sides'
begin
  declare len INT UNSIGNED DEFAULT 0;
  declare done TINYINT UNSIGNED DEFAULT 0;
  if txt IS NULL then
    return txt;
  end if;
  while not done do
    set len := CHAR_LENGTH(txt);
    set txt = trim(' ' FROM txt);
    set txt = trim('\r' FROM txt);
    set txt = trim('\n' FROM txt);
    set txt = trim('\t' FROM txt);
    set txt = trim('\b' FROM txt);
    if CHAR_LENGTH(txt) = len then
      set done := 1;
    end if;
  end while;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `unquote` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `unquote`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Unquotes a given text'
begin
  declare quoting_char VARCHAR(1) CHARSET utf8;
  declare terminating_quote_escape_char VARCHAR(1) CHARSET utf8;
  declare current_pos INT UNSIGNED;
  declare end_quote_pos INT UNSIGNED;

  if CHAR_LENGTH(txt) < 2 then
    return txt;
  end if;
  
  set quoting_char := LEFT(txt, 1);
  if not quoting_char in ('''', '"', '`', '/') then
    return txt;
  end if;
  if txt in ('''''', '""', '``', '//') then
    return '';
  end if;
  
  set current_pos := 1;
  terminating_quote_loop: while current_pos > 0 do
    set current_pos := LOCATE(quoting_char, txt, current_pos + 1);
    if current_pos = 0 then
      
      return txt;
    end if;
    if SUBSTRING(txt, current_pos, 2) = REPEAT(quoting_char, 2) then
      set current_pos := current_pos + 1;
      iterate terminating_quote_loop;
    end if;
    set terminating_quote_escape_char := SUBSTRING(txt, current_pos - 1, 1);
    if (terminating_quote_escape_char = quoting_char) or (terminating_quote_escape_char = '\\') then
      
      
      iterate terminating_quote_loop;
    end if;
    
    leave terminating_quote_loop;
  end while;
  if current_pos = CHAR_LENGTH(txt) then
      return SUBSTRING(txt, 2, CHAR_LENGTH(txt) - 2);
    end if;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `unwrap` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `unwrap`(txt TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Unwraps a given text from braces'
begin
  if CHAR_LENGTH(txt) < 2 then
    return txt;
  end if;
  if LEFT(txt, 1) = '{' AND RIGHT(txt, 1) = '}' then
    return SUBSTRING(txt, 2, CHAR_LENGTH(txt) - 2);
  end if;
  if LEFT(txt, 1) = '[' AND RIGHT(txt, 1) = ']' then
    return SUBSTRING(txt, 2, CHAR_LENGTH(txt) - 2);
  end if;
  if LEFT(txt, 1) = '(' AND RIGHT(txt, 1) = ')' then
    return SUBSTRING(txt, 2, CHAR_LENGTH(txt) - 2);
  end if;
  return txt;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_as_datetime` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_as_datetime`(txt TINYTEXT) RETURNS datetime
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Convert given text to DATETIME or NULL.'
BEGIN
  declare continue handler for SQLEXCEPTION return NULL; 
  RETURN (txt + interval 0 second);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_create_mxarray` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_create_mxarray`() RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Creates an array, returning its ID'
main_body: begin
  if @_common_schema_mx_array IS NULL then
    set @_common_schema_mx_array := '<ma></ma>';
  end if;
  
  set @_common_schema_create_mxarray_id := session_unique_id();
  set @_common_schema_mx_array := REPLACE(@_common_schema_mx_array, '</ma>', CONCAT('<a id="', @_common_schema_create_mxarray_id, '"><maxkey aid="', @_common_schema_create_mxarray_id, '">0</maxkey></a></ma>'));
  return @_common_schema_create_mxarray_id;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_drop_mxarray` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_drop_mxarray`(
   array_id int unsigned
) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Drops an array'
main_body: begin
  declare xpath varchar(64) charset utf8;
  if array_id is null then
    return null;
  end if;
  set xpath := CONCAT('/ma/a[@id="', array_id, '"]');
  set @_common_schema_mx_array := UpdateXML(@_common_schema_mx_array, xpath, '');
  return array_id;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_extract_expanded_query_script_variable_name` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_extract_expanded_query_script_variable_name`(
	expanded_query_script_variable TEXT CHARSET ascii) RETURNS text CHARSET ascii
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Get name of qs variable from expanded format'
begin
  
  if expanded_query_script_variable LIKE ':${%}' then
    return CONCAT('$', SUBSTRING(expanded_query_script_variable, 4, CHAR_LENGTH(expanded_query_script_variable) - 4));
  end if;
  
  if expanded_query_script_variable LIKE ':$%' then
    return SUBSTRING(expanded_query_script_variable, 2);
  end if;
  return NULL;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_get_mxarray_element` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_get_mxarray_element`(
   array_id int unsigned,
   array_key varchar(127) charset utf8
) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Get an element by array id and key'
main_body: begin
  declare xpath varchar(64) charset utf8;
  if _mxarray_key_exists(array_id, array_key) then
    set xpath := CONCAT('/ma/a[@id="', array_id, '"]/e[@key="', encode_xml(array_key), '"][1]');
    return decode_xml(ExtractValue(@_common_schema_mx_array, xpath));
  end if;
  return null;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_get_mxarray_max_key` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_get_mxarray_max_key`(
   array_id int unsigned
) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT '(internal) get array''s current max key'
main_body: begin
  return CAST(ExtractValue(@_common_schema_mx_array, CONCAT('/ma/a[@id="', array_id, '"]/maxkey')) AS UNSIGNED);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_get_mxarray_size` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_get_mxarray_size`(
   array_id int unsigned
) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return number of elements in indicated array'
main_body: begin
  return CAST(IFNULL(ExtractValue(@_common_schema_mx_array, CONCAT('count(/ma/a[@id="', array_id, '"]/e)')), 0) AS UNSIGNED);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_get_server_id` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_get_server_id`() RETURNS int(10) unsigned
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Return current server id'
BEGIN
  RETURN @@global.server_id;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_is_options_format` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_is_options_format`(options TEXT CHARSET utf8) RETURNS tinyint(3) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return value of option in JS options format'
begin
  if options is null then
    return false;
  end if;
  return (trim_wspace(options) RLIKE '^{.*}$') is true;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_is_select_query` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_is_select_query`(input LONGTEXT CHARSET utf8) RETURNS tinyint(3) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Returns 1 when given input starts with SELECT'
BEGIN
  RETURN (LOCATE('select', LOWER(trim_wspace(input))) = 1);
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_mxarray_key_exists` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_mxarray_key_exists`(
   array_id int unsigned,
   array_key varchar(127) charset utf8
) RETURNS tinyint(3) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Check whether key exists within array'
main_body: begin
  declare xpath varchar(64) charset utf8;
  set xpath := CONCAT('count(/ma/a[@id="', array_id, '"]/e[@key="', encode_xml(array_key), '"][1])');
  return (IFNULL(ExtractValue(@_common_schema_mx_array, xpath), 0) > 0);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_push_mxarray_element` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_push_mxarray_element`(
   array_id int unsigned,
   element text charset utf8
) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Pushes new element into array'
main_body: begin
  declare array_max_key int unsigned;
  
  if array_id is null then
    return null;
  end if;
  
  set array_max_key := _get_mxarray_max_key(array_id);
  set @_common_schema_mx_array := REPLACE(@_common_schema_mx_array, CONCAT('<maxkey aid="', array_id, '">'), CONCAT('<e key="', (array_max_key+1), '">', encode_xml(element), '</e><maxkey aid="', array_id, '">'));
  do _update_mxarray_max_key(array_id, (array_max_key+1));
  return (array_max_key+1);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_debug_code_breakpoint_hint` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_debug_code_breakpoint_hint`() RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  return '/*[B]*/';
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_debug_code_breakpoint_hint_end` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_debug_code_breakpoint_hint_end`() RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  return ':]*/';
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_debug_code_breakpoint_hint_start` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_debug_code_breakpoint_hint_start`() RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  return '/*[B:';
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_debug_code_end` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_debug_code_end`() RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  return '/* [/_common_schema_debug_] */';
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_debug_code_start` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_debug_code_start`() RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
begin
  
  
  
  return CONCAT('/* [_common_schema_debug_', '] */');
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_lock_name` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_lock_name`(
  connection_id int unsigned,
  name_hint varchar(32)
  ) RETURNS varchar(64) CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Return value of option in JS options format'
begin
  return CONCAT_WS('_', '__common_schema_rdebug_lock', connection_id, name_hint);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_rdebug_get_next_stack_level` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_rdebug_get_next_stack_level`() RETURNS int(10) unsigned
    READS SQL DATA
    DETERMINISTIC
    COMMENT 'Return next in order stack level'
begin
  declare next_stack_level int unsigned default null;
  
  select 
      max(stack_level) 
    from 
      _rdebug_stack_state
    where
      worker_id = CONNECTION_ID()
    into next_stack_level;
  
  if next_stack_level is null
    then return 1;
  end if;
  return IFNULL(@_rdebug_stack_level_ + 1, 1);
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_requalify_grantee_term` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_requalify_grantee_term`(grantee_term TINYTEXT CHARSET utf8) RETURNS tinytext CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Requalify grantee input'
BEGIN
  declare tokens_delimiter VARCHAR(64) CHARSET ascii DEFAULT NULL;
  declare num_tokens INT UNSIGNED DEFAULT 0;

  set grantee_term := _retokenized_text(grantee_term, '@', '''', TRUE, 'error');
  set tokens_delimiter := @common_schema_retokenized_delimiter;
  set num_tokens := @common_schema_retokenized_count;
  
  if num_tokens = 1 then
    return unquote(grantee_term);
  end if;
  if num_tokens = 2 then
    return mysql_grantee(unquote(SUBSTRING_INDEX(grantee_term, tokens_delimiter, 1)), unquote(SUBSTRING_INDEX(grantee_term, tokens_delimiter, -1)));
  end if;
  return null;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_retokenized_queries` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_retokenized_queries`(queries TEXT CHARSET utf8) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Retokenizes input queries with special token'
begin
  declare quoting_characters VARCHAR(5) CHARSET ascii DEFAULT '`''';

  if not find_in_set('ANSI_QUOTES', @@sql_mode) then
    set quoting_characters := CONCAT(quoting_characters, '"');
  end if;

  return _retokenized_text(queries, ';', quoting_characters, TRUE, 'skip');
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_retokenized_text` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_retokenized_text`(
  input_text TEXT CHARSET utf8, 
  delimiters VARCHAR(16) CHARSET utf8, 
  quoting_characters VARCHAR(16) CHARSET utf8,
  trim_tokens BOOL,
  empty_tokens_behavior enum('allow', 'skip', 'error')
) RETURNS text CHARSET utf8
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Retokenizes input_text with special token'
begin
  declare current_pos INT UNSIGNED DEFAULT 1;
  declare token_start_pos INT UNSIGNED DEFAULT 1;
  declare terminating_quote_found BOOL DEFAULT FALSE;
  declare terminating_quote_pos INT UNSIGNED DEFAULT 0;
  declare terminating_quote_escape_char CHAR(1) CHARSET utf8;
  declare current_char VARCHAR(1) CHARSET utf8;
  declare quoting_char VARCHAR(1) CHARSET utf8;
  declare current_token TEXT CHARSET utf8 DEFAULT '';
  declare result_text TEXT CHARSET utf8 DEFAULT '';
  declare delimiter_template VARCHAR(64) CHARSET ascii DEFAULT '\0[\n}\b+-\t|%&{])/\r~:;&"%`@>?=<_common_schema_unlikely_token_';
  declare internal_delimiter_length TINYINT UNSIGNED DEFAULT 0;
  declare internal_delimiter VARCHAR(64) CHARSET utf8 DEFAULT '';
  
  
  set @common_schema_retokenized_delimiter := NULL;
  set @common_schema_retokenized_count := NULL;

  
  
  
  _evaluate_internal_delimiter_loop: while internal_delimiter_length < CHAR_LENGTH(delimiter_template) do
  	set internal_delimiter_length := internal_delimiter_length + 1;
  	set internal_delimiter := LEFT(delimiter_template, internal_delimiter_length);
  	if LOCATE(internal_delimiter, input_text) = 0 then
  	  leave _evaluate_internal_delimiter_loop;
  	end if;
  end while;

  while current_pos <= CHAR_LENGTH(input_text) + 1 do
    if current_pos = CHAR_LENGTH(input_text) + 1 then
      
      
      set current_char := LEFT(delimiters, 1);
    else
      set current_char := SUBSTRING(input_text, current_pos, 1);
    end if;
    if LOCATE(current_char, quoting_characters) > 0 then
      
      set quoting_char := current_char;
      set terminating_quote_found := false;
      while not terminating_quote_found do
        set terminating_quote_pos := LOCATE(quoting_char, input_text, current_pos + 1);
        if terminating_quote_pos = 0 then
          
          return NULL;
        end if;
        if terminating_quote_pos = current_pos + 1 then
          
          set terminating_quote_found := true;
        else
          
          
          set terminating_quote_escape_char := SUBSTRING(input_text, terminating_quote_pos - 1, 1);
          if (terminating_quote_escape_char = quoting_char) or (terminating_quote_escape_char = '\\') then
            
            
            set terminating_quote_found := false;        
          else
            set terminating_quote_found := true;            
          end if;
        end if;
        set current_pos := terminating_quote_pos;
      end while;
    elseif LOCATE(current_char, delimiters) > 0 then
      
      set current_token := SUBSTRING(input_text, token_start_pos, current_pos - token_start_pos);
      if trim_tokens then
        set current_token := trim_wspace(current_token);
      end if;
      
      if ((CHAR_LENGTH(current_token) = 0) and (empty_tokens_behavior = 'error')) then
        
        return NULL;
      end if;
      if ((CHAR_LENGTH(current_token) > 0) or (empty_tokens_behavior = 'allow')) then
        
        if CHAR_LENGTH(result_text) > 0 then
          set result_text := CONCAT(result_text, internal_delimiter);
        end if;
        
        set result_text := CONCAT(result_text, current_token);
        set @common_schema_retokenized_count := 1 + IFNULL(@common_schema_retokenized_count, 0);
      end if;
      set token_start_pos := current_pos + 1;
    end if;
    set current_pos := current_pos + 1;
  end while;
  
  
  
  
  set @common_schema_retokenized_delimiter := internal_delimiter;
  return result_text;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_columns_comparison_clause` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_columns_comparison_clause`(
    comparison_operator VARCHAR(3), 
    split_variable_type enum('range_start', 'range_end', 'max'), 
    comparison_includes_equals TINYINT UNSIGNED,
    num_split_columns TINYINT UNSIGNED) RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select
    group_concat('(', partial_comparison, ')' order by n separator ' OR ') as comparison
  from (
    select 
      n,
      group_concat('(', column_name, ' ', if(is_last, comparison_operator, '='), ' ', variable_name, ')' order by column_order separator ' AND ') as partial_comparison
    from (
      select 
        n, CONCAT(mysql_qualify(split_table_name), '.', mysql_qualify(column_name)) AS column_name,
        case split_variable_type
          when 'range_start' then range_start_variable_name
          when 'range_end' then range_end_variable_name
          when 'max' then max_variable_name
        end as variable_name,
        _split_column_names_table.column_order, _split_column_names_table.column_order = n as is_last 
      from 
        numbers, _split_column_names_table 
      where 
        n between _split_column_names_table.column_order and num_split_columns 
      order by n, _split_column_names_table.column_order
    ) s1
    group by n
  ) s2
  into return_value
  ;
  
  if comparison_includes_equals then
    select
      CONCAT(
        return_value, ' OR (',
        GROUP_CONCAT(
          '(', CONCAT(mysql_qualify(split_table_name), '.', mysql_qualify(column_name)), ' = ', 
          case split_variable_type
            when 'range_start' then range_start_variable_name
            when 'range_end' then range_end_variable_name
            when 'max' then max_variable_name
          end,
          ')' order by column_order separator ' AND '),
        ')'
      )
    from
      _split_column_names_table
    into return_value
    ;
  end if;
  set return_value := CONCAT('(', return_value, ')');

  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_columns_count` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_columns_count`() RETURNS tinyint(3) unsigned
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TINYINT UNSIGNED;
  
  select 
      count(*)
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_columns_names` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_columns_names`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(column_name order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_columns_order_ascending_clause` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_columns_order_ascending_clause`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(column_name, ' ASC' order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_columns_order_descending_clause` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_columns_order_descending_clause`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(column_name, ' DESC' order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_max_variables_names` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_max_variables_names`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(max_variable_name order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_min_variables_names` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_min_variables_names`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(min_variable_name order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_range_end_variables_names` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_range_end_variables_names`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(range_end_variable_name order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_get_range_start_variables_names` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_get_range_start_variables_names`() RETURNS text CHARSET utf8
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN	
  declare return_value TEXT CHARSET utf8;
  
  select 
      group_concat(range_start_variable_name order by column_order separator ', ')
    from
      _split_column_names_table
    into return_value
    ;
  return return_value;
END ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_split_is_first_step` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_split_is_first_step`() RETURNS tinyint(3) unsigned
    NO SQL
    SQL SECURITY INVOKER
begin
  return @_split_is_first_step_flag;
end ;;
DELIMITER ;
/*!50003 DROP FUNCTION IF EXISTS `_update_mxarray_max_key` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` FUNCTION `_update_mxarray_max_key`(
   array_id int unsigned,
   array_max_key int unsigned
) RETURNS int(10) unsigned
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT '(internal) updated max-key indicator'
main_body: begin
  set @_common_schema_mx_array := UpdateXML(@_common_schema_mx_array, CONCAT('/ma/a[@id="', array_id, '"]/maxkey'), CONCAT('<maxkey aid="', array_id, '">', array_max_key, '</maxkey>'));
  return array_id;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `$` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `$`(collection TEXT CHARSET utf8, execute_queries TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Invoke queries per element of given collection'
begin
  call foreach(collection, execute_queries);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `duplicate_grantee` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `duplicate_grantee`(
    IN existing_grantee TINYTEXT CHARSET utf8,
    IN new_grantee TINYTEXT CHARSET utf8
  )
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Duplicate grantee''s privileges into new account'
begin
  declare sql_grants_statement TEXT charset utf8 default null;
    
  SELECT 
    MIN(REPLACE(sql_grants, _requalify_grantee_term(existing_grantee), _requalify_grantee_term(new_grantee)))
  FROM 
    sql_show_grants 
  WHERE 
    grantee = _requalify_grantee_term(existing_grantee)
  INTO
    sql_grants_statement;
  
  if sql_grants_statement is null then
    call throw(CONCAT('duplicate_grantee(): unknown grantee ', existing_grantee));
  end if;
  
  call exec(sql_grants_statement);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `eval` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `eval`(sql_query TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Evaluates queries resulting from given query'
begin
  DROP TEMPORARY TABLE IF EXISTS _tmp_eval_queries;
  CREATE TEMPORARY TABLE _tmp_eval_queries (query TEXT CHARSET utf8);
  set @q := CONCAT('INSERT INTO _tmp_eval_queries ', sql_query);  
  call exec_single(@q);
  
  begin	
    declare current_query TEXT CHARSET utf8 DEFAULT NULL;
    declare done INT DEFAULT 0;
    declare eval_cursor cursor for SELECT query FROM _tmp_eval_queries;
    declare continue handler for NOT FOUND SET done = 1;
    
    open eval_cursor;
    read_loop: loop
      fetch eval_cursor into current_query;
      if done then
        leave read_loop;
      end if;
      set @execute_query := current_query;
      call exec(@execute_query);
    end loop;

    close eval_cursor;
  end;
  
  DROP TEMPORARY TABLE IF EXISTS _tmp_eval_queries;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `exec` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `exec`(IN execute_queries TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
begin
  declare num_query_tokens, queries_loop_counter INT UNSIGNED DEFAULT 0;
  declare single_query TEXT CHARSET utf8; 
  
  
  set execute_queries := _retokenized_queries(execute_queries);
  set num_query_tokens := @common_schema_retokenized_count;
  set queries_loop_counter := 0;
  while queries_loop_counter < num_query_tokens do
    set single_query := split_token(execute_queries, @common_schema_retokenized_delimiter, queries_loop_counter + 1);
    call exec_single(single_query);
    set queries_loop_counter := queries_loop_counter + 1;
  end while;    
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `exec_file` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `exec_file`(IN file_name TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Executes queries from given file'
begin
  call exec(LOAD_FILE(file_name));	
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `exec_single` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `exec_single`(IN execute_query TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
_proc_body: begin
  set @_execute_query := trim_wspace(execute_query);
  if CHAR_LENGTH(@_execute_query) = 0 then
    
    
    leave _proc_body;
  end if;

  set @common_schema_rowcount := NULL;
  
  if @common_schema_dryrun IS TRUE then
    SELECT @_execute_query AS 'exec_single: @common_schema_dryrun';
  else
    if @common_schema_verbose IS TRUE then
	  SELECT @_execute_query AS 'exec_single: @common_schema_verbose';
    end if;
  
    PREPARE st FROM @_execute_query;
    EXECUTE st;
    set @common_schema_rowcount := ROW_COUNT(), @common_schema_found_rows := FOUND_ROWS();
    DEALLOCATE PREPARE st;    
  end if;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `foreach` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `foreach`(collection TEXT CHARSET utf8, execute_queries TEXT CHARSET utf8)
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Invoke queries per element of given collection'
main_body: begin  
  if collection IS NULL then
    leave main_body;
  end if;
  if execute_queries IS NULL then
    leave main_body;
  end if;
  
  call _foreach(collection, execute_queries, NULL, NULL, NULL, @_common_schema_dummy, NULL, NULL, NULL, @_common_schema_dummy);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `get_event_dependencies` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `get_event_dependencies`(
    IN p_event_schema VARCHAR(64) CHARSET utf8 
,   IN p_event_name VARCHAR(64) CHARSET utf8
)
    READS SQL DATA
    DETERMINISTIC
begin
    declare v_event_definition longtext charset utf8;
    declare exit handler for not found
        select concat('Event `', p_event_schema, '`.`', p_event_name, '` not found.') error
    ; 
    
    select  body
    into    v_event_definition
    from    mysql.event
    where   db      = p_event_schema
    and     name    = p_event_name;

    call get_sql_dependencies(v_event_definition, p_event_schema);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `get_routine_dependencies` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `get_routine_dependencies`(
    IN p_routine_schema VARCHAR(64) CHARSET utf8 
,   IN p_routine_name VARCHAR(64) CHARSET utf8
)
    READS SQL DATA
    DETERMINISTIC
begin
    declare v_routine_definition longtext charset utf8;
    declare exit handler for not found
        select concat('Routine `', p_routine_schema, '`.`', p_routine_name, '` not found.') error
    ; 
    
    select  body
    into    v_routine_definition
    from    mysql.proc
    where   db      = p_routine_schema
    and     name    = p_routine_name;

    call get_sql_dependencies(v_routine_definition, p_routine_schema);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `get_sql_dependencies` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `get_sql_dependencies`(
    IN p_sql               TEXT charset utf8
,   IN p_default_schema    VARCHAR(64) charset utf8
)
    DETERMINISTIC
my_main: begin
	call _get_sql_dependencies_internal(p_sql, p_default_schema, 1, @_common_schema_result_success);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `get_view_dependencies` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `get_view_dependencies`(
    IN p_table_schema VARCHAR(64) CHARSET utf8
,   IN p_table_name VARCHAR(64) CHARSET utf8
)
    READS SQL DATA
    DETERMINISTIC
begin
    declare v_view_definition longtext charset utf8;
    declare exit handler for not found
        select concat('View `', p_table_schema, '`.`', p_table_name, '` not found.') error
    ; 
    
    select  view_definition
    into    v_view_definition
    from    information_schema.views
    where   table_schema = p_table_schema
    and     table_name = p_table_name;

    call get_sql_dependencies(v_view_definition, p_table_schema);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `google_line_chart` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `google_line_chart`(
	IN values_query TEXT, 
	IN chart_legend TEXT
  )
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'ascii line chart'
begin
  set @_line_chart_values_query := values_query;
  call _wrap_select_list_columns(@_line_chart_values_query, 9, @common_schema_error);
  set @multi_line_chart_num_values := @_wrap_select_num_original_columns - 1;
	
  set @multi_line_chart_values_legend := ifnull(chart_legend, '');
  set @multi_line_chart_values_legend := replace(@multi_line_chart_values_legend, ',', '|');
  set @multi_line_chart_values_legend := replace(@multi_line_chart_values_legend, '| ', '|');
  set @multi_line_chart_values_legend := replace(@multi_line_chart_values_legend, ' |', '|');
  set @multi_line_chart_min_value := NULL;
  set @multi_line_chart_max_value := NULL;
  set @multi_line_chart_count_values := 0;
  set @multi_line_chart_colors := SUBSTRING_INDEX('ff8c00,4682b4,9acd32,dc143c,9932cc,ffd700,191970,7fffd4,808080,dda0dd', ',', @multi_line_chart_num_values);
  set @_line_chart_query := "
	SELECT
	  CONCAT(
	    'http://chart.apis.google.com/chart?cht=lc&chs=800x350&chtt=SQL+chart+by+common_schema&chxt=x,y&chxr=1,',
	    ROUND(MIN(min_value), 1), ',',
	    ROUND(MAX(max_value), 1),
	    '&chd=s:',
	    TRIM(LEADING ',' FROM GROUP_CONCAT(
		  IF(count_values = 1, ',', ''),
          IF(
	        row_value IS NULL,
	        '_',
	        SUBSTRING(
	          'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
	          1+round(61*(row_value - min_value)/(max_value - min_value)),
	          1
            )
	      )
          ORDER BY n,count_values
	      SEPARATOR ''
	    )),
	   '&chxs=0,505050,10,0,lt',
	   '&chxl=0:|',
	    GROUP_CONCAT(
	      IF(
	        n = 1,
	        IF(
              count_values IN (1, ROUND(@multi_line_chart_count_values/4), ROUND(@multi_line_chart_count_values/2), ROUND (@multi_line_chart_count_values*3/4), @multi_line_chart_count_values),
	          ordering_column,
	          ''
	        ),
	        NULL
	      )
          ORDER BY ordering_column
	      SEPARATOR '|'
	    ),
	   '&chg=', (100.0/(@multi_line_chart_count_values-1)), ',25,1,2,0,0',
       '&chco=${multi_line_chart_colors}',
	   '&chdl=${multi_line_chart_values_legend}',
       '&chdlp=b'
	  ) as google_chart_url
      FROM 
        (
        SELECT 
            n,
            ordering_column,
            row_value,
            count_values,
            @multi_line_chart_min_value AS min_value,
            @multi_line_chart_max_value AS max_value
        FROM
          (SELECT
            *,
            @multi_line_chart_min_value := LEAST(IFNULL(cast(@multi_line_chart_min_value as decimal(64,20)), row_value), IFNULL(row_value, cast(@multi_line_chart_min_value as decimal(64,20)))) AS min_value,
            @multi_line_chart_max_value := GREATEST(IFNULL(cast(@multi_line_chart_max_value as decimal(64,20)), row_value), IFNULL(row_value, cast(@multi_line_chart_max_value as decimal(64,20)))) AS max_value,
            if (n = 1, @multi_line_chart_count_values := @multi_line_chart_count_values + 1, @multi_line_chart_count_values) as count_values
          FROM
            (SELECT
              *,
              col1 as ordering_column,
              cast(
                case n
                  when 1 then col2   
                  when 2 then col3   
                  when 3 then col4   
                  when 4 then col5   
                  when 5 then col6   
                  when 6 then col7   
                  when 7 then col8   
                  when 8 then col9   
                end 
                as DECIMAL(64,20)
              ) AS row_value
            FROM
              numbers,
              (${wrapped_query}) AS sel_main_values
            WHERE
              numbers.n BETWEEN 1 AND @multi_line_chart_num_values
            ) sel_counted_values_main_values
          ) selec_data
		) select_data_min_max
  ";
  set @_line_chart_query := replace(@_line_chart_query, '${wrapped_query}', @_line_chart_values_query);
  set @_line_chart_query := replace(@_line_chart_query, '${multi_line_chart_colors}', @multi_line_chart_colors);
  set @_line_chart_query := replace(@_line_chart_query, '${multi_line_chart_values_legend}', @multi_line_chart_values_legend);
  
  call exec_single(@_line_chart_query);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `grant_access` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `grant_access`()
    MODIFIES SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Grant SELECT & EXECUTE to all on common_schema'
begin
  declare grant_query TEXT charset utf8 default null;
  
  set grant_query := '
    select 
      concat(''GRANT SELECT, EXECUTE ON '', 
        mysql_qualify(DATABASE()), ''.* TO '', GRANTEE) AS grant_query
      from
        sql_show_grants'
  ;
  
  call eval(grant_query);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `help` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `help`(expression TINYTEXT CHARSET utf8)
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Inline help'
begin
  set expression := REPLACE(expression, '()', '');
  set expression := REPLACE(expression, ';', '');
  set expression := trim_wspace(expression);
  set expression := REPLACE(expression, ' ', '%');
  SELECT 
    split_token(help_message, '\n', n) AS help
  FROM (
    SELECT help_message FROM (
      SELECT 1 AS order_column, help_message FROM help_content WHERE topic LIKE CONCAT('%', expression, '%')
      UNION ALL
      SELECT 2, help_message FROM help_content WHERE LEFT(help_message, 256) LIKE CONCAT('%', expression, '%')
      UNION ALL
      SELECT 3, help_message FROM help_content WHERE help_message LIKE CONCAT('%', expression, '%')
      UNION ALL
      SELECT 4, CONCAT('No help topics found for "', expression, '".')
    ) select_all 
    ORDER BY order_column ASC 
    LIMIT 1
  ) select_single,
  numbers
  WHERE 
    numbers.n BETWEEN 1 AND get_num_tokens(help_message, '\n')
  ORDER BY n ASC;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `hexcode_text` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `hexcode_text`(
  in txt TEXT CHARSET utf8)
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
    COMMENT 'Shows hex-table of given text'
main_body: begin
  declare title varchar(255) charset ascii default '';
  declare hex_text text charset utf8 default '';
  declare lpad_size tinyint unsigned default 2;
  declare current_chunk int unsigned default 1;
  declare count_chunks int unsigned default 0;
  declare current_index tinyint unsigned;
  
  if char_length(HEX(txt)) > 2*char_length(txt) then
    
    
    set lpad_size := 4;
  end if;
  
  set count_chunks := ceil(char_length(txt)/16.0);
  while current_chunk <= count_chunks do
    set current_index := 1;
    while current_index <= 16 do
      set hex_text := concat(
          hex_text,
          lpad(
            hex(substring(txt, (current_chunk - 1)*16 + current_index, 1)), 
            if (current_index = 1, lpad_size, lpad_size + 1), 
            ' '
          )
        );
      if current_chunk = 1 then
        set title := concat(
          title, 
          lpad(
            lower(hex(current_index - 1)), 
            if (current_index = 1, lpad_size, lpad_size + 1), 
            ' '
          )
        );
      end if;
      set current_index := current_index + 1;
    end while;
    
    set hex_text := concat(hex_text, '  ');
    if current_chunk = 1 then
      set title := concat(title, '  ');
    end if;
    
    set current_index := 1;
    while current_index <= 16 do
      set hex_text := concat(
          hex_text,
          lpad(substring(txt, (current_chunk - 1)*16 + current_index, 1), 2, ' ')
        );
      if current_chunk = 1 then
        set title := concat(
          title, 
          lpad(
            lower(hex(current_index - 1)), 
            2,
            ' '
          )
        );
      end if;
      set current_index := current_index + 1;
    end while;
    set hex_text := concat(hex_text, '\n');
    set current_chunk := current_chunk + 1;
  end while;

  set hex_text := trim('\n' from hex_text);
  set title := concat('>', substring(title, 2));
  call prettify_message(title, hex_text);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `killall` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `killall`(IN grantee_term TINYTEXT CHARSET utf8)
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Kills connections based on grantee term'
begin
  set grantee_term := _requalify_grantee_term(grantee_term);
  
  begin
    declare kill_process_id bigint unsigned default null;
    declare done tinyint default 0;
    declare killall_cursor cursor for 
      select 
        id 
      from 
        _processlist_grantees_exploded 
      where 
        grantee_term in (grantee, unqualified_grantee, grantee_host, grantee_user, qualified_user_host, unqualified_user_host, hostname, user)
        and id != CONNECTION_ID()
      ;
    declare continue handler for NOT FOUND set done = 1;
    declare continue handler for 1094 begin end; 
  
    
    
    
    
    open killall_cursor;
    read_loop: loop
      fetch killall_cursor into kill_process_id;
      if done then
        leave read_loop;
      end if;
      kill kill_process_id;
    end loop;

    close killall_cursor;
  end;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `kill_everything` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `kill_everything`()
BEGIN
	CALL eval("SELECT sql_kill_query FROM processlist_grantees WHERE COMMAND != 'Sleep' AND is_super = 0 AND is_repl = 0");
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `kill_slow` */;
DELIMITER ;;
CREATE DEFINER=`sander`@`%` PROCEDURE `kill_slow`()
BEGIN
	CALL eval("SELECT sql_kill_query FROM processlist_grantees WHERE COMMAND != 'Sleep' AND TIME > 20 AND is_super = 0 AND is_repl = 0");
    END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `line_chart` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `line_chart`(
	IN values_query TEXT, 
	IN chart_legend TEXT
  )
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'ascii line chart'
begin
  set @_line_chart_values_query := values_query;
  call _wrap_select_list_columns(@_line_chart_values_query, 9, @common_schema_error);
  set @multi_line_chart_num_values := @_wrap_select_num_original_columns - 1;
	
  set @multi_line_chart_bar_length := NULL;
  set @multi_line_chart_values_legend := ifnull(chart_legend, '');
  set @multi_line_chart_min_value := NULL;
  set @multi_line_chart_max_value := NULL;
  set @multi_line_chart_graph_rows := 17;
  set @_line_chart_query := "
	SELECT
	  cast(y_scale as decimal(64,${multi_line_chart_value_precision})) as y_scale,
	  horizontal_bar as common_schema_chart
	  FROM
	  (
	  SELECT
	    @multi_line_chart_row_number := @multi_line_chart_row_number+1,
	    CASE @multi_line_chart_row_number
	      WHEN 1                            THEN @multi_line_chart_max_value
	      WHEN @multi_line_chart_graph_rows THEN @multi_line_chart_min_value
	      ELSE                              @multi_line_chart_max_value-(@multi_line_chart_max_value-@multi_line_chart_min_value)*(@multi_line_chart_row_number-1)/(@multi_line_chart_graph_rows-1)
	    END AS y_scale,
	    horizontal_bar,
	    @multi_line_chart_bar_length := IFNULL(@multi_line_chart_bar_length, CHAR_LENGTH(horizontal_bar))
	  FROM
	    (SELECT @multi_line_chart_row_number := 0) AS select_row
	    INNER JOIN
	    (
	    SELECT
	      GROUP_CONCAT(SUBSTRING(unwalked_bar, numbers.n, 1) ORDER BY ordering_column SEPARATOR '') AS horizontal_bar
	    FROM
	      numbers
	    INNER JOIN (
	      SELECT
	        ordering_column,
	        GROUP_CONCAT(bar_string_token ORDER BY string_position SEPARATOR '') AS unwalked_bar
	      FROM
	        (SELECT
	          ordering_column,
	          string_position,
	          min(scaled_string_position) as scaled_string_position,
	          REPLACE(LEFT(GROUP_CONCAT(bar_string_token ORDER BY bar_string_token DESC SEPARATOR ''), 1), ' ', '-') AS bar_string_token
	        FROM
	          (SELECT
	            ordering_column,
	            @multi_line_chart_scaled_string_position := CONVERT((row_value-@multi_line_chart_min_value)*(@multi_line_chart_graph_rows-1)/(@multi_line_chart_max_value-@multi_line_chart_min_value), UNSIGNED) AS scaled_string_position,
	            n AS string_position,
	            IF(numbers.n = @multi_line_chart_scaled_string_position+1, SUBSTRING(@multi_line_chart_graph_colors, row_value_indicator, 1), ' ') AS bar_string_token
	          FROM
	            numbers,
	            (SELECT
	              ordering_column,
	              n AS row_value_indicator,
	              row_value
	            FROM (
	              SELECT
	                *,
	                @multi_line_chart_min_value := LEAST(IFNULL(cast(@multi_line_chart_min_value as decimal(64,20)), row_value), IFNULL(row_value, cast(@multi_line_chart_min_value as decimal(64,20)))) AS min_value,
    	            @multi_line_chart_max_value := GREATEST(IFNULL(cast(@multi_line_chart_max_value as decimal(64,20)), row_value), IFNULL(row_value, cast(@multi_line_chart_max_value as decimal(64,20)))) AS max_value,
	                @multi_line_chart_min_range := LEAST(IFNULL(@multi_line_chart_min_range, ordering_column), ordering_column) AS min_range,
	                @multi_line_chart_max_range := GREATEST(IFNULL(@multi_line_chart_max_range, ordering_column), ordering_column) AS max_range
	              FROM
	                (SELECT
	                  *,
	                  col1 as ordering_column,
	                  cast(
                        case n
	                      when 1 then col2   
	                      when 2 then col3   
	                      when 3 then col4   
	                      when 4 then col5   
	                      when 5 then col6   
	                      when 6 then col7   
	                      when 7 then col8   
	                      when 8 then col9   
	                    end 
                        as DECIMAL(64,20)
                      ) AS row_value
	                FROM
	                  numbers,
	                  (${wrapped_query}) AS sel_main_values,
	                  (SELECT @multi_line_chart_bar_length := NULL) AS select_nullify_bar_length,
	                  (SELECT @multi_line_chart_min_range := NULL) AS select_min_range,
	                  (SELECT @multi_line_chart_max_range := NULL) AS select_max_range,
	                  (SELECT @multi_line_chart_graph_colors := '#*@%o+x;m:') AS select_graph_colors,
	                  (SELECT @multi_line_chart_graph_fallback_colors := 'abcdefghij') AS select_graph_fallback_colors,
	                  (SELECT @multi_line_chart_value_precision := 2) AS select_value_precision	                  
	                WHERE
	                  numbers.n BETWEEN 1 AND @multi_line_chart_num_values
	                ) sel_counted_values_main_values
	              ) sel_row_values
	            ) AS sel_row_values_indicators
	          WHERE
	            numbers.n BETWEEN 1 AND @multi_line_chart_graph_rows
	          ) AS sel_marked_row_values
	        GROUP BY
	          ordering_column, string_position
	        ) AS sel_walked_bar
	      GROUP BY
	        ordering_column
	    ) AS select_vertical
	    WHERE
	      numbers.n BETWEEN 1 AND CHAR_LENGTH(unwalked_bar)
	    GROUP BY
	      numbers.n
	    ORDER BY
	      numbers.n DESC
	    ) AS select_horizontal
	  ) AS select_horizontal_untitled
	UNION ALL
	SELECT '', CONCAT('v', REPEAT(':', @multi_line_chart_bar_length-2), 'v')
	UNION ALL
	SELECT '', CONCAT(@multi_line_chart_min_range, REPEAT(' ', @multi_line_chart_bar_length-CHAR_LENGTH(@multi_line_chart_min_range)-CHAR_LENGTH(@multi_line_chart_max_range)), @multi_line_chart_max_range)
	UNION ALL
	SELECT
	  '', CONCAT('    ', SUBSTRING(@multi_line_chart_graph_colors, n, 1), ' ', trim_wspace(SUBSTRING_INDEX(SUBSTRING_INDEX(@multi_line_chart_values_legend, ',', n), ',', -1)))
	FROM
	  numbers
	WHERE
	  n BETWEEN 1 AND @multi_line_chart_num_values
	  AND @multi_line_chart_values_legend IS NOT NULL

  ";
  set @_line_chart_query := replace(@_line_chart_query, '${wrapped_query}', @_line_chart_values_query);
  set @_line_chart_query := replace(@_line_chart_query, '${multi_line_chart_value_precision}', @multi_line_chart_value_precision);
  
  call exec_single(@_line_chart_query);
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `prettify_message` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `prettify_message`(title TINYTEXT CHARSET utf8, msg MEDIUMTEXT CHARSET utf8)
    NO SQL
    SQL SECURITY INVOKER
    COMMENT 'Outputs a prettified text message, one row per line in text'
main_body: begin
  declare query text charset utf8;
  
  if msg is null or msg = '' then
    leave main_body;
  end if;
  
  set @_prettify_message_text := msg;
  set @_prettify_message_num_rows := get_num_tokens(msg, '\n');
  set query := CONCAT('
    SELECT 
        split_token(@_prettify_message_text, \'\\n\', n) AS ', mysql_qualify(title), '
      FROM 
        numbers
      WHERE 
        numbers.n BETWEEN 1 AND @_prettify_message_num_rows
      ORDER BY n ASC;
    ');
  call exec_single(query);
  set @_prettify_message_text := NULL;
  set @_prettify_message_num_rows := NULL;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `query_checksum` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `query_checksum`(in query TEXT CHARSET utf8)
    READS SQL DATA
    SQL SECURITY INVOKER
    COMMENT 'Checksum resultset of given query (max 9 columns)'
begin
  
  declare sql_query_num_columns TINYINT UNSIGNED DEFAULT 9;
  declare result_checksum CHAR(40) CHARSET ascii DEFAULT '';
  
  set @query_checksum_result := NULL;
  if not _is_select_query(query) then
    call throw('query_checksum input must be SELECT query');
  end if;

  DROP TEMPORARY TABLE IF EXISTS _tmp_query_checksum;
    
  call _wrap_select_list_columns(query, sql_query_num_columns, @common_schema_error);
  set @_common_schema_checkum_temporary_query := CONCAT('CREATE TEMPORARY TABLE _tmp_query_checksum ', query);

  PREPARE st FROM @_common_schema_checkum_temporary_query;
  EXECUTE st;
  DEALLOCATE PREPARE st;
    
  
  begin	
    declare col1, col2, col3, col4, col5, col6, col7, col8, col9 VARCHAR(4096) CHARSET utf8;
    declare done INT DEFAULT 0;
    declare query_cursor cursor for SELECT * FROM _tmp_query_checksum;
    declare continue handler for NOT FOUND set done = 1;
          
    open query_cursor;
    read_loop: loop
      fetch query_cursor into col1, col2, col3, col4, col5, col6, col7, col8, col9;
      if done then
        leave read_loop;
      end if;
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col1, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col2, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col3, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col4, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col5, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col6, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col7, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col8, '\0')));
      set result_checksum := MD5(CONCAT(result_checksum, '\0', IFNULL(col9, '\0')));
    end loop;
    close query_cursor;
  end; 
    
  DROP TEMPORARY TABLE IF EXISTS _tmp_query_checksum;
  
  SELECT (@query_checksum_result := result_checksum) AS `checksum`;
end ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_compile_routine` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_compile_routine`(
  in rdebug_routine_schema varchar(128) charset utf8,
  in rdebug_routine_name   varchar(128) charset utf8,
  in debug_info     bool
  )
    MODIFIES SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
  declare quoting_characters VARCHAR(5) CHARSET ascii DEFAULT '`''';
  declare compiled_body, compiled_body_utf8 longblob;
  declare debug_code text charset utf8 default '';
  declare first_statement_debug_code text charset utf8;
  declare first_valid_for_breakpoint_debug_code text charset utf8;
  declare first_valid_for_breakpoint_id int unsigned default null;
  declare debug_code_start varchar(64) charset utf8 default _rdebug_get_debug_code_start();
  declare debug_code_end varchar(64) charset utf8 default _rdebug_get_debug_code_end();
  declare routine_param_list blob default null;

  set @__debug_group_concat_max_len := @@group_concat_max_len;
  set @@group_concat_max_len := GREATEST(@@group_concat_max_len, 32 * 1024 * 1024);
  
  if not find_in_set('ANSI_QUOTES', @@sql_mode) then
    set quoting_characters := CONCAT(quoting_characters, '"');
  end if;

  
  set compiled_body := null;
  select body, body_utf8, param_list from mysql.proc where db = rdebug_routine_schema and name = rdebug_routine_name into compiled_body, compiled_body_utf8, routine_param_list;
  if compiled_body is null then
    call throw(CONCAT('Unknown routine: ', mysql_qualify(rdebug_routine_schema), '.', mysql_qualify(rdebug_routine_name)));
  end if;
  
  
  set compiled_body := replace_sections(compiled_body, debug_code_start, debug_code_end, '');
  set compiled_body_utf8 := replace_sections(compiled_body_utf8, debug_code_start, debug_code_end, '');

  begin
    declare v_from, v_old_from int unsigned;
    declare v_token text;
    declare v_level int;
    declare v_state varchar(32);
    declare _sql_tokens_id int unsigned default 0;
    
    drop temporary table if exists _routine_tokens;
    create temporary table _routine_tokens(
        id int unsigned primary key
    ,   start int unsigned  not null
    ,   level int not null
    ,   token text          
    ,   state text           not null
    ,   nesting_level int unsigned default 0
    ,   is_valid_for_breakpoint tinyint unsigned default 0
    ,   is_declare_variables_statement tinyint unsigned default 0
    ,   is_first_statement tinyint unsigned default 0
    ) engine=MyISAM;
    
    repeat 
      set v_old_from = v_from;
      call _get_sql_token(compiled_body, v_from, v_level, v_token, 'routine', v_state);
      set _sql_tokens_id := _sql_tokens_id + 1;
      insert into _routine_tokens(id,start,level,token,state) 
      values (_sql_tokens_id, v_from - char_length(v_token), v_level, v_token, v_state);
    until 
      v_old_from = v_from
    end repeat;
  end;
  
  if debug_info then
    set debug_code := '';
    set debug_code := concat(debug_code, '_RDEBUG_RESTORE_STACK_LEVEL');
    set debug_code := concat(debug_code, '_RDEBUG_EXPORT_VARIABLES');
    set debug_code := concat(debug_code, 'call ', database(), '._rdebug_on_breakpoint(_RDEBUG_BREAKPOINT_ID,', QUOTE(rdebug_routine_schema), ',', QUOTE(rdebug_routine_name),');');
    set debug_code := concat(debug_code, '_RDEBUG_IMPORT_VARIABLES');
    set debug_code := concat(debug_code_start, _rdebug_get_debug_code_breakpoint_hint_start(), '_RDEBUG_BREAKPOINT_ID', _rdebug_get_debug_code_breakpoint_hint_end(), debug_code, debug_code_end);
    
    set first_statement_debug_code := concat('declare _rdebug_stack_level_ int unsigned default (@_rdebug_stack_level_ := ', database(), '._rdebug_get_next_stack_level());');
    set first_statement_debug_code := concat(debug_code_start, first_statement_debug_code, debug_code_end);
    
    set first_valid_for_breakpoint_debug_code := concat('call ', database(), '._rdebug_on_routine_entry(', QUOTE(rdebug_routine_schema), ',', QUOTE(rdebug_routine_name), ');');
    set first_valid_for_breakpoint_debug_code := concat(debug_code_start, first_valid_for_breakpoint_debug_code, debug_code_end);
    
    call _rdebug_analyze_routine(rdebug_routine_schema, rdebug_routine_name);
    call _rdebug_analyze_routine_params(rdebug_routine_schema, rdebug_routine_name, routine_param_list, quoting_characters);
    call _rdebug_analyze_routine_variables_scope(rdebug_routine_schema, rdebug_routine_name);

    select id from _routine_tokens where is_valid_for_breakpoint order by id limit 1 into first_valid_for_breakpoint_id;
    
    select 
        group_concat(
          if(is_first_statement, first_statement_debug_code, ''),
          if(id = first_valid_for_breakpoint_id, first_valid_for_breakpoint_debug_code, ''),
          if(
            is_valid_for_breakpoint, 
            REPLACE(
            REPLACE(
            REPLACE(
            REPLACE(
              debug_code, 
                '_RDEBUG_BREAKPOINT_ID', id ), 
                '_RDEBUG_EXPORT_VARIABLES', IF(export_variables is not null, CONCAT('set ', export_variables, ';'), '') ),
                '_RDEBUG_IMPORT_VARIABLES', IF(import_variables is not null, CONCAT('set ', import_variables, ';'), '') ),
                '_RDEBUG_RESTORE_STACK_LEVEL', 'set @_rdebug_stack_level_ := _rdebug_stack_level_;' ),
            '' 
          ), token 
          order by id separator '' 
        ) 
      from (
        select 
          _routine_tokens.*, 
          group_concat(variable_name order by variable_name) as variable_names,
          group_concat(if(variable_type in ('local', 'param'), concat(variable_name,':= ', '@$_$',variable_name), NULL) order by variable_name) as import_variables,
          group_concat(if(variable_type in ('local', 'param'), concat('@$_$',variable_name,':= ', variable_name), NULL) order by variable_name) as export_variables
        from 
          _routine_tokens
          left join _rdebug_routine_variables on (
            _routine_tokens.id between _rdebug_routine_variables.variable_scope_id_start and _rdebug_routine_variables.variable_scope_id_end
            and routine_schema = rdebug_routine_schema and routine_name = rdebug_routine_name
          )
        group by 
          _routine_tokens.id,
          _routine_tokens.start,
          _routine_tokens.level,
          _routine_tokens.token,
          _routine_tokens.state,
          _routine_tokens.nesting_level,
          _routine_tokens.is_valid_for_breakpoint,
          _routine_tokens.is_declare_variables_statement,
          _routine_tokens.is_first_statement
        ) select_tokens_variables
      into 
        compiled_body;
    set compiled_body_utf8 := compiled_body;
  end if;
  
  update mysql.proc set body = compiled_body, body_utf8 = compiled_body_utf8 where db = rdebug_routine_schema and name = rdebug_routine_name;
  

  call _rdebug_invalidate_routine_cache();
  
  set @@group_concat_max_len := @__debug_group_concat_max_len;  
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_release_debugger` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_release_debugger`()
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  call _rdebug_send_breakpoint_clock();
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_run` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_run`()
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  call _rdebug_set_step_hint('run');
  

  
  call _rdebug_release_worker_and_wait_for_breakpoint();
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_set_breakpoint` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_set_breakpoint`(
    in rdebug_routine_schema varchar(128) charset utf8,
    in rdebug_routine_name   varchar(128) charset utf8,
    in rdebug_statement_id   int unsigned,
    in rdebug_conditional_expression text charset utf8,
    in breakpoint_enabled bool
  )
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  if breakpoint_enabled then
    insert into 
      _rdebug_breakpoint_hints (worker_id, routine_schema, routine_name, statement_id, conditional_expression)
      values (@_rdebug_recipient_id, rdebug_routine_schema, rdebug_routine_name, rdebug_statement_id, rdebug_conditional_expression)
      on duplicate key update conditional_expression = values(conditional_expression)
    ;
  else
    delete from _rdebug_breakpoint_hints
      where worker_id = @_rdebug_recipient_id
        and routine_schema = rdebug_routine_schema
        and routine_name = rdebug_routine_name
        and statement_id = rdebug_statement_id
    ;
  end if;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_set_variable` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_set_variable`(
    in rdebug_variable_name varchar(128),
    in rdebug_variable_value blob
  )
    MODIFIES SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  declare current_stack_level int unsigned;
  
  select 
      max(stack_level) 
    from 
      _rdebug_stack_state 
    where 
      worker_id = @_rdebug_recipient_id
    into current_stack_level;
    
  update 
      _rdebug_stack_state
      join _rdebug_routine_variables using (routine_schema, routine_name)
      join _rdebug_routine_variables_state using (worker_id, stack_level, routine_schema, routine_name, variable_name)
    set 
      variable_value = rdebug_variable_value
    where
      _rdebug_stack_state.worker_id = @_rdebug_recipient_id
      and _rdebug_stack_state.stack_level = current_stack_level
      and _rdebug_stack_state.statement_id between variable_scope_id_start and variable_scope_id_end
      and variable_name = rdebug_variable_name
      ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_set_verbose` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_set_verbose`(
    in verbose bool
  )
    NO SQL
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
  set @_rdebug_verbose := (verbose is true);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_show_routine` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_show_routine`(
  in rdebug_routine_schema varchar(128) charset utf8,
  in rdebug_routine_name   varchar(128) charset utf8
  )
    MODIFIES SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
BEGIN
  declare routine_body longblob default null;
  declare debug_code_start varchar(64) charset utf8 default _rdebug_get_debug_code_start();
  declare debug_code_end varchar(64) charset utf8 default _rdebug_get_debug_code_end();

  select body from mysql.proc where db = rdebug_routine_schema and name = rdebug_routine_name into routine_body;
  if routine_body is null then
    call throw(CONCAT('Unknown routine: ', mysql_qualify(rdebug_routine_schema), '.', mysql_qualify(rdebug_routine_name)));
  end if;
  
  set routine_body := replace_sections(routine_body, concat(debug_code_start, _rdebug_get_debug_code_breakpoint_hint_start()), _rdebug_get_debug_code_breakpoint_hint_end(), concat('[:\\0]', debug_code_start));
  set routine_body := replace_sections(routine_body, concat(debug_code_start, _rdebug_get_debug_code_breakpoint_hint()), debug_code_end, '[:]');
  set routine_body := replace_sections(routine_body, debug_code_start, debug_code_end, '');
  call prettify_message(concat(mysql_qualify(rdebug_routine_schema), '.', mysql_qualify(rdebug_routine_name), ' breakpoints'), routine_body);
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_show_routine_statements` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_show_routine_statements`(
  in rdebug_routine_schema varchar(128) charset utf8,
  in rdebug_routine_name   varchar(128) charset utf8
  )
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  select 
      routine_schema, routine_name, statement_id
    from 
      _rdebug_routine_statements 
    where 
      routine_schema = rdebug_routine_schema
      and routine_name = rdebug_routine_name
    order by statement_id
  ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_show_stack_state` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_show_stack_state`()
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  select 
      stack_level, routine_schema, routine_name, statement_id, entry_time
    from 
      _rdebug_stack_state 
    where 
      worker_id = @_rdebug_recipient_id
    order by stack_level
  ;
END ;;
DELIMITER ;
/*!50003 DROP PROCEDURE IF EXISTS `rdebug_show_statement` */;
DELIMITER ;;
CREATE DEFINER=`percona`@`localhost` PROCEDURE `rdebug_show_statement`()
    READS SQL DATA
    DETERMINISTIC
    SQL SECURITY INVOKER
main_body: BEGIN
  declare rdebug_start_pos, rdebug_end_pos int unsigned default 0;
  declare rdebug_statement_id int unsigned;
  declare rdebug_routine_schema, rdebug_routine_name varchar(128) default null;
  declare debug_code_start varchar(64) charset utf8 default _rdebug_get_debug_code_start();
  declare debug_code_end varchar(64) charset utf8 default _rdebug_get_debug_code_end();
  declare rdebug_routine_body longblob default null;
  
  select 
      routine_schema, routine_name, statement_id, statement_start_pos, statement_end_pos
    from 
      (select * from _rdebug_stack_state where worker_id = @_rdebug_recipient_id
       order by stack_level desc limit 1) select_current_stack_state
      join _rdebug_routine_statements using (routine_schema, routine_name, statement_id)
    into
      rdebug_routine_schema, rdebug_routine_name, rdebug_statement_id, rdebug_start_pos, rdebug_end_pos
    ;
