mariadb/sql/sp_cursor.h
Alexander Barkov e6961ea311 MDEV-20034 Add support for the pre-defined weak SYS_REFCURSOR
This patch adds support for SYS_REFCURSOR (a weakly typed cursor)
for both sql_mode=ORACLE and sql_mode=DEFAULT.

Works as a regular stored routine variable, parameter and return value:

- can be passed as an IN parameter to stored functions and procedures
- can be passed as an INOUT and OUT parameter to stored procedures
- can be returned from a stored function

Note, strongly typed REF CURSOR will be added separately.

Note, to maintain dependencies easier, some parts of sql_class.h
and item.h were moved to new header files:

- select_results.h:
  class select_result_sink
  class select_result
  class select_result_interceptor

- sp_cursor.h:
  class sp_cursor_statistics
  class sp_cursor

- sp_rcontext_handler.h
  class Sp_rcontext_handler and its descendants

The implementation consists of the following parts:
- A new class sp_cursor_array deriving from Dynamic_array

- A new class Statement_rcontext which contains data shared
  between sub-statements of a compound statement.
  It has a member m_statement_cursors of the sp_cursor_array data type,
  as well as open cursor counter. THD inherits from Statement_rcontext.

- A new data type handler Type_handler_sys_refcursor in plugins/type_cursor/
  It is designed to store uint16 references -
  positions of the cursor in THD::m_statement_cursors.

- Type_handler_sys_refcursor suppresses some derived numeric features.
  When a SYS_REFCURSOR variable is used as an integer an error is raised.

- A new abstract class sp_instr_fetch_cursor. It's needed to share
  the common code between "OPEN cur" (for static cursors) and
  "OPER cur FOR stmt" (for SYS_REFCURSORs).

- New sp_instr classes:
  * sp_instr_copen_by_ref      - OPEN sys_ref_curor FOR stmt;
  * sp_instr_cfetch_by_ref     - FETCH sys_ref_cursor INTO targets;
  * sp_instr_cclose_by_ref     - CLOSE sys_ref_cursor;
  * sp_instr_destruct_variable - to destruct SYS_REFCURSOR variables when
                                 the execution goes out of the BEGIN..END block
                                 where SYS_REFCURSOR variables are declared.
- New methods in LEX:
  * sp_open_cursor_for_stmt   - handles "OPEN sys_ref_cursor FOR stmt".
  * sp_add_instr_fetch_cursor - "FETCH cur INTO targets" for both
                                static cursors and SYS_REFCURSORs.
  * sp_close - handles "CLOSE cur" both for static cursors and SYS_REFCURSORs.

- Changes in cursor functions to handle both static cursors and SYS_REFCURSORs:
  * Item_func_cursor_isopen
  * Item_func_cursor_found
  * Item_func_cursor_notfound
  * Item_func_cursor_rowcount

- A new system variable @@max_open_cursors - to limit the number
  of cursors (static and SYS_REFCURSORs) opened at the same time.
  Its allowed range is [0-65536], with 50 by default.

- A new virtual method Type_handler::can_return_bool() telling
  if calling item->val_bool() is allowed for Items of this data type,
  or if otherwise the "Illegal parameter for operation" error should be raised
  at fix_fields() time.

- New methods in Sp_rcontext_handler:
  * get_cursor()
  * get_cursor_by_ref()

- A new class Sp_rcontext_handler_statement to handle top level statement
  wide cursors which are shared by all substatements.

- A new virtual method expr_event_handler() in classes Item and Field.
  It's needed to close (and make available for a new OPEN)
  unused THD::m_statement_cursors elements which do not have any references
  any more. It can happen in various moments in time, e.g.
  * after evaluation parameters of an SQL routine
  * after assigning a cursor expression into a SYS_REFCURSOR variable
  * when leaving a BEGIN..END block with SYS_REFCURSOR variables
  * after setting OUT/INOUT routine actual parameters from formal
    parameters.
2025-03-18 18:31:28 +01:00

286 lines
7.8 KiB
C++

