--echo #
--echo # MDEV-20034 Add support for the pre-defined weak SYS_REFCURSOR
--echo #

#
# Cursor operations on a ROW field are not supported yet:
# OPEN row_name.field_name;
# FETCH row_name.field_name INTO v;
# FETCH cur INTO row_name.field_name;
# CLOSE row_name.field_name;
#

--echo #
--echo # ROWs with SYS_REFCURSOR fields
--echo #

DELIMITER /;
CREATE PROCEDURE p1(p1r0 ROW(c0 SYS_REFCURSOR, c1 SYS_REFCURSOR))
BEGIN
  DECLARE c0 SYS_REFCURSOR DEFAULT p1r0.c0;
  DECLARE c1 SYS_REFCURSOR DEFAULT p1r0.c1;
  DECLARE v0 INT;
  DECLARE v1 INT;
  FETCH c0 INTO v0;
  FETCH c1 INTO v1;
  SELECT v0, v1;
END
/
CREATE PROCEDURE p2()
BEGIN
  DECLARE c0 SYS_REFCURSOR;
  DECLARE c1 SYS_REFCURSOR;
  OPEN c0 FOR SELECT 10;
  OPEN c1 FOR SELECT 11;
  CALL p1(ROW(c0, c1));
END;
/
DELIMITER ;/
CALL p2;
DROP PROCEDURE p2;
DROP PROCEDURE p1;

--echo #
--echo # Fetching from a SYS_REFCURSOR variable to an explicit ROW
--echo #

DELIMITER /;
CREATE PROCEDURE p1()
BEGIN
  DECLARE c0 SYS_REFCURSOR;
  DECLARE r0 ROW (a INT, b VARCHAR(10));
  OPEN c0 FOR SELECT 1, 'b1';
  FETCH c0 INTO r0;
  SELECT r0.a, r0.b;
END;
/
DELIMITER ;/
CALL p1;
DROP PROCEDURE p1;


--echo #
--echo # Fetching from a SYS_REFCURSOR variable to an anchored ROW
--echo #

CREATE TABLE t1 (a INT, b VARCHAR(10));
INSERT INTO t1 VALUES (1,'b1');
DELIMITER /;
CREATE PROCEDURE p1()
BEGIN
  DECLARE c0 SYS_REFCURSOR;
  DECLARE r0 ROW TYPE OF t1;
  OPEN c0 FOR SELECT * FROM t1;
  FETCH c0 INTO r0;
  SELECT r0.a, r0.b;
END;
/
DELIMITER ;/
CALL p1;
DROP PROCEDURE p1;
DROP TABLE t1;

--echo #
--echo # Make sure a ROW variable with SYS_REFCURSOR members destructs
--echo # its members properly when leaving a BEGIN..END block.
--echo #

DELIMITER /;
CREATE PROCEDURE p1()
BEGIN
  BEGIN
    DECLARE r0 ROW(m0 SYS_REFCURSOR, m1 SYS_REFCURSOR);
    BEGIN
      DECLARE c0 SYS_REFCURSOR;
      DECLARE c1 SYS_REFCURSOR;
      OPEN c0 FOR SELECT 10;
      OPEN c1 FOR SELECT 11;
      SET r0= ROW(c0, c1);
    END;
    SELECT r0.m0, r0.m1; -- Expect 0, 1
  END; -- All SYS_REFCURSORs should be freed here: c0, c1, r0.m0, r0.m1
  BEGIN
    DECLARE v0 INT;
    DECLARE v1 INT;
    DECLARE c0 SYS_REFCURSOR;
    DECLARE c1 SYS_REFCURSOR;
    OPEN c0 FOR SELECT 20; -- Expect to reuse m_statement_cursors.at(0)
    OPEN c1 FOR SELECT 21; -- Expect to reuse m_statement_cursors.at(1)
    FETCH c0 INTO v0;
    FETCH c1 INTO v1;
    SELECT c0, c1, v0, v1; -- Expect 0, 1, 20, 21
  END;
END;
/
DELIMITER ;/
CALL p1;
DROP PROCEDURE p1;
