# Test file for stored procedure bugfixes

--echo #
--echo # Bug #47412: Valgrind warnings / user can read uninitalized memory
--echo # using SP variables
--echo #

CREATE SCHEMA testdb;
USE testdb;
DELIMITER |;
CREATE FUNCTION f2 () RETURNS INTEGER
BEGIN
   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
   RETURN f_not_exists () ;
END|
CREATE PROCEDURE p3 ( arg1 VARCHAR(32) )
BEGIN
   CALL p_not_exists ( );
END|
DELIMITER ;|
--echo # should not return valgrind warnings
--error ER_SP_DOES_NOT_EXIST
CALL p3 ( f2 () );

DROP SCHEMA testdb;

CREATE SCHEMA testdb;
USE testdb;
DELIMITER |;
CREATE FUNCTION f2 () RETURNS INTEGER
BEGIN
   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
   RETURN f_not_exists () ;
END|
CREATE PROCEDURE p3 ( arg2 INTEGER )
BEGIN
   CALL p_not_exists ( );
END|
DELIMITER ;|
--echo # should not return valgrind warnings
--error ER_SP_DOES_NOT_EXIST
CALL p3 ( f2 () );

DROP SCHEMA testdb;

CREATE SCHEMA testdb;
USE testdb;
DELIMITER |;
CREATE FUNCTION f2 () RETURNS INTEGER
BEGIN
   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
   RETURN f_not_exists () ;
END|
DELIMITER ;|
--echo # should not return valgrind warnings
SELECT f2 ();

DROP SCHEMA testdb;

USE test;

--echo #
--echo # Bug#50423: Crash on second call of a procedure dropping a trigger
--echo #

--disable_warnings
DROP TABLE IF EXISTS t1;
DROP TRIGGER IF EXISTS tr1;
DROP PROCEDURE IF EXISTS p1;
--enable_warnings

CREATE TABLE t1 (f1 INTEGER);
CREATE TRIGGER tr1 BEFORE INSERT ON t1 FOR EACH ROW SET @aux = 1;
CREATE PROCEDURE p1 () DROP TRIGGER tr1;

CALL p1 ();
--error ER_TRG_DOES_NOT_EXIST
CALL p1 ();

DROP TABLE t1;
DROP PROCEDURE p1;

--echo #
--echo # Bug#50423: Crash on second call of a procedure dropping a trigger
--echo #

--disable_warnings
DROP TABLE IF EXISTS t1;
DROP TRIGGER IF EXISTS tr1;
DROP PROCEDURE IF EXISTS p1;
--enable_warnings

CREATE TABLE t1 (f1 INTEGER);
CREATE TRIGGER tr1 BEFORE INSERT ON t1 FOR EACH ROW SET @aux = 1;
CREATE PROCEDURE p1 () DROP TRIGGER tr1;

CALL p1 ();
--error ER_TRG_DOES_NOT_EXIST
CALL p1 ();

DROP TABLE t1;
DROP PROCEDURE p1;

--echo #
--echo # Bug#54375: Error in stored procedure leaves connection
--echo # in different default schema
--echo #

--disable_warnings
SET @@SQL_MODE = 'STRICT_ALL_TABLES';
DROP DATABASE IF EXISTS db1;
CREATE DATABASE db1;
USE db1;
DROP TABLE IF EXISTS t1;
CREATE TABLE t1 (c1 int NOT NULL PRIMARY KEY);
INSERT INTO t1 VALUES (1);
DELIMITER $$;
CREATE FUNCTION f1 (
	some_value int
)
RETURNS smallint
DETERMINISTIC
BEGIN
	INSERT INTO t1 SET c1 = some_value;
        RETURN(LAST_INSERT_ID());
END$$
DELIMITER ;$$
DROP DATABASE IF EXISTS db2;
CREATE DATABASE db2;
--enable_warnings
USE db2;
SELECT DATABASE();
--error ER_DUP_ENTRY
SELECT db1.f1(1);
SELECT DATABASE();
USE test;
DROP FUNCTION db1.f1;
DROP TABLE db1.t1;
DROP DATABASE db1;
DROP DATABASE db2;
--echo End of 5.1 tests