/*
Copyright (c) 2009, 2025, MariaDB Corporation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */
#ifndef SP_CURSOR_INCLUDED
#define SP_CURSOR_INCLUDED
#include "sp_rcontext_handler.h"
class Server_side_cursor;
class sp_cursor_statistics
{
protected:
ulonglong m_fetch_count; // Number of FETCH commands since last OPEN
ulonglong m_row_count; // Number of successful FETCH since last OPEN
bool m_found; // If last FETCH fetched a row
public:
sp_cursor_statistics()
:m_fetch_count(0),
m_row_count(0),
m_found(false)
{ }
bool found() const
{ return m_found; }
ulonglong row_count() const
{ return m_row_count; }
ulonglong fetch_count() const
{ return m_fetch_count; }
void reset() { *this= sp_cursor_statistics(); }
};
class sp_instr_cpush;
/* A mediator between stored procedures and server side cursors */
class sp_lex_keeper;
class sp_cursor: public sp_cursor_statistics
{
private:
/// An interceptor of cursor result set used to implement
/// FETCH <cname> INTO <varlist>.
class Select_fetch_into_spvars: public select_result_interceptor
{
List<sp_fetch_target> *m_fetch_target_list;
uint field_count;
bool m_view_structure_only;
bool send_data_to_variable_list(List<sp_fetch_target> &vars,
List<Item> &items);
public:
Select_fetch_into_spvars(THD *thd_arg, bool view_structure_only)
:select_result_interceptor(thd_arg),
m_view_structure_only(view_structure_only)
{}
void reset(THD *thd_arg)
{
select_result_interceptor::reinit(thd_arg);
m_fetch_target_list= NULL;
field_count= 0;
}
uint get_field_count() { return field_count; }
void set_spvar_list(List<sp_fetch_target> *vars)
{
m_fetch_target_list= vars;
}
bool send_eof() override { return FALSE; }
int send_data(List<Item> &items) override;
int prepare(List<Item> &list, SELECT_LEX_UNIT *u) override;
bool view_structure_only() const override { return m_view_structure_only; }
};
public:
sp_cursor()
:result(NULL, false),
server_side_cursor(NULL)
{ }
sp_cursor(THD *thd_arg, bool view_structure_only)
:result(thd_arg, view_structure_only),
server_side_cursor(NULL)
{}
virtual ~sp_cursor()
{ destroy(); }
virtual sp_lex_keeper *get_lex_keeper() { return nullptr; }
int open(THD *thd, bool check_max_open_cursor_counter= true);
int close(THD *thd);
my_bool is_open() const
{ return MY_TEST(server_side_cursor); }
int fetch(THD *, List<sp_fetch_target> *vars, bool error_on_no_data);
bool export_structure(THD *thd, Row_definition_list *list);
void reset(THD *thd_arg)
{
sp_cursor_statistics::reset();
result.reinit(thd_arg);
server_side_cursor= NULL;
}
/*
Reset a cursor before reopening (two OPEN without CLOSE in between).
This method does not raise ER_SP_CURSOR_ALREADY_OPEN.
It's used to handle:
c SYS_REFCURSOR;
OPEN c FOR SELECT 1;
OPEN c FOR SELECT 2; -- This is allowed without closing the previous OPEN
*/
void reset_for_reopen(THD *thd_arg)
{
if (is_open())
close(thd_arg);
reset(thd_arg);
}
virtual sp_instr_cpush *get_push_instr() { return nullptr; }
private:
Select_fetch_into_spvars result;
Server_side_cursor *server_side_cursor;
void destroy();
};
class sp_cursor_array_element: public sp_cursor
{
uint m_ref_count;
public:
sp_cursor_array_element()
:sp_cursor(),
m_ref_count(0)
{ }
uint ref_count() const { return m_ref_count; }
void ref_count_inc() { m_ref_count++; }
void ref_count_dec(THD *thd)
{
/*
For performance purposes, the SP instructions in sp_head::m_instr
do not guarantee that the number of ref_cursor_inc() calls matches the
number of ref_cursor_dec() calls:
We don't add sp_instr_destruct_variable instructions in these cases:
- before sp_instr_freturn and sp_instr_preturn
- after the very last instruction
(the one before the END of the most outer stored routine block)
So sp_head::execute() can leave with some SYS_REFCURORs variables
still attached to thd->m_statement_cursor elements.
Later they get detached by the sp_rcontext::sp_variable_detach_all()
calls in sp_head::execute_procedure() and sp_head::execute_function().
Executing a bunch of sp_instr_destruct_variable instructions would
be more expensive.
*/
if (m_ref_count > 0)
{
m_ref_count--;
if (!m_ref_count && is_open())
close(thd);
}
}
void reset(THD *thd, uint ref_count)
{
sp_cursor::reset(thd);
m_ref_count= ref_count;
}
};
class sp_cursor_array: public Dynamic_array<sp_cursor_array_element>
{
protected:
Type_ref_null find_unused()
{
for (size_t i= 0 ; i < size(); i++)
{
if (!at(i).is_open() && !at(i).ref_count())
return Type_ref_null((ulonglong) i);
}
return Type_ref_null();
}
Type_ref_null append(THD *thd);
public:
sp_cursor_array()
:Dynamic_array(PSI_INSTRUMENT_MEM, 0)
{}
~sp_cursor_array()
{
free(current_thd);
}
ULonglong_null ref_count(ulonglong offset) const
{
return offset < elements() ?
ULonglong_null((ulonglong) at((size_t) offset).ref_count()) :
ULonglong_null();
}
void ref_count_inc(ulonglong offset)
{
if (offset < elements())
at((size_t) offset).ref_count_inc();
}
void ref_count_dec(THD *thd, ulonglong offset)
{
if (offset < elements())
at((size_t) offset).ref_count_dec(thd);
}
void ref_count_update(THD *thd, const Type_ref_null &old_value,
const Type_ref_null &new_value)
{
if (old_value.is_null())
{
if (!new_value.is_null())
ref_count_inc(new_value.value());
}
else if (new_value.is_null())
{
ref_count_dec(thd, old_value.value());
}
else if (old_value.value() != new_value.value())
{
ref_count_dec(thd, old_value.value());
ref_count_inc(new_value.value());
}
}
/*
Find a cursor at the offset specified by "ref".
@param thd - current thd
@param ref - the field containing the cursor offset
@param for_open - tells if the cursor is needed for OPEN or
for FETCH/CLOSE and determines the behaviour
on dereference failure.
Dereference failure means either of these:
- ref->is_null() returned true.
This happens when the reference SYS_REFCURSOR variable
owning the Field "ref" is not assigned to any cursors yet.
- ref->val_int() returned an offset greater than elements()-1.
This can mean that something went wrong in the code.
If dereference failed, then:
- In case for_open is false the function returns nullptr.
- In case for_open is true, the function searches for an unused cursor.
If all cursors are used, it appends a new cursor to the end of the array.
*/
sp_cursor_array_element *get_cursor_by_ref(THD *thd, Field *ref,
bool for_open);
void close(THD *thd)
{
for (uint i= 0; i < (uint) size(); i++)
{
if (at(i).is_open())
at(i).close(thd);
}
}
void free(THD *thd)
{
close(thd);
free_memory();
}
};
#endif // SP_CURSOR_INCLUDED