summaryrefslogtreecommitdiff
path: root/sql/sql_prepare.cc
diff options
context:
space:
mode:
Diffstat (limited to 'sql/sql_prepare.cc')
-rw-r--r--sql/sql_prepare.cc1697
1 files changed, 1106 insertions, 591 deletions
diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc
index a07fcc37856..cd11b6d4c24 100644
--- a/sql/sql_prepare.cc
+++ b/sql/sql_prepare.cc
@@ -13,7 +13,9 @@
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
-/**********************************************************************
+/**
+ @file
+
This file contains the implementation of prepared statements.
When one prepares a statement:
@@ -28,23 +30,33 @@ When one prepares a statement:
- Without executing the query, return back to client the total
number of parameters along with result-set metadata information
(if any) in the following format:
+ @verbatim
[STMT_ID:4]
[Column_count:2]
[Param_count:2]
[Params meta info (stubs only for now)] (if Param_count > 0)
[Columns meta info] (if Column_count > 0)
+ @endverbatim
+
+ During prepare the tables used in a statement are opened, but no
+ locks are acquired. Table opening will block any DDL during the
+ operation, and we do not need any locks as we neither read nor
+ modify any data during prepare. Tables are closed after prepare
+ finishes.
When one executes a statement:
- Server gets the command 'COM_STMT_EXECUTE' to execute the
previously prepared query. If there are any parameter markers, then the
client will send the data in the following format:
+ @verbatim
[COM_STMT_EXECUTE:1]
[STMT_ID:4]
[NULL_BITS:(param_count+7)/8)]
[TYPES_SUPPLIED_BY_CLIENT(0/1):1]
[[length]data]
[[length]data] .. [[length]data].
+ @endverbatim
(Note: Except for string/binary types; all other types will not be
supplied with length field)
- If it is a first execute or types of parameters were altered by client,
@@ -53,6 +65,10 @@ When one executes a statement:
- Execute the query without re-parsing and send back the results
to client
+ During execution of prepared statement tables are opened and locked
+ the same way they would for normal (non-prepared) statement
+ execution. Tables are unlocked and closed after the execution.
+
When one supplies long data for a placeholder:
- Server gets the long data in pieces with command type
@@ -65,8 +81,7 @@ When one supplies long data for a placeholder:
server doesn't care; also, the server doesn't notify the client whether
it got the data or not; if there is any error, then it will be returned
at statement execute.
-
-***********************************************************************/
+*/
#include "mysql_priv.h"
#include "sql_select.h" // for JOIN
@@ -81,13 +96,15 @@ When one supplies long data for a placeholder:
#include <mysql_com.h>
#endif
-/* A result class used to send cursor rows using the binary protocol. */
+/**
+ A result class used to send cursor rows using the binary protocol.
+*/
-class Select_fetch_protocol_prep: public select_send
+class Select_fetch_protocol_binary: public select_send
{
- Protocol_prep protocol;
+ Protocol_binary protocol;
public:
- Select_fetch_protocol_prep(THD *thd);
+ Select_fetch_protocol_binary(THD *thd);
virtual bool send_fields(List<Item> &list, uint flags);
virtual bool send_data(List<Item> &items);
virtual bool send_eof();
@@ -102,8 +119,7 @@ public:
/****************************************************************************/
/**
- @class Prepared_statement
- @brief Prepared_statement: a statement that can contain placeholders
+ Prepared_statement: a statement that can contain placeholders.
*/
class Prepared_statement: public Statement
@@ -115,7 +131,7 @@ public:
};
THD *thd;
- Select_fetch_protocol_prep result;
+ Select_fetch_protocol_binary result;
Protocol *protocol;
Item_param **param_array;
uint param_count;
@@ -139,21 +155,30 @@ public:
virtual void cleanup_stmt();
bool set_name(LEX_STRING *name);
inline void close_cursor() { delete cursor; cursor= 0; }
-
+ inline bool is_in_use() { return flags & (uint) IS_IN_USE; }
+ inline bool is_protocol_text() const { return protocol == &thd->protocol_text; }
bool prepare(const char *packet, uint packet_length);
- bool execute(String *expanded_query, bool open_cursor);
+ bool execute_loop(String *expanded_query,
+ bool open_cursor,
+ uchar *packet_arg, uchar *packet_end_arg);
/* Destroy this statement */
- bool deallocate();
+ void deallocate();
private:
/**
- Store the parsed tree of a prepared statement here.
- */
- LEX main_lex;
- /**
The memory root to allocate parsed tree elements (instances of Item,
SELECT_LEX and other classes).
*/
MEM_ROOT main_mem_root;
+ /* Version of the stored functions cache at the time of prepare. */
+ ulong m_sp_cache_version;
+private:
+ bool set_db(const char *db, uint db_length);
+ bool set_parameters(String *expanded_query,
+ uchar *packet, uchar *packet_end);
+ bool execute(String *expanded_query, bool open_cursor);
+ bool reprepare();
+ bool validate_metadata(Prepared_statement *copy);
+ void swap_prepared_statement(Prepared_statement *copy);
};
@@ -167,25 +192,22 @@ inline bool is_param_null(const uchar *pos, ulong param_no)
return pos[param_no/8] & (1 << (param_no & 7));
}
-/*
+/**
Find a prepared statement in the statement map by id.
- SYNOPSIS
- find_prepared_statement()
- thd thread handle
- id statement id
- where the place from which this function is called (for
- error reporting).
-
- DESCRIPTION
Try to find a prepared statement and set THD error if it's not found.
- RETURN VALUE
+ @param thd thread handle
+ @param id statement id
+ @param where the place from which this function is called (for
+ error reporting).
+
+ @return
0 if the statement was not found, a pointer otherwise.
*/
static Prepared_statement *
-find_prepared_statement(THD *thd, ulong id, const char *where)
+find_prepared_statement(THD *thd, ulong id)
{
/*
To strictly separate namespaces of SQL prepared statements and C API
@@ -195,23 +217,19 @@ find_prepared_statement(THD *thd, ulong id, const char *where)
Statement *stmt= thd->stmt_map.find(id);
if (stmt == 0 || stmt->type() != Query_arena::PREPARED_STATEMENT)
- {
- char llbuf[22];
- my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf), llstr(id, llbuf),
- where);
- return 0;
- }
+ return NULL;
+
return (Prepared_statement *) stmt;
}
-/*
+/**
Send prepared statement id and metadata to the client after prepare.
- SYNOPSIS
- send_prep_stmt()
+ @todo
+ Fix this nasty upcast from List<Item_param> to List<Item>
- RETURN VALUE
+ @return
0 in case of success, 1 otherwise
*/
@@ -219,8 +237,10 @@ find_prepared_statement(THD *thd, ulong id, const char *where)
static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
{
NET *net= &stmt->thd->net;
- char buff[12];
+ uchar buff[12];
uint tmp;
+ int error;
+ THD *thd= stmt->thd;
DBUG_ENTER("send_prep_stmt");
buff[0]= 0; /* OK packet indicator */
@@ -235,11 +255,16 @@ static bool send_prep_stmt(Prepared_statement *stmt, uint columns)
Send types and names of placeholders to the client
XXX: fix this nasty upcast from List<Item_param> to List<Item>
*/
- DBUG_RETURN(my_net_write(net, buff, sizeof(buff)) ||
- (stmt->param_count &&
- stmt->thd->protocol_simple.send_fields((List<Item> *)
- &stmt->lex->param_list,
- Protocol::SEND_EOF)));
+ error= my_net_write(net, buff, sizeof(buff));
+ if (stmt->param_count && ! error)
+ {
+ error= thd->protocol_text.send_fields((List<Item> *)
+ &stmt->lex->param_list,
+ Protocol::SEND_EOF);
+ }
+ /* Flag that a response has already been sent */
+ thd->main_da.disable_status();
+ DBUG_RETURN(error);
}
#else
static bool send_prep_stmt(Prepared_statement *stmt,
@@ -250,30 +275,29 @@ static bool send_prep_stmt(Prepared_statement *stmt,
thd->client_stmt_id= stmt->id;
thd->client_param_count= stmt->param_count;
thd->clear_error();
+ thd->main_da.disable_status();
return 0;
}
#endif /*!EMBEDDED_LIBRARY*/
-/*
+#ifndef EMBEDDED_LIBRARY
+
+/**
Read the length of the parameter data and return it back to
the caller.
- SYNOPSIS
- get_param_length()
- packet a pointer to the data
- len remaining packet length
-
- DESCRIPTION
Read data length, position the packet to the first byte after it,
and return the length to the caller.
- RETURN VALUE
+ @param packet a pointer to the data
+ @param len remaining packet length
+
+ @return
Length of data piece.
*/
-#ifndef EMBEDDED_LIBRARY
static ulong get_param_length(uchar **packet, ulong len)
{
reg1 uchar *pos= *packet;
@@ -314,16 +338,9 @@ static ulong get_param_length(uchar **packet, ulong len)
#define get_param_length(packet, len) len
#endif /*!EMBEDDED_LIBRARY*/
- /*
- Data conversion routines.
-
- SYNOPSIS
- set_param_xx()
- param parameter item
- pos input data buffer
- len length of data in the buffer
+/**
+ Data conversion routines.
- DESCRIPTION
All these functions read the data from pos, convert it to requested
type and assign to param; pos is advanced to predefined length.
@@ -331,8 +348,9 @@ static ulong get_param_length(uchar **packet, ulong len)
(i.e. when input types altered) and for all subsequent executions
we don't read any values for this.
- RETURN VALUE
- none
+ @param param parameter item
+ @param pos input data buffer
+ @param len length of data in the buffer
*/
static void set_param_tiny(Item_param *param, uchar **pos, ulong len)
@@ -434,6 +452,10 @@ static void set_param_decimal(Item_param *param, uchar **pos, ulong len)
libmysql.c (store_param_{time,date,datetime}).
*/
+/**
+ @todo
+ Add warning 'Data truncated' here
+*/
static void set_param_time(Item_param *param, uchar **pos, ulong len)
{
MYSQL_TIME tm;
@@ -523,6 +545,10 @@ static void set_param_date(Item_param *param, uchar **pos, ulong len)
}
#else/*!EMBEDDED_LIBRARY*/
+/**
+ @todo
+ Add warning 'Data truncated' here
+*/
void set_param_time(Item_param *param, uchar **pos, ulong len)
{
MYSQL_TIME tm= *((MYSQL_TIME*)*pos);
@@ -635,6 +661,7 @@ static void setup_one_conversion_function(THD *thd, Item_param *param,
param->value.cs_info.character_set_of_placeholder= &my_charset_bin;
param->value.cs_info.character_set_client=
thd->variables.character_set_client;
+ DBUG_ASSERT(thd->variables.character_set_client);
param->value.cs_info.final_character_set_of_str_value= &my_charset_bin;
param->item_type= Item::STRING_ITEM;
param->item_result_type= STRING_RESULT;
@@ -674,41 +701,47 @@ static void setup_one_conversion_function(THD *thd, Item_param *param,
}
#ifndef EMBEDDED_LIBRARY
-/*
+/**
Routines to assign parameters from data supplied by the client.
- DESCRIPTION
Update the parameter markers by reading data from the packet and
and generate a valid query for logging.
- NOTES
- This function, along with other _withlog functions is called when one of
+ @note
+ This function, along with other _with_log functions is called when one of
binary, slow or general logs is open. Logging of prepared statements in
all cases is performed by means of conventional queries: if parameter
data was supplied from C API, each placeholder in the query is
replaced with its actual value; if we're logging a [Dynamic] SQL
prepared statement, parameter markers are replaced with variable names.
Example:
+ @verbatim
mysql_stmt_prepare("UPDATE t1 SET a=a*1.25 WHERE a=?")
--> general logs gets [Prepare] UPDATE t1 SET a*1.25 WHERE a=?"
mysql_stmt_execute(stmt);
--> general and binary logs get
[Execute] UPDATE t1 SET a*1.25 WHERE a=1"
- If a statement has been prepared using SQL syntax:
+ @endverbatim
+
+ If a statement has been prepared using SQL syntax:
+ @verbatim
PREPARE stmt FROM "UPDATE t1 SET a=a*1.25 WHERE a=?"
--> general log gets
[Query] PREPARE stmt FROM "UPDATE ..."
EXECUTE stmt USING @a
--> general log gets
- [Query] EXECUTE stmt USING @a;
+ [Query] EXECUTE stmt USING @a;
+ @endverbatim
- RETURN VALUE
- 0 if success, 1 otherwise
+ @retval
+ 0 if success
+ @retval
+ 1 otherwise
*/
-static bool insert_params_withlog(Prepared_statement *stmt, uchar *null_array,
- uchar *read_pos, uchar *data_end,
- String *query)
+static bool insert_params_with_log(Prepared_statement *stmt, uchar *null_array,
+ uchar *read_pos, uchar *data_end,
+ String *query)
{
THD *thd= stmt->thd;
Item_param **begin= stmt->param_array;
@@ -716,7 +749,7 @@ static bool insert_params_withlog(Prepared_statement *stmt, uchar *null_array,
uint32 length= 0;
String str;
const String *res;
- DBUG_ENTER("insert_params_withlog");
+ DBUG_ENTER("insert_params_with_log");
if (query->copy(stmt->query, stmt->query_length, default_charset_info))
DBUG_RETURN(1);
@@ -819,12 +852,12 @@ static bool setup_conversion_functions(Prepared_statement *stmt,
#else
-/*
+/**
Embedded counterparts of parameter assignment routines.
- DESCRIPTION
The main difference between the embedded library and the server is
that in embedded case we don't serialize/deserialize parameters data.
+
Additionally, for unknown reason, the client-side flag raised for
changed types of placeholders is ignored and we simply setup conversion
functions at each execute (TODO: fix).
@@ -866,7 +899,8 @@ static bool emb_insert_params(Prepared_statement *stmt, String *expanded_query)
}
-static bool emb_insert_params_withlog(Prepared_statement *stmt, String *query)
+static bool emb_insert_params_with_log(Prepared_statement *stmt,
+ String *query)
{
THD *thd= stmt->thd;
Item_param **it= stmt->param_array;
@@ -877,7 +911,7 @@ static bool emb_insert_params_withlog(Prepared_statement *stmt, String *query)
const String *res;
uint32 length= 0;
- DBUG_ENTER("emb_insert_params_withlog");
+ DBUG_ENTER("emb_insert_params_with_log");
if (query->copy(stmt->query, stmt->query_length, default_charset_info))
DBUG_RETURN(1);
@@ -916,16 +950,64 @@ static bool emb_insert_params_withlog(Prepared_statement *stmt, String *query)
#endif /*!EMBEDDED_LIBRARY*/
+/**
+ Setup data conversion routines using an array of parameter
+ markers from the original prepared statement.
+ Swap the parameter data of the original prepared
+ statement to the new one.
+
+ Used only when we re-prepare a prepared statement.
+ There are two reasons for this function to exist:
+
+ 1) In the binary client/server protocol, parameter metadata
+ is sent only at first execute. Consequently, if we need to
+ reprepare a prepared statement at a subsequent execution,
+ we may not have metadata information in the packet.
+ In that case we use the parameter array of the original
+ prepared statement to setup parameter types of the new
+ prepared statement.
+
+ 2) In the binary client/server protocol, we may supply
+ long data in pieces. When the last piece is supplied,
+ we assemble the pieces and convert them from client
+ character set to the connection character set. After
+ that the parameter value is only available inside
+ the parameter, the original pieces are lost, and thus
+ we can only assign the corresponding parameter of the
+ reprepared statement from the original value.
+
+ @param[out] param_array_dst parameter markers of the new statement
+ @param[in] param_array_src parameter markers of the original
+ statement
+ @param[in] param_count total number of parameters. Is the
+ same in src and dst arrays, since
+ the statement query is the same
+
+ @return this function never fails
+*/
-/*
+static void
+swap_parameter_array(Item_param **param_array_dst,
+ Item_param **param_array_src,
+ uint param_count)
+{
+ Item_param **dst= param_array_dst;
+ Item_param **src= param_array_src;
+ Item_param **end= param_array_dst + param_count;
+
+ for (; dst < end; ++src, ++dst)
+ (*dst)->set_param_type_and_swap_value(*src);
+}
+
+
+/**
Assign prepared statement parameters from user variables.
- SYNOPSIS
- insert_params_from_vars()
- stmt Statement
- varnames List of variables. Caller must ensure that number of variables
- in the list is equal to number of statement parameters
- query Ignored
+ @param stmt Statement
+ @param varnames List of variables. Caller must ensure that number
+ of variables in the list is equal to number of statement
+ parameters
+ @param query Ignored
*/
static bool insert_params_from_vars(Prepared_statement *stmt,
@@ -944,7 +1026,7 @@ static bool insert_params_from_vars(Prepared_statement *stmt,
Item_param *param= *it;
varname= var_it++;
entry= (user_var_entry*)hash_search(&stmt->thd->user_vars,
- (byte*) varname->str,
+ (uchar*) varname->str,
varname->length);
if (param->set_from_user_var(stmt->thd, entry) ||
param->convert_str_value(stmt->thd))
@@ -954,17 +1036,16 @@ static bool insert_params_from_vars(Prepared_statement *stmt,
}
-/*
+/**
Do the same as insert_params_from_vars but also construct query text for
binary log.
- SYNOPSIS
- insert_params_from_vars()
- stmt Prepared statement
- varnames List of variables. Caller must ensure that number of variables
- in the list is equal to number of statement parameters
- query The query with parameter markers replaced with corresponding
- user variables that were used to execute the query.
+ @param stmt Prepared statement
+ @param varnames List of variables. Caller must ensure that number of
+ variables in the list is equal to number of statement
+ parameters
+ @param query The query with parameter markers replaced with corresponding
+ user variables that were used to execute the query.
*/
static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
@@ -991,7 +1072,7 @@ static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
Item_param *param= *it;
varname= var_it++;
- entry= (user_var_entry *) hash_search(&thd->user_vars, (byte*) varname->str,
+ entry= (user_var_entry *) hash_search(&thd->user_vars, (uchar*) varname->str,
varname->length);
/*
We have to call the setup_one_conversion_function() here to set
@@ -1013,17 +1094,16 @@ static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
DBUG_RETURN(0);
}
-/*
+/**
Validate INSERT statement.
- SYNOPSIS
- mysql_test_insert()
- stmt prepared statement
- tables global/local table list
+ @param stmt prepared statement
+ @param tables global/local table list
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_insert(Prepared_statement *stmt,
@@ -1062,7 +1142,7 @@ static bool mysql_test_insert(Prepared_statement *stmt,
if (table_list->table)
{
// don't allocate insert_values
- table_list->table->insert_values=(byte *)1;
+ table_list->table->insert_values=(uchar *)1;
}
if (mysql_prepare_insert(thd, table_list, table_list->table,
@@ -1074,11 +1154,11 @@ static bool mysql_test_insert(Prepared_statement *stmt,
its.rewind();
if (table_list->lock_type == TL_WRITE_DELAYED &&
- !(table_list->table->file->table_flags() & HA_CAN_INSERT_DELAYED))
+ !(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
{
- my_error(ER_ILLEGAL_HA, MYF(0), (table_list->view ?
- table_list->view_name.str :
- table_list->table_name));
+ my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), (table_list->view ?
+ table_list->view_name.str :
+ table_list->table_name));
goto error;
}
while ((values= its++))
@@ -1089,7 +1169,7 @@ static bool mysql_test_insert(Prepared_statement *stmt,
my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), counter);
goto error;
}
- if (setup_fields(thd, 0, *values, 0, 0, 0))
+ if (setup_fields(thd, 0, *values, MARK_COLUMNS_NONE, 0, 0))
goto error;
}
}
@@ -1101,18 +1181,21 @@ error:
}
-/*
- Validate UPDATE statement
+/**
+ Validate UPDATE statement.
+
+ @param stmt prepared statement
+ @param tables list of tables used in this query
- SYNOPSIS
- mysql_test_update()
- stmt prepared statement
- tables list of tables used in this query
+ @todo
+ - here we should send types of placeholders to the client.
- RETURN VALUE
- 0 success
- 1 error, error message is set in THD
- 2 convert to multi_update
+ @retval
+ 0 success
+ @retval
+ 1 error, error message is set in THD
+ @retval
+ 2 convert to multi_update
*/
static int mysql_test_update(Prepared_statement *stmt,
@@ -1125,32 +1208,20 @@ static int mysql_test_update(Prepared_statement *stmt,
#ifndef NO_EMBEDDED_ACCESS_CHECKS
uint want_privilege;
#endif
- bool need_reopen;
DBUG_ENTER("mysql_test_update");
- if (update_precheck(thd, table_list))
+ if (update_precheck(thd, table_list) ||
+ open_tables(thd, &table_list, &table_count, 0))
goto error;
- for ( ; ; )
+ if (table_list->multitable_view)
{
- if (open_tables(thd, &table_list, &table_count, 0))
- goto error;
-
- if (table_list->multitable_view)
- {
- DBUG_ASSERT(table_list->view != 0);
- DBUG_PRINT("info", ("Switch to multi-update"));
- /* pass counter value */
- thd->lex->table_count= table_count;
- /* convert to multiupdate */
- DBUG_RETURN(2);
- }
-
- if (!lock_tables(thd, table_list, table_count, &need_reopen))
- break;
- if (!need_reopen)
- goto error;
- close_tables_for_reopen(thd, &table_list);
+ DBUG_ASSERT(table_list->view != 0);
+ DBUG_PRINT("info", ("Switch to multi-update"));
+ /* pass counter value */
+ thd->lex->table_count= table_count;
+ /* convert to multiupdate */
+ DBUG_RETURN(2);
}
/*
@@ -1177,7 +1248,7 @@ static int mysql_test_update(Prepared_statement *stmt,
table_list->register_want_access(want_privilege);
#endif
thd->lex->select_lex.no_wrap_view_item= TRUE;
- res= setup_fields(thd, 0, select->item_list, 1, 0, 0);
+ res= setup_fields(thd, 0, select->item_list, MARK_COLUMNS_READ, 0, 0);
thd->lex->select_lex.no_wrap_view_item= FALSE;
if (res)
goto error;
@@ -1188,7 +1259,7 @@ static int mysql_test_update(Prepared_statement *stmt,
(SELECT_ACL & ~table_list->table->grant.privilege);
table_list->register_want_access(SELECT_ACL);
#endif
- if (setup_fields(thd, 0, stmt->lex->value_list, 0, 0, 0))
+ if (setup_fields(thd, 0, stmt->lex->value_list, MARK_COLUMNS_NONE, 0, 0))
goto error;
/* TODO: here we should send types of placeholders to the client. */
DBUG_RETURN(0);
@@ -1197,17 +1268,16 @@ error:
}
-/*
+/**
Validate DELETE statement.
- SYNOPSIS
- mysql_test_delete()
- stmt prepared statement
- tables list of tables used in this query
+ @param stmt prepared statement
+ @param tables list of tables used in this query
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_delete(Prepared_statement *stmt,
@@ -1218,7 +1288,7 @@ static bool mysql_test_delete(Prepared_statement *stmt,
DBUG_ENTER("mysql_test_delete");
if (delete_precheck(thd, table_list) ||
- open_and_lock_tables(thd, table_list))
+ open_normal_and_derived_tables(thd, table_list, 0))
goto error;
if (!table_list->table)
@@ -1234,26 +1304,25 @@ error:
}
-/*
+/**
Validate SELECT statement.
- SYNOPSIS
- mysql_test_select()
- stmt prepared statement
- tables list of tables used in the query
-
- DESCRIPTION
In case of success, if this query is not EXPLAIN, send column list info
back to the client.
- RETURN VALUE
- 0 success
- 1 error, error message is set in THD
- 2 success, and statement metadata has been sent
+ @param stmt prepared statement
+ @param tables list of tables used in the query
+
+ @retval
+ 0 success
+ @retval
+ 1 error, error message is set in THD
+ @retval
+ 2 success, and statement metadata has been sent
*/
static int mysql_test_select(Prepared_statement *stmt,
- TABLE_LIST *tables, bool text_protocol)
+ TABLE_LIST *tables)
{
THD *thd= stmt->thd;
LEX *lex= stmt->lex;
@@ -1265,7 +1334,7 @@ static int mysql_test_select(Prepared_statement *stmt,
ulong privilege= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL;
if (tables)
{
- if (check_table_access(thd, privilege, tables,0))
+ if (check_table_access(thd, privilege, tables, UINT_MAX, FALSE))
goto error;
}
else if (check_access(thd, privilege, any_db,0,0,0,0))
@@ -1277,7 +1346,7 @@ static int mysql_test_select(Prepared_statement *stmt,
goto error;
}
- if (open_and_lock_tables(thd, tables))
+ if (open_normal_and_derived_tables(thd, tables, 0))
goto error;
thd->used_tables= 0; // Updated by setup_fields
@@ -1289,7 +1358,7 @@ static int mysql_test_select(Prepared_statement *stmt,
*/
if (unit->prepare(thd, 0, 0))
goto error;
- if (!lex->describe && !text_protocol)
+ if (!lex->describe && !stmt->is_protocol_text())
{
/* Make copy of item list, as change_columns may change it */
List<Item> fields(lex->select_lex.item_list);
@@ -1314,18 +1383,17 @@ error:
}
-/*
+/**
Validate and prepare for execution DO statement expressions.
- SYNOPSIS
- mysql_test_do_fields()
- stmt prepared statement
- tables list of tables used in this query
- values list of expressions
+ @param stmt prepared statement
+ @param tables list of tables used in this query
+ @param values list of expressions
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_do_fields(Prepared_statement *stmt,
@@ -1335,27 +1403,26 @@ static bool mysql_test_do_fields(Prepared_statement *stmt,
THD *thd= stmt->thd;
DBUG_ENTER("mysql_test_do_fields");
- if (tables && check_table_access(thd, SELECT_ACL, tables, 0))
+ if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE))
DBUG_RETURN(TRUE);
- if (open_and_lock_tables(thd, tables))
+ if (open_normal_and_derived_tables(thd, tables, 0))
DBUG_RETURN(TRUE);
- DBUG_RETURN(setup_fields(thd, 0, *values, 0, 0, 0));
+ DBUG_RETURN(setup_fields(thd, 0, *values, MARK_COLUMNS_NONE, 0, 0));
}
-/*
- Validate and prepare for execution SET statement expressions
+/**
+ Validate and prepare for execution SET statement expressions.
- SYNOPSIS
- mysql_test_set_fields()
- stmt prepared statement
- tables list of tables used in this query
- values list of expressions
+ @param stmt prepared statement
+ @param tables list of tables used in this query
+ @param values list of expressions
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_set_fields(Prepared_statement *stmt,
@@ -1367,8 +1434,8 @@ static bool mysql_test_set_fields(Prepared_statement *stmt,
THD *thd= stmt->thd;
set_var_base *var;
- if (tables && check_table_access(thd, SELECT_ACL, tables, 0) ||
- open_and_lock_tables(thd, tables))
+ if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE) ||
+ open_normal_and_derived_tables(thd, tables, 0))
goto error;
while ((var= it++))
@@ -1382,23 +1449,59 @@ error:
}
-/*
- Check internal SELECT of the prepared command
+/**
+ Validate and prepare for execution CALL statement expressions.
+
+ @param stmt prepared statement
+ @param tables list of tables used in this query
+ @param value_list list of expressions
+
+ @retval FALSE success
+ @retval TRUE error, error message is set in THD
+*/
+
+static bool mysql_test_call_fields(Prepared_statement *stmt,
+ TABLE_LIST *tables,
+ List<Item> *value_list)
+{
+ DBUG_ENTER("mysql_test_call_fields");
+
+ List_iterator<Item> it(*value_list);
+ THD *thd= stmt->thd;
+ Item *item;
+
+ if (tables && check_table_access(thd, SELECT_ACL, tables, UINT_MAX, FALSE) ||
+ open_normal_and_derived_tables(thd, tables, 0))
+ goto err;
+
+ while ((item= it++))
+ {
+ if (!item->fixed && item->fix_fields(thd, it.ref()) ||
+ item->check_cols(1))
+ goto err;
+ }
+ DBUG_RETURN(FALSE);
+err:
+ DBUG_RETURN(TRUE);
+}
+
+
+/**
+ Check internal SELECT of the prepared command.
- SYNOPSIS
- select_like_stmt_test()
- stmt prepared statement
- specific_prepare function of command specific prepare
- setup_tables_done_option options to be passed to LEX::unit.prepare()
+ @param stmt prepared statement
+ @param specific_prepare function of command specific prepare
+ @param setup_tables_done_option options to be passed to LEX::unit.prepare()
- NOTE
+ @note
This function won't directly open tables used in select. They should
be opened either by calling function (and in this case you probably
- should use select_like_stmt_test_with_open_n_lock()) or by
+ should use select_like_stmt_test_with_open()) or by
"specific_prepare" call (like this happens in case of multi-update).
- RETURN VALUE
+ @retval
FALSE success
+ @retval
TRUE error, error message is set in THD
*/
@@ -1421,37 +1524,37 @@ static bool select_like_stmt_test(Prepared_statement *stmt,
DBUG_RETURN(lex->unit.prepare(thd, 0, setup_tables_done_option));
}
-/*
- Check internal SELECT of the prepared command (with opening and
- locking of used tables).
-
- SYNOPSIS
- select_like_stmt_test_with_open_n_lock()
- stmt prepared statement
- tables list of tables to be opened and locked
- before calling specific_prepare function
- specific_prepare function of command specific prepare
- setup_tables_done_option options to be passed to LEX::unit.prepare()
-
- RETURN VALUE
+/**
+ Check internal SELECT of the prepared command (with opening of used
+ tables).
+
+ @param stmt prepared statement
+ @param tables list of tables to be opened
+ before calling specific_prepare function
+ @param specific_prepare function of command specific prepare
+ @param setup_tables_done_option options to be passed to LEX::unit.prepare()
+
+ @retval
FALSE success
+ @retval
TRUE error
*/
static bool
-select_like_stmt_test_with_open_n_lock(Prepared_statement *stmt,
- TABLE_LIST *tables,
- int (*specific_prepare)(THD *thd),
- ulong setup_tables_done_option)
+select_like_stmt_test_with_open(Prepared_statement *stmt,
+ TABLE_LIST *tables,
+ int (*specific_prepare)(THD *thd),
+ ulong setup_tables_done_option)
{
- DBUG_ENTER("select_like_stmt_test_with_open_n_lock");
+ DBUG_ENTER("select_like_stmt_test_with_open");
/*
- We should not call LEX::unit.cleanup() after this open_and_lock_tables()
- call because we don't allow prepared EXPLAIN yet so derived tables will
- clean up after themself.
+ We should not call LEX::unit.cleanup() after this
+ open_normal_and_derived_tables() call because we don't allow
+ prepared EXPLAIN yet so derived tables will clean up after
+ themself.
*/
- if (open_and_lock_tables(stmt->thd, tables))
+ if (open_normal_and_derived_tables(stmt->thd, tables, 0))
DBUG_RETURN(TRUE);
DBUG_RETURN(select_like_stmt_test(stmt, specific_prepare,
@@ -1459,17 +1562,16 @@ select_like_stmt_test_with_open_n_lock(Prepared_statement *stmt,
}
-/*
- Validate and prepare for execution CREATE TABLE statement
+/**
+ Validate and prepare for execution CREATE TABLE statement.
- SYNOPSIS
- mysql_test_create_table()
- stmt prepared statement
- tables list of tables used in this query
+ @param stmt prepared statement
+ @param tables list of tables used in this query
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_create_table(Prepared_statement *stmt)
@@ -1495,7 +1597,7 @@ static bool mysql_test_create_table(Prepared_statement *stmt)
create_table->create= TRUE;
}
- if (open_and_lock_tables(stmt->thd, lex->query_tables))
+ if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0))
DBUG_RETURN(TRUE);
if (!(lex->create_info.options & HA_LEX_CREATE_TMP_TABLE))
@@ -1505,6 +1607,17 @@ static bool mysql_test_create_table(Prepared_statement *stmt)
res= select_like_stmt_test(stmt, 0, 0);
}
+ else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE)
+ {
+ /*
+ Check that the source table exist, and also record
+ its metadata version. Even though not strictly necessary,
+ we validate metadata of all CREATE TABLE statements,
+ which keeps metadata validation code simple.
+ */
+ if (open_normal_and_derived_tables(stmt->thd, lex->query_tables, 0))
+ DBUG_RETURN(TRUE);
+ }
/* put tables back for PS rexecuting */
lex->link_first_table_back(create_table, link_to_local);
@@ -1553,15 +1666,14 @@ err:
/*
Validate and prepare for execution a multi update statement.
- SYNOPSIS
- mysql_test_multiupdate()
- stmt prepared statement
- tables list of tables used in this query
- converted converted to multi-update from usual update
+ @param stmt prepared statement
+ @param tables list of tables used in this query
+ @param converted converted to multi-update from usual update
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_multiupdate(Prepared_statement *stmt,
@@ -1577,17 +1689,16 @@ static bool mysql_test_multiupdate(Prepared_statement *stmt,
}
-/*
+/**
Validate and prepare for execution a multi delete statement.
- SYNOPSIS
- mysql_test_multidelete()
- stmt prepared statement
- tables list of tables used in this query
+ @param stmt prepared statement
+ @param tables list of tables used in this query
- RETURN VALUE
- FALSE success
- TRUE error, error message in THD is set.
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message in THD is set.
*/
static bool mysql_test_multidelete(Prepared_statement *stmt,
@@ -1601,9 +1712,9 @@ static bool mysql_test_multidelete(Prepared_statement *stmt,
}
if (multi_delete_precheck(stmt->thd, tables) ||
- select_like_stmt_test_with_open_n_lock(stmt, tables,
- &mysql_multi_delete_prepare,
- OPTION_SETUP_TABLES_DONE))
+ select_like_stmt_test_with_open(stmt, tables,
+ &mysql_multi_delete_prepare,
+ OPTION_SETUP_TABLES_DONE))
goto error;
if (!tables->table)
{
@@ -1617,17 +1728,16 @@ error:
}
-/*
+/**
Wrapper for mysql_insert_select_prepare, to make change of local tables
- after open_and_lock_tables() call.
+ after open_normal_and_derived_tables() call.
- SYNOPSIS
- mysql_insert_select_prepare_tester()
- thd thread handle
+ @param thd thread handle
- NOTE
- We need to remove the first local table after open_and_lock_tables,
- because mysql_handle_derived uses local tables lists.
+ @note
+ We need to remove the first local table after
+ open_normal_and_derived_tables(), because mysql_handle_derived
+ uses local tables lists.
*/
static int mysql_insert_select_prepare_tester(THD *thd)
@@ -1637,7 +1747,7 @@ static int mysql_insert_select_prepare_tester(THD *thd)
next_local;
/* Skip first table, which is the table we are inserting in */
- first_select->table_list.first= (byte *) second_table;
+ first_select->table_list.first= (uchar *) second_table;
thd->lex->select_lex.context.table_list=
thd->lex->select_lex.context.first_name_resolution_table= second_table;
@@ -1645,17 +1755,16 @@ static int mysql_insert_select_prepare_tester(THD *thd)
}
-/*
+/**
Validate and prepare for execution INSERT ... SELECT statement.
- SYNOPSIS
- mysql_test_insert_select()
- stmt prepared statement
- tables list of tables used in this query
+ @param stmt prepared statement
+ @param tables list of tables used in this query
- RETURN VALUE
- FALSE success
- TRUE error, error message is set in THD
+ @retval
+ FALSE success
+ @retval
+ TRUE error, error message is set in THD
*/
static bool mysql_test_insert_select(Prepared_statement *stmt,
@@ -1668,7 +1777,7 @@ static bool mysql_test_insert_select(Prepared_statement *stmt,
if (tables->table)
{
// don't allocate insert_values
- tables->table->insert_values=(byte *)1;
+ tables->table->insert_values=(uchar *)1;
}
if (insert_precheck(stmt->thd, tables))
@@ -1679,36 +1788,33 @@ static bool mysql_test_insert_select(Prepared_statement *stmt,
DBUG_ASSERT(first_local_table != 0);
res=
- select_like_stmt_test_with_open_n_lock(stmt, tables,
- &mysql_insert_select_prepare_tester,
- OPTION_SETUP_TABLES_DONE);
+ select_like_stmt_test_with_open(stmt, tables,
+ &mysql_insert_select_prepare_tester,
+ OPTION_SETUP_TABLES_DONE);
/* revert changes made by mysql_insert_select_prepare_tester */
- lex->select_lex.table_list.first= (byte*) first_local_table;
+ lex->select_lex.table_list.first= (uchar*) first_local_table;
return res;
}
-/*
+/**
Perform semantic analysis of the parsed tree and send a response packet
to the client.
- SYNOPSIS
- check_prepared_statement()
- stmt prepared statement
-
- DESCRIPTION
This function
- opens all tables and checks access rights
- validates semantics of statement columns and SQL functions
by calling fix_fields.
- RETURN VALUE
- FALSE success, statement metadata is sent to client
- TRUE error, error message is set in THD (but not sent)
+ @param stmt prepared statement
+
+ @retval
+ FALSE success, statement metadata is sent to client
+ @retval
+ TRUE error, error message is set in THD (but not sent)
*/
-static bool check_prepared_statement(Prepared_statement *stmt,
- bool text_protocol)
+static bool check_prepared_statement(Prepared_statement *stmt)
{
THD *thd= stmt->thd;
LEX *lex= stmt->lex;
@@ -1749,9 +1855,23 @@ static bool check_prepared_statement(Prepared_statement *stmt,
case SQLCOM_DELETE:
res= mysql_test_delete(stmt, tables);
break;
-
+ /* The following allow WHERE clause, so they must be tested like SELECT */
+ case SQLCOM_SHOW_DATABASES:
+ case SQLCOM_SHOW_TABLES:
+ case SQLCOM_SHOW_TRIGGERS:
+ case SQLCOM_SHOW_EVENTS:
+ case SQLCOM_SHOW_OPEN_TABLES:
+ case SQLCOM_SHOW_FIELDS:
+ case SQLCOM_SHOW_KEYS:
+ case SQLCOM_SHOW_COLLATIONS:
+ case SQLCOM_SHOW_CHARSETS:
+ case SQLCOM_SHOW_VARIABLES:
+ case SQLCOM_SHOW_STATUS:
+ case SQLCOM_SHOW_TABLE_STATUS:
+ case SQLCOM_SHOW_STATUS_PROC:
+ case SQLCOM_SHOW_STATUS_FUNC:
case SQLCOM_SELECT:
- res= mysql_test_select(stmt, tables, text_protocol);
+ res= mysql_test_select(stmt, tables);
if (res == 2)
{
/* Statement and field info has already been sent */
@@ -1774,6 +1894,9 @@ static bool check_prepared_statement(Prepared_statement *stmt,
res= mysql_test_do_fields(stmt, tables, lex->insert_list);
break;
+ case SQLCOM_CALL:
+ res= mysql_test_call_fields(stmt, tables, &lex->value_list);
+ break;
case SQLCOM_SET_OPTION:
res= mysql_test_set_fields(stmt, tables, &lex->var_list);
break;
@@ -1787,22 +1910,34 @@ static bool check_prepared_statement(Prepared_statement *stmt,
res= mysql_test_insert_select(stmt, tables);
break;
- case SQLCOM_SHOW_DATABASES:
+ /*
+ Note that we don't need to have cases in this list if they are
+ marked with CF_STATUS_COMMAND in sql_command_flags
+ */
case SQLCOM_SHOW_PROCESSLIST:
case SQLCOM_SHOW_STORAGE_ENGINES:
case SQLCOM_SHOW_PRIVILEGES:
case SQLCOM_SHOW_COLUMN_TYPES:
- case SQLCOM_SHOW_STATUS:
- case SQLCOM_SHOW_VARIABLES:
- case SQLCOM_SHOW_LOGS:
- case SQLCOM_SHOW_TABLES:
- case SQLCOM_SHOW_OPEN_TABLES:
- case SQLCOM_SHOW_CHARSETS:
- case SQLCOM_SHOW_COLLATIONS:
- case SQLCOM_SHOW_FIELDS:
- case SQLCOM_SHOW_KEYS:
+ case SQLCOM_SHOW_ENGINE_LOGS:
+ case SQLCOM_SHOW_ENGINE_STATUS:
+ case SQLCOM_SHOW_ENGINE_MUTEX:
case SQLCOM_SHOW_CREATE_DB:
case SQLCOM_SHOW_GRANTS:
+ case SQLCOM_SHOW_BINLOG_EVENTS:
+ case SQLCOM_SHOW_MASTER_STAT:
+ case SQLCOM_SHOW_SLAVE_STAT:
+ case SQLCOM_SHOW_CREATE_PROC:
+ case SQLCOM_SHOW_CREATE_FUNC:
+ case SQLCOM_SHOW_CREATE_EVENT:
+ case SQLCOM_SHOW_CREATE_TRIGGER:
+ case SQLCOM_SHOW_CREATE:
+ case SQLCOM_SHOW_PROC_CODE:
+ case SQLCOM_SHOW_FUNC_CODE:
+ case SQLCOM_SHOW_AUTHORS:
+ case SQLCOM_SHOW_CONTRIBUTORS:
+ case SQLCOM_SHOW_WARNS:
+ case SQLCOM_SHOW_ERRORS:
+ case SQLCOM_SHOW_BINLOGS:
case SQLCOM_DROP_TABLE:
case SQLCOM_RENAME_TABLE:
case SQLCOM_ALTER_TABLE:
@@ -1811,29 +1946,55 @@ static bool check_prepared_statement(Prepared_statement *stmt,
case SQLCOM_DROP_INDEX:
case SQLCOM_ROLLBACK:
case SQLCOM_TRUNCATE:
- case SQLCOM_CALL:
case SQLCOM_DROP_VIEW:
case SQLCOM_REPAIR:
case SQLCOM_ANALYZE:
case SQLCOM_OPTIMIZE:
+ case SQLCOM_CHANGE_MASTER:
+ case SQLCOM_RESET:
+ case SQLCOM_FLUSH:
+ case SQLCOM_SLAVE_START:
+ case SQLCOM_SLAVE_STOP:
+ case SQLCOM_INSTALL_PLUGIN:
+ case SQLCOM_UNINSTALL_PLUGIN:
+ case SQLCOM_CREATE_DB:
+ case SQLCOM_DROP_DB:
+ case SQLCOM_ALTER_DB_UPGRADE:
+ case SQLCOM_CHECKSUM:
+ case SQLCOM_CREATE_USER:
+ case SQLCOM_RENAME_USER:
+ case SQLCOM_DROP_USER:
+ case SQLCOM_ASSIGN_TO_KEYCACHE:
+ case SQLCOM_PRELOAD_KEYS:
+ case SQLCOM_GRANT:
+ case SQLCOM_REVOKE:
+ case SQLCOM_KILL:
break;
case SQLCOM_PREPARE:
case SQLCOM_EXECUTE:
case SQLCOM_DEALLOCATE_PREPARE:
default:
- /* All other statements are not supported yet. */
- my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0));
- goto error;
+ /*
+ Trivial check of all status commands. This is easier than having
+ things in the above case list, as it's less chance for mistakes.
+ */
+ if (!(sql_command_flags[sql_command] & CF_STATUS_COMMAND))
+ {
+ /* All other statements are not supported yet. */
+ my_message(ER_UNSUPPORTED_PS, ER(ER_UNSUPPORTED_PS), MYF(0));
+ goto error;
+ }
+ break;
}
if (res == 0)
- DBUG_RETURN(text_protocol? FALSE : (send_prep_stmt(stmt, 0) ||
- thd->protocol->flush()));
+ DBUG_RETURN(stmt->is_protocol_text() ?
+ FALSE : (send_prep_stmt(stmt, 0) || thd->protocol->flush()));
error:
DBUG_RETURN(TRUE);
}
-/*
+/**
Initialize array of parameters in statement from LEX.
(We need to have quick access to items by number in mysql_stmt_get_longdata).
This is to avoid using malloc/realloc in the parser.
@@ -1869,31 +2030,28 @@ static bool init_param_array(Prepared_statement *stmt)
}
-/*
+/**
COM_STMT_PREPARE handler.
- SYNOPSIS
- mysql_stmt_prepare()
- packet query to be prepared
- packet_length query string length, including ignored
- trailing NULL or quote char.
-
- DESCRIPTION
Given a query string with parameter markers, create a prepared
statement from it and send PS info back to the client.
- NOTES
- This function parses the query and sends the total number of parameters
- and resultset metadata information back to client (if any), without
- executing the query i.e. without any log/disk writes. This allows the
- queries to be re-executed without re-parsing during execute.
-
If parameter markers are found in the query, then store the information
using Item_param along with maintaining a list in lex->param_array, so
that a fast and direct retrieval can be made without going through all
field items.
- RETURN VALUE
+ @param packet query to be prepared
+ @param packet_length query string length, including ignored
+ trailing NULL or quote char.
+
+ @note
+ This function parses the query and sends the total number of parameters
+ and resultset metadata information back to client (if any), without
+ executing the query i.e. without any log/disk writes. This allows the
+ queries to be re-executed without re-parsing during execute.
+
+ @return
none: in case of success a new statement id and metadata is sent
to the client, otherwise an error message is set in THD.
*/
@@ -1909,7 +2067,7 @@ void mysql_stmt_prepare(THD *thd, const char *packet, uint packet_length)
/* First of all clear possible warnings from the previous command */
mysql_reset_thd_for_next_command(thd);
- if (! (stmt= new Prepared_statement(thd, &thd->protocol_prep)))
+ if (! (stmt= new Prepared_statement(thd, &thd->protocol_binary)))
DBUG_VOID_RETURN; /* out of memory: error is set in Sql_alloc */
if (thd->stmt_map.insert(thd, stmt))
@@ -1943,22 +2101,22 @@ void mysql_stmt_prepare(THD *thd, const char *packet, uint packet_length)
DBUG_VOID_RETURN;
}
-/*
- SYNOPSIS
- get_dynamic_sql_string()
- lex in main lex
- query_len out length of the SQL statement (is set only
- in case of success)
-
- DESCRIPTION
- Get an SQL statement text from a user variable or from plain
- text. If the statement is plain text, just assign the
- pointers, otherwise allocate memory in thd->mem_root and copy
- the contents of the variable, possibly with character
- set conversion.
-
- RETURN VALUE
- non-zero success, 0 in case of error (out of memory)
+/**
+ Get an SQL statement text from a user variable or from plain text.
+
+ If the statement is plain text, just assign the
+ pointers, otherwise allocate memory in thd->mem_root and copy
+ the contents of the variable, possibly with character
+ set conversion.
+
+ @param[in] lex main lex
+ @param[out] query_len length of the SQL statement (is set only
+ in case of success)
+
+ @retval
+ non-zero success
+ @retval
+ 0 in case of error (out of memory)
*/
static const char *get_dynamic_sql_string(LEX *lex, uint *query_len)
@@ -1982,7 +2140,7 @@ static const char *get_dynamic_sql_string(LEX *lex, uint *query_len)
*/
if ((entry=
(user_var_entry*)hash_search(&thd->user_vars,
- (byte*)lex->prepared_stmt_code.str,
+ (uchar*)lex->prepared_stmt_code.str,
lex->prepared_stmt_code.length))
&& entry->value)
{
@@ -2011,7 +2169,7 @@ static const char *get_dynamic_sql_string(LEX *lex, uint *query_len)
len= (needs_conversion ? var_value->length() * to_cs->mbmaxlen :
var_value->length());
- if (!(query_str= alloc_root(thd->mem_root, len+1)))
+ if (!(query_str= (char*) alloc_root(thd->mem_root, len+1)))
goto end;
if (needs_conversion)
@@ -2036,7 +2194,7 @@ end:
}
-/* Init PS/SP specific parse tree members. */
+/** Init PS/SP specific parse tree members. */
static void init_stmt_after_parse(LEX *lex)
{
@@ -2049,19 +2207,16 @@ static void init_stmt_after_parse(LEX *lex)
sl->uncacheable&= ~UNCACHEABLE_PREPARE;
}
-/*
+/**
SQLCOM_PREPARE implementation.
- SYNOPSIS
- mysql_sql_stmt_prepare()
- thd thread handle
-
- DESCRIPTION
Prepare an SQL prepared statement. This is called from
mysql_execute_command and should therefore behave like an
ordinary query (e.g. should not reset any global THD data).
- RETURN VALUE
+ @param thd thread handle
+
+ @return
none: in case of success, OK packet is sent to the client,
otherwise an error message is set in THD
*/
@@ -2074,8 +2229,8 @@ void mysql_sql_stmt_prepare(THD *thd)
const char *query;
uint query_len;
DBUG_ENTER("mysql_sql_stmt_prepare");
- DBUG_ASSERT(thd->protocol == &thd->protocol_simple);
LINT_INIT(query_len);
+ DBUG_ASSERT(thd->protocol == &thd->protocol_text);
if ((stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
{
@@ -2083,12 +2238,17 @@ void mysql_sql_stmt_prepare(THD *thd)
If there is a statement with the same name, remove it. It is ok to
remove old and fail to insert a new one at the same time.
*/
- if (stmt->deallocate())
+ if (stmt->is_in_use())
+ {
+ my_error(ER_PS_NO_RECURSION, MYF(0));
DBUG_VOID_RETURN;
+ }
+
+ stmt->deallocate();
}
if (! (query= get_dynamic_sql_string(lex, &query_len)) ||
- ! (stmt= new Prepared_statement(thd, &thd->protocol_simple)))
+ ! (stmt= new Prepared_statement(thd, &thd->protocol_text)))
{
DBUG_VOID_RETURN; /* out of memory */
}
@@ -2106,18 +2266,25 @@ void mysql_sql_stmt_prepare(THD *thd)
DBUG_VOID_RETURN;
}
- if (stmt->prepare(query, query_len+1))
+ if (stmt->prepare(query, query_len))
{
/* Statement map deletes the statement on erase */
thd->stmt_map.erase(stmt);
}
else
- send_ok(thd, 0L, 0L, "Statement prepared");
+ my_ok(thd, 0L, 0L, "Statement prepared");
DBUG_VOID_RETURN;
}
-/* Reinit prepared statement/stored procedure before execution */
+/**
+ Reinit prepared statement/stored procedure before execution.
+
+ @todo
+ When the new table structure is ready, then have a status bit
+ to indicate the table is altered, and re-do the setup_*
+ and open the tables back.
+*/
void reinit_stmt_before_use(THD *thd, LEX *lex)
{
@@ -2223,13 +2390,11 @@ void reinit_stmt_before_use(THD *thd, LEX *lex)
}
-/*
- Clears parameters from data left from previous execution or long data
+/**
+ Clears parameters from data left from previous execution or long data.
- SYNOPSIS
- reset_stmt_params()
- stmt prepared statement for which parameters should
- be reset
+ @param stmt prepared statement for which parameters should
+ be reset
*/
static void reset_stmt_params(Prepared_statement *stmt)
@@ -2241,22 +2406,19 @@ static void reset_stmt_params(Prepared_statement *stmt)
}
-/*
+/**
COM_STMT_EXECUTE handler: execute a previously prepared statement.
- SYNOPSIS
- mysql_stmt_execute()
- thd current thread
- packet parameter types and data, if any
- packet_length packet length, including the terminator character.
-
- DESCRIPTION
If there are any parameters, then replace parameter markers with the
data supplied from the client, and then execute the statement.
This function uses binary protocol to send a possible result set
to the client.
- RETURN VALUE
+ @param thd current thread
+ @param packet_arg parameter types and data, if any
+ @param packet_length packet length, including the terminator character.
+
+ @return
none: in case of success OK packet or a result set is sent to the
client, otherwise an error message is set in THD.
*/
@@ -2268,11 +2430,9 @@ void mysql_stmt_execute(THD *thd, char *packet_arg, uint packet_length)
ulong flags= (ulong) packet[4];
/* Query text for binary, general or slow log, if any of them is open */
String expanded_query;
-#ifndef EMBEDDED_LIBRARY
- uchar *packet_end= packet + packet_length - 1;
-#endif
+ uchar *packet_end= packet + packet_length;
Prepared_statement *stmt;
- bool error;
+ bool open_cursor;
DBUG_ENTER("mysql_stmt_execute");
packet+= 9; /* stmt_id + 5 bytes of flags */
@@ -2280,64 +2440,35 @@ void mysql_stmt_execute(THD *thd, char *packet_arg, uint packet_length)
/* First of all clear possible warnings from the previous command */
mysql_reset_thd_for_next_command(thd);
- if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_execute")))
+ if (!(stmt= find_prepared_statement(thd, stmt_id)))
+ {
+ char llbuf[22];
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ llstr(stmt_id, llbuf), "mysql_stmt_execute");
DBUG_VOID_RETURN;
+ }
+#if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
+ thd->profiling.set_query_source(stmt->query, stmt->query_length);
+#endif
DBUG_PRINT("exec_query", ("%s", stmt->query));
- DBUG_PRINT("info",("stmt: %p", stmt));
+ DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
sp_cache_flush_obsolete(&thd->sp_proc_cache);
sp_cache_flush_obsolete(&thd->sp_func_cache);
-#ifndef EMBEDDED_LIBRARY
- if (stmt->param_count)
- {
- uchar *null_array= packet;
- if (setup_conversion_functions(stmt, &packet, packet_end) ||
- stmt->set_params(stmt, null_array, packet, packet_end,
- &expanded_query))
- goto set_params_data_err;
- }
-#else
- /*
- In embedded library we re-install conversion routines each time
- we set params, and also we don't need to parse packet.
- So we do it in one function.
- */
- if (stmt->param_count && stmt->set_params_data(stmt, &expanded_query))
- goto set_params_data_err;
-#endif
- if (!(specialflag & SPECIAL_NO_PRIOR))
- my_pthread_setprio(pthread_self(),QUERY_PRIOR);
+ open_cursor= test(flags & (ulong) CURSOR_TYPE_READ_ONLY);
- /*
- If the free_list is not empty, we'll wrongly free some externally
- allocated items when cleaning up after validation of the prepared
- statement.
- */
- DBUG_ASSERT(thd->free_list == NULL);
+ stmt->execute_loop(&expanded_query, open_cursor, packet, packet_end);
- error= stmt->execute(&expanded_query,
- test(flags & (ulong) CURSOR_TYPE_READ_ONLY));
- if (!(specialflag & SPECIAL_NO_PRIOR))
- my_pthread_setprio(pthread_self(), WAIT_PRIOR);
DBUG_VOID_RETURN;
-set_params_data_err:
- my_error(ER_WRONG_ARGUMENTS, MYF(0), "mysql_stmt_execute");
- reset_stmt_params(stmt);
- DBUG_VOID_RETURN;
}
-/*
+/**
SQLCOM_EXECUTE implementation.
- SYNOPSIS
- mysql_sql_stmt_execute()
- thd thread handle
-
- DESCRIPTION
Execute prepared statement using parameter values from
lex->prepared_stmt_params and send result to the client using
text protocol. This is called from mysql_execute_command and
@@ -2345,7 +2476,9 @@ set_params_data_err:
global THD data, such as warning count, server status, etc).
This function uses text protocol to send a possible result set.
- RETURN
+ @param thd thread handle
+
+ @return
none: in case of success, OK (or result set) packet is sent to the
client, otherwise an error is set in THD
*/
@@ -2358,7 +2491,7 @@ void mysql_sql_stmt_execute(THD *thd)
/* Query text for binary, general or slow log, if any of them is open */
String expanded_query;
DBUG_ENTER("mysql_sql_stmt_execute");
- DBUG_PRINT("info", ("EXECUTE: %.*s\n", name->length, name->str));
+ DBUG_PRINT("info", ("EXECUTE: %.*s\n", (int) name->length, name->str));
if (!(stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
{
@@ -2373,38 +2506,20 @@ void mysql_sql_stmt_execute(THD *thd)
DBUG_VOID_RETURN;
}
- DBUG_PRINT("info",("stmt: %p", stmt));
+ DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
- /*
- If the free_list is not empty, we'll wrongly free some externally
- allocated items when cleaning up after validation of the prepared
- statement.
- */
- DBUG_ASSERT(thd->free_list == NULL);
-
- if (stmt->set_params_from_vars(stmt, lex->prepared_stmt_params,
- &expanded_query))
- goto set_params_data_err;
-
- (void) stmt->execute(&expanded_query, FALSE);
+ (void) stmt->execute_loop(&expanded_query, FALSE, NULL, NULL);
DBUG_VOID_RETURN;
-
-set_params_data_err:
- my_error(ER_WRONG_ARGUMENTS, MYF(0), "EXECUTE");
- reset_stmt_params(stmt);
- DBUG_VOID_RETURN;
}
-/*
- COM_STMT_FETCH handler: fetches requested amount of rows from cursor
+/**
+ COM_STMT_FETCH handler: fetches requested amount of rows from cursor.
- SYNOPSIS
- mysql_stmt_fetch()
- thd Thread handle
- packet Packet from client (with stmt_id & num_rows)
- packet_length Length of packet
+ @param thd Thread handle
+ @param packet Packet from client (with stmt_id & num_rows)
+ @param packet_length Length of packet
*/
void mysql_stmt_fetch(THD *thd, char *packet, uint packet_length)
@@ -2419,9 +2534,14 @@ void mysql_stmt_fetch(THD *thd, char *packet, uint packet_length)
/* First of all clear possible warnings from the previous command */
mysql_reset_thd_for_next_command(thd);
- statistic_increment(thd->status_var.com_stmt_fetch, &LOCK_status);
- if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_fetch")))
+ status_var_increment(thd->status_var.com_stmt_fetch);
+ if (!(stmt= find_prepared_statement(thd, stmt_id)))
+ {
+ char llbuf[22];
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ llstr(stmt_id, llbuf), "mysql_stmt_fetch");
DBUG_VOID_RETURN;
+ }
cursor= stmt->cursor;
if (!cursor)
@@ -2455,22 +2575,20 @@ void mysql_stmt_fetch(THD *thd, char *packet, uint packet_length)
}
-/*
+/**
Reset a prepared statement in case there was a recoverable error.
- SYNOPSIS
- mysql_stmt_reset()
- thd Thread handle
- packet Packet with stmt id
- DESCRIPTION
This function resets statement to the state it was right after prepare.
It can be used to:
- - clear an error happened during mysql_stmt_send_long_data
- - cancel long data stream for all placeholders without
- having to call mysql_stmt_execute.
- - close an open cursor
+ - clear an error happened during mysql_stmt_send_long_data
+ - cancel long data stream for all placeholders without
+ having to call mysql_stmt_execute.
+ - close an open cursor
Sends 'OK' packet in case of success (statement was reset)
or 'ERROR' packet (unrecoverable error/statement not found/etc).
+
+ @param thd Thread handle
+ @param packet Packet with stmt id
*/
void mysql_stmt_reset(THD *thd, char *packet)
@@ -2483,9 +2601,14 @@ void mysql_stmt_reset(THD *thd, char *packet)
/* First of all clear possible warnings from the previous command */
mysql_reset_thd_for_next_command(thd);
- statistic_increment(thd->status_var.com_stmt_reset, &LOCK_status);
- if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_reset")))
+ status_var_increment(thd->status_var.com_stmt_reset);
+ if (!(stmt= find_prepared_statement(thd, stmt_id)))
+ {
+ char llbuf[22];
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ llstr(stmt_id, llbuf), "mysql_stmt_reset");
DBUG_VOID_RETURN;
+ }
stmt->close_cursor();
@@ -2497,15 +2620,19 @@ void mysql_stmt_reset(THD *thd, char *packet)
stmt->state= Query_arena::PREPARED;
- send_ok(thd);
+ general_log_print(thd, thd->command, NullS);
+
+ my_ok(thd);
DBUG_VOID_RETURN;
}
-/*
+/**
Delete a prepared statement from memory.
- Note: we don't send any reply to this command.
+
+ @note
+ we don't send any reply to this command.
*/
void mysql_stmt_close(THD *thd, char *packet)
@@ -2515,32 +2642,31 @@ void mysql_stmt_close(THD *thd, char *packet)
Prepared_statement *stmt;
DBUG_ENTER("mysql_stmt_close");
- if (!(stmt= find_prepared_statement(thd, stmt_id, "mysql_stmt_close")))
- goto out;
+ thd->main_da.disable_status();
+
+ if (!(stmt= find_prepared_statement(thd, stmt_id)))
+ DBUG_VOID_RETURN;
/*
The only way currently a statement can be deallocated when it's
in use is from within Dynamic SQL.
*/
- DBUG_ASSERT(! (stmt->flags & (uint) Prepared_statement::IS_IN_USE));
- (void) stmt->deallocate();
+ DBUG_ASSERT(! stmt->is_in_use());
+ stmt->deallocate();
+ general_log_print(thd, thd->command, NullS);
-out:
- /* clear errors, response packet is not expected */
- thd->clear_error();
DBUG_VOID_RETURN;
}
-/*
+/**
SQLCOM_DEALLOCATE implementation.
- DESCRIPTION
Close an SQL prepared statement. As this can be called from Dynamic
SQL, we should be careful to not close a statement that is currently
being executed.
- RETURN VALUE
+ @return
none: OK packet is sent in case of success, otherwise an error
message is set in THD
*/
@@ -2549,34 +2675,33 @@ void mysql_sql_stmt_close(THD *thd)
{
Prepared_statement* stmt;
LEX_STRING *name= &thd->lex->prepared_stmt_name;
- DBUG_PRINT("info", ("DEALLOCATE PREPARE: %.*s\n", name->length, name->str));
+ DBUG_PRINT("info", ("DEALLOCATE PREPARE: %.*s\n", (int) name->length,
+ name->str));
if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
- {
my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
name->length, name->str, "DEALLOCATE PREPARE");
- return;
+ else if (stmt->is_in_use())
+ my_error(ER_PS_NO_RECURSION, MYF(0));
+ else
+ {
+ stmt->deallocate();
+ my_ok(thd);
}
-
- if (stmt->deallocate() == 0)
- send_ok(thd);
}
-/*
+/**
Handle long data in pieces from client.
- SYNOPSIS
- mysql_stmt_get_longdata()
- thd Thread handle
- packet String to append
- packet_length Length of string (including end \0)
-
- DESCRIPTION
Get a part of a long data. To make the protocol efficient, we are
not sending any return packets here. If something goes wrong, then
we will send the error on 'execute' We assume that the client takes
care of checking that all parts are sent to the server. (No checking
that we get a 'end of column' in the server is performed).
+
+ @param thd Thread handle
+ @param packet String to append
+ @param packet_length Length of string (including end \\0)
*/
void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
@@ -2586,23 +2711,24 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
Prepared_statement *stmt;
Item_param *param;
#ifndef EMBEDDED_LIBRARY
- char *packet_end= packet + packet_length - 1;
+ char *packet_end= packet + packet_length;
#endif
DBUG_ENTER("mysql_stmt_get_longdata");
- statistic_increment(thd->status_var.com_stmt_send_long_data, &LOCK_status);
+ status_var_increment(thd->status_var.com_stmt_send_long_data);
+
+ thd->main_da.disable_status();
#ifndef EMBEDDED_LIBRARY
/* Minimal size of long data packet is 6 bytes */
- if (packet_length <= MYSQL_LONG_DATA_HEADER)
- goto out;
+ if (packet_length < MYSQL_LONG_DATA_HEADER)
+ DBUG_VOID_RETURN;
#endif
stmt_id= uint4korr(packet);
packet+= 4;
- if (!(stmt=find_prepared_statement(thd, stmt_id,
- "mysql_stmt_send_long_data")))
- goto out;
+ if (!(stmt=find_prepared_statement(thd, stmt_id)))
+ DBUG_VOID_RETURN;
param_number= uint2korr(packet);
packet+= 2;
@@ -2614,7 +2740,7 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
stmt->last_errno= ER_WRONG_ARGUMENTS;
sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS),
"mysql_stmt_send_long_data");
- goto out;
+ DBUG_VOID_RETURN;
}
#endif
@@ -2631,22 +2757,21 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
sprintf(stmt->last_error, ER(ER_OUTOFMEMORY), 0);
}
-out:
- /* clear errors, response packet is not expected */
- thd->clear_error();
+ general_log_print(thd, thd->command, NullS);
+
DBUG_VOID_RETURN;
}
/***************************************************************************
- Select_fetch_protocol_prep
+ Select_fetch_protocol_binary
****************************************************************************/
-Select_fetch_protocol_prep::Select_fetch_protocol_prep(THD *thd_arg)
+Select_fetch_protocol_binary::Select_fetch_protocol_binary(THD *thd_arg)
:protocol(thd_arg)
{}
-bool Select_fetch_protocol_prep::send_fields(List<Item> &list, uint flags)
+bool Select_fetch_protocol_binary::send_fields(List<Item> &list, uint flags)
{
bool rc;
Protocol *save_protocol= thd->protocol;
@@ -2664,19 +2789,15 @@ bool Select_fetch_protocol_prep::send_fields(List<Item> &list, uint flags)
return rc;
}
-bool Select_fetch_protocol_prep::send_eof()
+bool Select_fetch_protocol_binary::send_eof()
{
- Protocol *save_protocol= thd->protocol;
-
- thd->protocol= &protocol;
- ::send_eof(thd);
- thd->protocol= save_protocol;
+ ::my_eof(thd);
return FALSE;
}
bool
-Select_fetch_protocol_prep::send_data(List<Item> &fields)
+Select_fetch_protocol_binary::send_data(List<Item> &fields)
{
Protocol *save_protocol= thd->protocol;
bool rc;
@@ -2692,7 +2813,7 @@ Select_fetch_protocol_prep::send_data(List<Item> &fields)
****************************************************************************/
Prepared_statement::Prepared_statement(THD *thd_arg, Protocol *protocol_arg)
- :Statement(&main_lex, &main_mem_root,
+ :Statement(NULL, &main_mem_root,
INITIALIZED, ++thd_arg->statement_id_counter),
thd(thd_arg),
result(thd_arg),
@@ -2700,7 +2821,8 @@ Prepared_statement::Prepared_statement(THD *thd_arg, Protocol *protocol_arg)
param_array(0),
param_count(0),
last_errno(0),
- flags((uint) IS_IN_USE)
+ flags((uint) IS_IN_USE),
+ m_sp_cache_version(0)
{
init_sql_alloc(&main_mem_root, thd_arg->variables.query_alloc_block_size,
thd_arg->variables.query_prealloc_size);
@@ -2710,15 +2832,26 @@ Prepared_statement::Prepared_statement(THD *thd_arg, Protocol *protocol_arg)
void Prepared_statement::setup_set_params()
{
- /* Setup binary logging */
+ /*
+ Note: BUG#25843 applies here too (query cache lookup uses thd->db, not
+ db from "prepare" time).
+ */
+ if (query_cache_maybe_disabled(thd)) // we won't expand the query
+ lex->safe_to_cache_query= FALSE; // so don't cache it at Execution
+
+ /*
+ Decide if we have to expand the query (because we must write it to logs or
+ because we want to look it up in the query cache) or not.
+ */
if (mysql_bin_log.is_open() && is_update_query(lex->sql_command) ||
- mysql_log.is_open() || mysql_slow_log.is_open())
+ opt_log || opt_slow_log ||
+ query_cache_is_cacheable_query(lex))
{
set_params_from_vars= insert_params_from_vars_with_log;
#ifndef EMBEDDED_LIBRARY
- set_params= insert_params_withlog;
+ set_params= insert_params_with_log;
#else
- set_params_data= emb_insert_params_withlog;
+ set_params_data= emb_insert_params_with_log;
#endif
}
else
@@ -2733,25 +2866,30 @@ void Prepared_statement::setup_set_params()
}
-/*
- DESCRIPTION
- Destroy this prepared statement, cleaning up all used memory
- and resources. This is called from ::deallocate() to
- handle COM_STMT_CLOSE and DEALLOCATE PREPARE or when
- THD ends and all prepared statements are freed.
+/**
+ Destroy this prepared statement, cleaning up all used memory
+ and resources.
+
+ This is called from ::deallocate() to handle COM_STMT_CLOSE and
+ DEALLOCATE PREPARE or when THD ends and all prepared statements are freed.
*/
Prepared_statement::~Prepared_statement()
{
DBUG_ENTER("Prepared_statement::~Prepared_statement");
- DBUG_PRINT("enter",("stmt: %p cursor: %p", this, cursor));
+ DBUG_PRINT("enter",("stmt: 0x%lx cursor: 0x%lx",
+ (long) this, (long) cursor));
delete cursor;
/*
We have to call free on the items even if cleanup is called as some items,
like Item_param, don't free everything until free_items()
*/
free_items();
- delete lex->result;
+ if (lex)
+ {
+ delete lex->result;
+ delete (st_lex_local *) lex;
+ }
free_root(&main_mem_root, MYF(0));
DBUG_VOID_RETURN;
}
@@ -2766,7 +2904,7 @@ Query_arena::Type Prepared_statement::type() const
void Prepared_statement::cleanup_stmt()
{
DBUG_ENTER("Prepared_statement::cleanup_stmt");
- DBUG_PRINT("enter",("stmt: %p", this));
+ DBUG_PRINT("enter",("stmt: 0x%lx", (long) this));
DBUG_ASSERT(lex->sphead == 0);
/* The order is important */
@@ -2783,10 +2921,38 @@ void Prepared_statement::cleanup_stmt()
bool Prepared_statement::set_name(LEX_STRING *name_arg)
{
name.length= name_arg->length;
- name.str= memdup_root(mem_root, (char*) name_arg->str, name_arg->length);
+ name.str= (char*) memdup_root(mem_root, name_arg->str, name_arg->length);
return name.str == 0;
}
+
+/**
+ Remember the current database.
+
+ We must reset/restore the current database during execution of
+ a prepared statement since it affects execution environment:
+ privileges, @@character_set_database, and other.
+
+ @return Returns an error if out of memory.
+*/
+
+bool
+Prepared_statement::set_db(const char *db_arg, uint db_length_arg)
+{
+ /* Remember the current database. */
+ if (db_arg && db_length_arg)
+ {
+ db= this->strmake(db_arg, db_length_arg);
+ db_length= db_length_arg;
+ }
+ else
+ {
+ db= NULL;
+ db_length= 0;
+ }
+ return db_arg != NULL && db == NULL;
+}
+
/**************************************************************************
Common parts of mysql_[sql]_stmt_prepare, mysql_[sql]_stmt_execute.
Essentially, these functions do all the magic of preparing/executing
@@ -2794,28 +2960,24 @@ bool Prepared_statement::set_name(LEX_STRING *name_arg)
global THD state management to the caller.
***************************************************************************/
-/*
+/**
Parse statement text, validate the statement, and prepare it for execution.
- SYNOPSIS
- Prepared_statement::prepare()
- packet statement text
- packet_len
-
- DESCRIPTION
You should not change global THD state in this function, if at all
possible: it may be called from any context, e.g. when executing
a COM_* command, and SQLCOM_* command, or a stored procedure.
- NOTES
- Precondition.
- -------------
+ @param packet statement text
+ @param packet_len
+
+ @note
+ Precondition:
The caller must ensure that thd->change_list and thd->free_list
is empty: this function will not back them up but will free
in the end of its execution.
- Postcondition.
- --------------
+ @note
+ Postcondition:
thd->mem_root contains unused memory allocated during validation.
*/
@@ -2830,7 +2992,13 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
However, it seems handy if com_stmt_prepare is increased always,
no matter what kind of prepare is processed.
*/
- statistic_increment(thd->status_var.com_stmt_prepare, &LOCK_status);
+ status_var_increment(thd->status_var.com_stmt_prepare);
+
+ if (! (lex= new (mem_root) st_lex_local))
+ DBUG_RETURN(TRUE);
+
+ if (set_db(thd->db, thd->db_length))
+ DBUG_RETURN(TRUE);
/*
alloc_query() uses thd->memroot && thd->query, so we should call
@@ -2851,15 +3019,13 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
Parser_state parser_state(thd, thd->query, thd->query_length);
parser_state.m_lip.stmt_prepare_mode= TRUE;
- thd->m_parser_state= &parser_state;
lex_start(thd);
- lex->safe_to_cache_query= FALSE;
- int err= MYSQLparse((void *)thd);
- thd->m_parser_state= NULL;
- lex->set_trg_event_type_for_tables();
- error= err || thd->is_fatal_error ||
- thd->net.report_error || init_param_array(this);
+ error= parse_sql(thd, & parser_state, NULL) ||
+ thd->is_error() ||
+ init_param_array(this);
+
+ lex->set_trg_event_type_for_tables();
/*
While doing context analysis of the query (in check_prepared_statement)
@@ -2884,7 +3050,7 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
*/
if (error == 0)
- error= check_prepared_statement(this, name.str != 0);
+ error= check_prepared_statement(this);
/*
Currently CREATE PROCEDURE/TRIGGER/EVENT are prohibited in prepared
@@ -2909,6 +3075,20 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
init_stmt_after_parse(lex);
state= Query_arena::PREPARED;
flags&= ~ (uint) IS_IN_USE;
+ /*
+ This is for prepared statement validation purposes.
+ A statement looks up and pre-loads all its stored functions
+ at prepare. Later on, if a function is gone from the cache,
+ execute may fail.
+ Remember the cache version to be able to invalidate the prepared
+ statement at execute if it changes.
+ We only need to care about version of the stored functions cache:
+ if a prepared statement uses a stored procedure, it's indirect,
+ via a stored function. The only exception is SQLCOM_CALL,
+ but the latter one looks up the stored procedure each time
+ it's invoked, rather than once at prepare.
+ */
+ m_sp_cache_version= sp_cache_version(&thd->sp_func_cache);
/*
Log COM_EXECUTE to the general log. Note, that in case of SQL
@@ -2926,38 +3106,330 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
the general log.
*/
if (thd->spcont == NULL)
- {
- const char *format= "[%lu] %.*b";
- mysql_log.write(thd, COM_STMT_PREPARE, format, id,
- query_length, query);
-
- }
+ general_log_write(thd, COM_STMT_PREPARE, query, query_length);
}
DBUG_RETURN(error);
}
-/*
- Execute a prepared statement.
- SYNOPSIS
- Prepared_statement::execute()
- expanded_query A query for binlogging which has all parameter
- markers ('?') replaced with their actual values.
- open_cursor True if an attempt to open a cursor should be made.
- Currenlty used only in the binary protocol.
+/**
+ Assign parameter values either from variables, in case of SQL PS
+ or from the execute packet.
+
+ @param expanded_query a container with the original SQL statement.
+ '?' placeholders will be replaced with
+ their values in case of success.
+ The result is used for logging and replication
+ @param packet pointer to execute packet.
+ NULL in case of SQL PS
+ @param packet_end end of the packet. NULL in case of SQL PS
+
+ @todo Use a paremeter source class family instead of 'if's, and
+ support stored procedure variables.
+
+ @retval TRUE an error occurred when assigning a parameter (likely
+ a conversion error or out of memory, or malformed packet)
+ @retval FALSE success
+*/
+
+bool
+Prepared_statement::set_parameters(String *expanded_query,
+ uchar *packet, uchar *packet_end)
+{
+ bool is_sql_ps= packet == NULL;
+ bool res= FALSE;
+
+ if (is_sql_ps)
+ {
+ /* SQL prepared statement */
+ res= set_params_from_vars(this, thd->lex->prepared_stmt_params,
+ expanded_query);
+ }
+ else if (param_count)
+ {
+#ifndef EMBEDDED_LIBRARY
+ uchar *null_array= packet;
+ res= (setup_conversion_functions(this, &packet, packet_end) ||
+ set_params(this, null_array, packet, packet_end, expanded_query));
+#else
+ /*
+ In embedded library we re-install conversion routines each time
+ we set parameters, and also we don't need to parse packet.
+ So we do it in one function.
+ */
+ res= set_params_data(this, expanded_query);
+#endif
+ }
+ if (res)
+ {
+ my_error(ER_WRONG_ARGUMENTS, MYF(0),
+ is_sql_ps ? "EXECUTE" : "mysql_stmt_execute");
+ reset_stmt_params(this);
+ }
+ return res;
+}
+
+
+/**
+ Execute a prepared statement. Re-prepare it a limited number
+ of times if necessary.
+
+ Try to execute a prepared statement. If there is a metadata
+ validation error, prepare a new copy of the prepared statement,
+ swap the old and the new statements, and try again.
+ If there is a validation error again, repeat the above, but
+ perform no more than MAX_REPREPARE_ATTEMPTS.
+
+ @note We have to try several times in a loop since we
+ release metadata locks on tables after prepared statement
+ prepare. Therefore, a DDL statement may sneak in between prepare
+ and execute of a new statement. If this happens repeatedly
+ more than MAX_REPREPARE_ATTEMPTS times, we give up.
+
+ In future we need to be able to keep the metadata locks between
+ prepare and execute, but right now open_and_lock_tables(), as
+ well as close_thread_tables() are buried deep inside
+ execution code (mysql_execute_command()).
+
+ @return TRUE if an error, FALSE if success
+ @retval TRUE either MAX_REPREPARE_ATTEMPTS has been reached,
+ or some general error
+ @retval FALSE successfully executed the statement, perhaps
+ after having reprepared it a few times.
+*/
+
+bool
+Prepared_statement::execute_loop(String *expanded_query,
+ bool open_cursor,
+ uchar *packet,
+ uchar *packet_end)
+{
+ const int MAX_REPREPARE_ATTEMPTS= 3;
+ Reprepare_observer reprepare_observer;
+ bool error;
+ int reprepare_attempt= 0;
+
+ if (set_parameters(expanded_query, packet, packet_end))
+ return TRUE;
+
+reexecute:
+ reprepare_observer.reset_reprepare_observer();
+
+ /*
+ If the free_list is not empty, we'll wrongly free some externally
+ allocated items when cleaning up after validation of the prepared
+ statement.
+ */
+ DBUG_ASSERT(thd->free_list == NULL);
+
+ /*
+ Install the metadata observer. If some metadata version is
+ different from prepare time and an observer is installed,
+ the observer method will be invoked to push an error into
+ the error stack.
+ */
+ if (sql_command_flags[lex->sql_command] &
+ CF_REEXECUTION_FRAGILE)
+ {
+ DBUG_ASSERT(thd->m_reprepare_observer == NULL);
+ thd->m_reprepare_observer = &reprepare_observer;
+ }
+
+ if (!(specialflag & SPECIAL_NO_PRIOR))
+ my_pthread_setprio(pthread_self(),QUERY_PRIOR);
+
+ error= execute(expanded_query, open_cursor) || thd->is_error();
+
+ if (!(specialflag & SPECIAL_NO_PRIOR))
+ my_pthread_setprio(pthread_self(), WAIT_PRIOR);
+
+ thd->m_reprepare_observer= NULL;
+
+ if (error && !thd->is_fatal_error && !thd->killed &&
+ reprepare_observer.is_invalidated() &&
+ reprepare_attempt++ < MAX_REPREPARE_ATTEMPTS)
+ {
+ DBUG_ASSERT(thd->main_da.sql_errno() == ER_NEED_REPREPARE);
+ thd->clear_error();
+
+ error= reprepare();
+
+ if (! error) /* Success */
+ goto reexecute;
+ }
+ reset_stmt_params(this);
+
+ return error;
+}
+
+
+/**
+ Reprepare this prepared statement.
+
+ Currently this is implemented by creating a new prepared
+ statement, preparing it with the original query and then
+ swapping the new statement and the original one.
+
+ @retval TRUE an error occurred. Possible errors include
+ incompatibility of new and old result set
+ metadata
+ @retval FALSE success, the statement has been reprepared
+*/
+
+bool
+Prepared_statement::reprepare()
+{
+ char saved_cur_db_name_buf[NAME_LEN+1];
+ LEX_STRING saved_cur_db_name=
+ { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
+ LEX_STRING stmt_db_name= { db, db_length };
+ bool cur_db_changed;
+ bool error;
+
+ Prepared_statement copy(thd, &thd->protocol_text);
+
+ status_var_increment(thd->status_var.com_stmt_reprepare);
+
+ if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
+ &cur_db_changed))
+ return TRUE;
+
+ error= (name.str && copy.set_name(&name) ||
+ copy.prepare(query, query_length) ||
+ validate_metadata(&copy));
+
+ if (cur_db_changed)
+ mysql_change_db(thd, &saved_cur_db_name, TRUE);
+
+ if (! error)
+ {
+ swap_prepared_statement(&copy);
+ swap_parameter_array(param_array, copy.param_array, param_count);
+#ifndef DBUG_OFF
+ is_reprepared= TRUE;
+#endif
+ /*
+ Clear possible warnings during reprepare, it has to be completely
+ transparent to the user. We use mysql_reset_errors() since
+ there were no separate query id issued for re-prepare.
+ Sic: we can't simply silence warnings during reprepare, because if
+ it's failed, we need to return all the warnings to the user.
+ */
+ mysql_reset_errors(thd, TRUE);
+ }
+ return error;
+}
+
+
+/**
+ Validate statement result set metadata (if the statement returns
+ a result set).
+
+ Currently we only check that the number of columns of the result
+ set did not change.
+ This is a helper method used during re-prepare.
+
+ @param[in] copy the re-prepared prepared statement to verify
+ the metadata of
+
+ @retval TRUE error, ER_PS_REBIND is reported
+ @retval FALSE statement return no or compatible metadata
+*/
+
+
+bool Prepared_statement::validate_metadata(Prepared_statement *copy)
+{
+ /**
+ If this is an SQL prepared statement or EXPLAIN,
+ return FALSE -- the metadata of the original SELECT,
+ if any, has not been sent to the client.
+ */
+ if (is_protocol_text() || lex->describe)
+ return FALSE;
+
+ if (lex->select_lex.item_list.elements !=
+ copy->lex->select_lex.item_list.elements)
+ {
+ /** Column counts mismatch, update the client */
+ thd->server_status|= SERVER_STATUS_METADATA_CHANGED;
+ }
+
+ return FALSE;
+}
+
+
+/**
+ Replace the original prepared statement with a prepared copy.
+
+ This is a private helper that is used as part of statement
+ reprepare
+
+ @return This function does not return any errors.
+*/
+
+void
+Prepared_statement::swap_prepared_statement(Prepared_statement *copy)
+{
+ Statement tmp_stmt;
+
+ /* Swap memory roots. */
+ swap_variables(MEM_ROOT, main_mem_root, copy->main_mem_root);
+
+ /* Swap the arenas */
+ tmp_stmt.set_query_arena(this);
+ set_query_arena(copy);
+ copy->set_query_arena(&tmp_stmt);
+
+ /* Swap the statement parent classes */
+ tmp_stmt.set_statement(this);
+ set_statement(copy);
+ copy->set_statement(&tmp_stmt);
+
+ /* Swap ids back, we need the original id */
+ swap_variables(ulong, id, copy->id);
+ /* Swap mem_roots back, they must continue pointing at the main_mem_roots */
+ swap_variables(MEM_ROOT *, mem_root, copy->mem_root);
+ /*
+ Swap the old and the new parameters array. The old array
+ is allocated in the old arena.
+ */
+ swap_variables(Item_param **, param_array, copy->param_array);
+ /* Swap flags: this is perhaps unnecessary */
+ swap_variables(uint, flags, copy->flags);
+ /* Swap names, the old name is allocated in the wrong memory root */
+ swap_variables(LEX_STRING, name, copy->name);
+ /* Ditto */
+ swap_variables(char *, db, copy->db);
+ swap_variables(ulong, m_sp_cache_version, copy->m_sp_cache_version);
+
+ DBUG_ASSERT(db_length == copy->db_length);
+ DBUG_ASSERT(param_count == copy->param_count);
+ DBUG_ASSERT(thd == copy->thd);
+ last_error[0]= '\0';
+ last_errno= 0;
+ /* Do not swap protocols, the copy always has protocol_text */
+}
+
+
+/**
+ Execute a prepared statement.
- DESCRIPTION
You should not change global THD state in this function, if at all
possible: it may be called from any context, e.g. when executing
a COM_* command, and SQLCOM_* command, or a stored procedure.
- NOTES
- Preconditions, postconditions.
- ------------------------------
- See the comment for Prepared_statement::prepare().
+ @param expanded_query A query for binlogging which has all parameter
+ markers ('?') replaced with their actual values.
+ @param open_cursor True if an attempt to open a cursor should be made.
+ Currenlty used only in the binary protocol.
- RETURN
- FALSE ok
+ @note
+ Preconditions, postconditions.
+ - See the comment for Prepared_statement::prepare().
+
+ @retval
+ FALSE ok
+ @retval
TRUE Error
*/
@@ -2967,7 +3439,14 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
Query_arena *old_stmt_arena;
bool error= TRUE;
- statistic_increment(thd->status_var.com_stmt_execute, &LOCK_status);
+ char saved_cur_db_name_buf[NAME_LEN+1];
+ LEX_STRING saved_cur_db_name=
+ { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
+ bool cur_db_changed;
+
+ LEX_STRING stmt_db_name= { db, db_length };
+
+ status_var_increment(thd->status_var.com_stmt_execute);
/* Check if we got an error when sending long data */
if (state == Query_arena::ERROR)
@@ -2982,6 +3461,19 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
}
/*
+ Reprepare the statement if we're using stored functions
+ and the version of the stored routines cache has changed.
+ */
+ if (lex->uses_stored_routines() &&
+ m_sp_cache_version != sp_cache_version(&thd->sp_func_cache) &&
+ thd->m_reprepare_observer &&
+ thd->m_reprepare_observer->report_error(thd))
+ {
+ return TRUE;
+ }
+
+
+ /*
For SHOW VARIABLES lex->result is NULL, as it's a non-SELECT
command. For such queries we don't return an error and don't
open a cursor -- the client library will recognize this case and
@@ -3015,9 +3507,24 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
*/
thd->set_n_backup_statement(this, &stmt_backup);
+
+ /*
+ Change the current database (if needed).
+
+ Force switching, because the database of the prepared statement may be
+ NULL (prepared statements can be created while no current database
+ selected).
+ */
+
+ if (mysql_opt_change_db(thd, &stmt_db_name, &saved_cur_db_name, TRUE,
+ &cur_db_changed))
+ goto error;
+
+ /* Allocate query. */
+
if (expanded_query->length() &&
alloc_query(thd, (char*) expanded_query->ptr(),
- expanded_query->length()+1))
+ expanded_query->length()))
{
my_error(ER_OUTOFMEMORY, 0, expanded_query->length());
goto error;
@@ -3031,12 +3538,6 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
stmt_backup.query_length= thd->query_length;
/*
- Save orig_sql_command as we use it to disable slow logging for SHOW
- commands (see log_slow_statement()).
- */
- stmt_backup.lex->orig_sql_command= thd->lex->orig_sql_command;
-
- /*
At first execution of prepared statement we may perform logical
transformations of the query tree. Such changes should be performed
on the parse tree of current prepared statement and new items should
@@ -3048,20 +3549,44 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
reinit_stmt_before_use(thd, lex);
thd->protocol= protocol; /* activate stmt protocol */
- error= (open_cursor ?
- mysql_open_cursor(thd, (uint) ALWAYS_MATERIALIZED_CURSOR,
- &result, &cursor) :
- mysql_execute_command(thd));
- thd->protocol= &thd->protocol_simple; /* use normal protocol */
+
+ /* Go! */
+
+ if (open_cursor)
+ error= mysql_open_cursor(thd, (uint) ALWAYS_MATERIALIZED_CURSOR,
+ &result, &cursor);
+ else
+ {
+ /*
+ Try to find it in the query cache, if not, execute it.
+ Note that multi-statements cannot exist here (they are not supported in
+ prepared statements).
+ */
+ if (query_cache_send_result_to_client(thd, thd->query,
+ thd->query_length) <= 0)
+ {
+ error= mysql_execute_command(thd);
+ }
+ }
+
+ /*
+ Restore the current database (if changed).
+
+ Force switching back to the saved current database (if changed),
+ because it may be NULL. In this case, mysql_change_db() would generate
+ an error.
+ */
+
+ if (cur_db_changed)
+ mysql_change_db(thd, &saved_cur_db_name, TRUE);
+
+ thd->protocol= &thd->protocol_text; /* use normal protocol */
/* Assert that if an error, no cursor is open */
DBUG_ASSERT(! (error && cursor));
if (! cursor)
- {
cleanup_stmt();
- reset_stmt_params(this);
- }
thd->set_statement(&stmt_backup);
thd->stmt_arena= old_stmt_arena;
@@ -3085,11 +3610,7 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
the general log.
*/
if (error == 0 && thd->spcont == NULL)
- {
- const char *format= "[%lu] %.*b";
- mysql_log.write(thd, COM_STMT_EXECUTE, format, id,
- thd->query_length, thd->query);
- }
+ general_log_write(thd, COM_STMT_EXECUTE, thd->query, thd->query_length);
error:
flags&= ~ (uint) IS_IN_USE;
@@ -3097,18 +3618,12 @@ error:
}
-/* Common part of DEALLOCATE PREPARE and mysql_stmt_close */
+/** Common part of DEALLOCATE PREPARE and mysql_stmt_close. */
-bool Prepared_statement::deallocate()
+void Prepared_statement::deallocate()
{
/* We account deallocate in the same manner as mysql_stmt_close */
- statistic_increment(thd->status_var.com_stmt_close, &LOCK_status);
- if (flags & (uint) IS_IN_USE)
- {
- my_error(ER_PS_NO_RECURSION, MYF(0));
- return TRUE;
- }
+ status_var_increment(thd->status_var.com_stmt_close);
/* Statement map calls delete stmt on erase */
thd->stmt_map.erase(this);
- return FALSE;
}